// File: @hashflow/contracts-evm/contracts/interfaces/IHashflowRouter.sol



/**
 * SPDX-License-Identifier: UNLICENSED
 */
pragma solidity >=0.8.0;

import './IQuote.sol';

/// @title IHashflowRouter
/// @author Victor Ionescu
/**
 * @notice In terms of user-facing functionality, the Router is responsible for:
 * - orchestrating trades
 * - managing cross-chain permissions
 *
 * Every trade requires consent from two parties: the Trader and the Market Maker.
 * However, there are two models to establish consent:
 * - RFQ-T: in this model, the Market Maker provides an EIP-191 signature for the quote,
 *   while the Trader signs the transaction and submits it on-chain
 * - RFQ-M: in this model, the Trader provides an EIP-712 signature for the quote,
 *   the Market Maker provides an EIP-191 signature, and a 3rd party relays the trade.
 *   The 3rd party can be the Market Maker itself.
 *
 * In terms of Hashflow internals, the Router maintains a set of authorized pool
 * contracts that are allowed to be used for trading. This allowlist creates
 * guarantees against malicious behavior, as documented in specific places.
 *
 * The Router contract is not upgradeable. In order to change functionality, a new
 * Router has to be deployed, and new HashflowPool contracts have to be deployed
 * by the Market Makers.
 */
/// @dev Trade / liquidity events are emitted at the HashflowPool level, rather than the router.
interface IHashflowRouter is IQuote {
    /**
     * @notice X-Chain message received from an X-Chain Messenger. This is used by the
     * Router to communicate a fill to a HashflowPool.
     */
    struct XChainFillMessage {
        /// @notice The Hashflow Chain ID of the source chain.
        uint16 srcHashflowChainId;
        /// @notice The address of the HashflowPool on the source chain.
        bytes32 srcPool;
        /// @notice The HashflowPool to disburse funds on the destination chain.
        address dstPool;
        /**
         * @notice The external account linked to the HashflowPool on the destination chain.
         * If the HashflowPool holds funds, this should be bytes32(0).
         */
        address dstExternalAccount;
        /// @notice The recipient of the quoteToken on the destination chain.
        address dstTrader;
        /// @notice The token that the trader buys on the destination chain.
        address quoteToken;
        /// @notice The amount of quoteToken bought.
        uint256 quoteTokenAmount;
        /// @notice Unique identifier for the quote.
        /// @dev Generated off-chain via a distributed UUID generator.
        bytes32 txid;
        /// @notice The caller of the trade function on the source chain.
        bytes32 srcCaller;
        /// @notice The contract to call, if any.
        address dstContract;
        /// @notice The calldata for the contract.
        bytes dstContractCalldata;
    }

    /// @notice Emitted when the authorization status of a pool changes.
    /// @param pool The pool whose status changed.
    /// @param authorized The new auth status.
    event UpdatePoolAuthorizaton(address pool, bool authorized);

    /// @notice Emitted when a sender pool authorization changes.
    /// @param pool Pool address on this chain.
    /// @param otherHashflowChainId Hashflow Chain ID of the other chain.
    /// @param otherChainPool Pool address on the other chain.
    /// @param authorized Whether the pool is authorized.
    event UpdateXChainPoolAuthorization(
        address indexed pool,
        uint16 otherHashflowChainId,
        bytes32 otherChainPool,
        bool authorized
    );

    /// @notice Emitted when the authorization of an x-caller changes.
    /// @param pool Pool address on this chain.
    /// @param otherHashflowChainId Hashflow Chain ID of the other chain.
    /// @param caller Caller address on the other chain.
    /// @param authorized Whether the caller is authorized.
    event UpdateXChainCallerAuthorization(
        address indexed pool,
        uint16 otherHashflowChainId,
        bytes32 caller,
        bool authorized
    );

    /// @notice Emitted when the authorization status of an X-Chain Messenger changes for a pool.
    /// @param pool Pool address for which the Messenger authorization changes.
    /// @param xChainMessenger Address of the Messenger.
    /// @param authorized Whether the X-Chain Messenger is authorized.
    event UpdateXChainMessengerAuthorization(
        address indexed pool,
        address xChainMessenger,
        bool authorized
    );

    /// @notice Emitted when the authorized status of an X-Chain Messenger changes for a callee.
    /// @param callee Address of the callee.
    /// @param xChainMessenger Address of the Messenger.
    /// @param authorized Whether the X-Chain Messenger is authorized.
    event UpdateXChainMessengerCallerAuthorization(
        address indexed callee,
        address xChainMessenger,
        bool authorized
    );

    /// @notice Emitted when the Limit Order Guardian address is updated.
    /// @param guardian The new Guardian address.
    event UpdateLimitOrderGuardian(address guardian);

    /// @notice Initializes the Router. Called one time.
    /// @param factory The address of the HashflowFactory contract.
    function initialize(address factory) external;

    /// @notice Returns the address of the associated HashflowFactor contract.
    function factory() external view returns (address);

    function authorizedXChainPools(
        bytes32 dstPool,
        uint16 srcHChainId,
        bytes32 srcPool
    ) external view returns (bool);

    function authorizedXChainCallers(
        address dstContract,
        uint16 srcHashflowChainId,
        bytes32 caller
    ) external view returns (bool);

    function authorizedXChainMessengersByPool(address pool, address messenger)
        external
        view
        returns (bool);

    function authorizedXChainMessengersByCallee(
        address callee,
        address messenger
    ) external view returns (bool);

    /// @notice Executes an intra-chain RFQ-T trade.
    /// @param quote The quote data to be executed.
    function tradeRFQT(RFQTQuote memory quote) external payable;

    /// @notice Executes an intra-chain RFQ-T trade, leveraging an ERC-20 permit.
    /// @param quote The quote data to be executed.
    /// @dev Does not support native tokens for the baseToken.
    function tradeRFQTWithPermit(
        RFQTQuote memory quote,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s,
        uint256 amountToApprove
    ) external;

    /// @notice Executes an intra-chain RFQ-T trade.
    /// @param quote The quote to be executed.
    function tradeRFQM(RFQMQuote memory quote) external;

    /// @notice Executes an intra-chain RFQ-T trade, leveraging an ERC-20 permit.
    /// @param quote The quote to be executed.
    /// @param deadline The deadline of the ERC-20 permit.
    /// @param v v-part of the signature.
    /// @param r r-part of the signature.
    /// @param s s-part of the signature.
    /// @param amountToApprove The amount being approved.
    function tradeRFQMWithPermit(
        RFQMQuote memory quote,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s,
        uint256 amountToApprove
    ) external;

    /// @notice Executes an intra-chain RFQ-T trade.
    /// @param quote The quote to be executed.
    /// @param guardianSignature A signature issued by the Limit Order Guardian.
    function tradeRFQMLimitOrder(
        RFQMQuote memory quote,
        bytes memory guardianSignature
    ) external;

    /// @notice Executes an intra-chain RFQ-T trade, leveraging an ERC-20 permit.
    /// @param quote The quote to be executed.
    /// @param guardianSignature A signature issued by the Limit Order Guardian.
    /// @param deadline The deadline of the ERC-20 permit.
    /// @param v v-part of the signature.
    /// @param r r-part of the signature.
    /// @param s s-part of the signature.
    /// @param amountToApprove The amount being approved.
    function tradeRFQMLimitOrderWithPermit(
        RFQMQuote memory quote,
        bytes memory guardianSignature,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s,
        uint256 amountToApprove
    ) external;

    /// @notice Executes an RFQ-T cross-chain trade.
    /// @param quote The quote to be executed.
    /// @param dstContract The address of the contract to be called on the destination chain.
    /// @param dstCalldata The calldata for the smart contract call.
    function tradeXChainRFQT(
        XChainRFQTQuote memory quote,
        bytes32 dstContract,
        bytes memory dstCalldata
    ) external payable;

    /// @notice Executes an RFQ-T cross-chain trade, leveraging an ERC-20 permit.
    /// @param quote The quote to be executed.
    /// @param dstContract The address of the contract to be called on the destination chain.
    /// @param dstCalldata The calldata for the smart contract call.
    /// @param deadline The deadline of the ERC-20 permit.
    /// @param v v-part of the signature.
    /// @param r r-part of the signature.
    /// @param s s-part of the signature.
    /// @param amountToApprove The amount being approved.
    function tradeXChainRFQTWithPermit(
        XChainRFQTQuote memory quote,
        bytes32 dstContract,
        bytes memory dstCalldata,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s,
        uint256 amountToApprove
    ) external payable;

    /// @notice Executes an RFQ-M cross-chain trade.
    /// @param quote The quote to be executed.
    /// @param dstContract The address of the contract to be called on the destination chain.
    /// @param dstCalldata The calldata for the smart contract call.
    function tradeXChainRFQM(
        XChainRFQMQuote memory quote,
        bytes32 dstContract,
        bytes memory dstCalldata
    ) external payable;

    /// @notice Similar to tradeXChainRFQm, but includes a spend permit for the baseToken.
    /// @param quote The quote to be executed.
    /// @param dstContract The address of the contract to be called on the destination chain.
    /// @param dstCalldata The calldata for the smart contract call.
    /// @param deadline The deadline of the ERC-20 permit.
    /// @param v v-part of the signature.
    /// @param r r-part of the signature.
    /// @param s s-part of the signature.
    /// @param amountToApprove The amount to approve.
    function tradeXChainRFQMWithPermit(
        XChainRFQMQuote memory quote,
        bytes32 dstContract,
        bytes memory dstCalldata,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s,
        uint256 amountToApprove
    ) external payable;

    /// @notice Completes the second leg of a cross-chain trade.
    /// @param fillMessage Payload containing information necessary to complete the trade.
    function fillXChain(XChainFillMessage memory fillMessage) external;

    /// @notice Returns whether the pool is authorized for trading.
    /// @param pool The address of the HashflowPool.
    function authorizedPools(address pool) external view returns (bool);

    /// @notice Allows the owner to unauthorize a potentially compromised pool. Cannot be reverted.
    /// @param pool The address of the HashflowPool.
    function forceUnauthorizePool(address pool) external;

    /// @notice Authorizes a HashflowPool for trading.
    /// @dev Can only be called by the HashflowFactory or the admin.
    function updatePoolAuthorization(address pool, bool authorized) external;

    /// @notice Updates the authorization status of an X-Chain pool pair.
    /// @param otherHashflowChainId The Hashflow Chain ID of the peer chain.
    /// @param otherPool The 32-byte representation of the Pool address on the peer chain.
    /// @param authorized Whether the pool is authorized to communicate with the sender pool.
    function updateXChainPoolAuthorization(
        uint16 otherHashflowChainId,
        bytes32 otherPool,
        bool authorized
    ) external;

    /// @notice Updates the authorization status of an X-Chain caller.
    /// @param otherHashflowChainId The Hashflow Chain ID of the peer chain.
    /// @param caller The caller address.
    /// @param authorized Whether the caller is authorized to send an x-call to the sender pool.
    function updateXChainCallerAuthorization(
        uint16 otherHashflowChainId,
        bytes32 caller,
        bool authorized
    ) external;

    /// @notice Updates the authorization status of an X-Chain Messenger app.
    /// @param xChainMessenger The address of the Messenger App.
    /// @param authorized The new authorization status.
    function updateXChainMessengerAuthorization(
        address xChainMessenger,
        bool authorized
    ) external;

    /// @notice Updates the authorization status of an X-Chain Messenger app.
    /// @param xChainMessenger The address of the Messenger App.
    /// @param authorized The new authorization status.
    function updateXChainMessengerCallerAuthorization(
        address xChainMessenger,
        bool authorized
    ) external;

    /// @notice Used to stop all operations on a pool, in case of an emergency.
    /// @param pool The address of the HashflowPool.
    /// @param enabled Whether the pool is enabled.
    function killswitchPool(address pool, bool enabled) external;

    /// @notice Used to update the Limit Order Guardian.
    /// @param guardian The address of the new Guardian.
    function updateLimitOrderGuardian(address guardian) external;

    /// @notice Allows the owner to withdraw excess funds from the Router.
    /// @dev Under normal operations, the Router should not have excess funds.
    function withdrawFunds(address token) external;
}

// File: @hashflow/contracts-evm/contracts/interfaces/IQuote.sol



/**
 * SPDX-License-Identifier: UNLICENSED
 */
pragma solidity >=0.8.0;

/// @title IQuote
/// @author Victor Ionescu
/**
 * @notice Interface for quote structs used for trading. There are two major types of trades:
 * - intra-chain: atomic transactions within one chain
 * - cross-chain: multi-leg transactions between two chains, which utilize interoperability protocols
 *                such as Wormhole.
 *
 * Separately, there are two trading modes:
 * - RFQ-T: the trader signs the transaction, the market maker signs the quote
 * - RFQ-M: both the trader and Market Maker sign the quote, any relayer can sign the transaction
 */
interface IQuote {
    /// @notice Used for intra-chain RFQ-T trades.
    struct RFQTQuote {
        /// @notice The address of the HashflowPool to trade against.
        address pool;
        /**
         * @notice The external account linked to the HashflowPool.
         * If the HashflowPool holds funds, this should be address(0).
         */
        address externalAccount;
        /// @notice The recipient of the quoteToken at the end of the trade.
        address trader;
        /**
         * @notice The account "effectively" making the trade (ultimately receiving the funds).
         * This is commonly used by aggregators, where a proxy contract (the 'trader')
         * receives the quoteToken, and the effective trader is the user initiating the call.
         *
         * This field DOES NOT influence movement of funds. However, it is used to check against
         * quote replay.
         */
        address effectiveTrader;
        /// @notice The token that the trader sells.
        address baseToken;
        /// @notice The token that the trader buys.
        address quoteToken;
        /**
         * @notice The amount of baseToken sold in this trade. The exchange rate
         * is going to be preserved as the quoteTokenAmount / baseTokenAmount ratio.
         *
         * Most commonly, effectiveBaseTokenAmount will == baseTokenAmount.
         */
        uint256 effectiveBaseTokenAmount;
        /// @notice The max amount of baseToken sold.
        uint256 baseTokenAmount;
        /// @notice The amount of quoteToken bought when baseTokenAmount is sold.
        uint256 quoteTokenAmount;
        /// @notice The Unix timestamp (in seconds) when the quote expires.
        /// @dev This gets checked against block.timestamp.
        uint256 quoteExpiry;
        /// @notice The nonce used by this effectiveTrader. Nonces are used to protect against replay.
        uint256 nonce;
        /// @notice Unique identifier for the quote.
        /// @dev Generated off-chain via a distributed UUID generator.
        bytes32 txid;
        /// @notice Signature provided by the market maker (EIP-191).
        bytes signature;
    }

    /// @notice Used for intra-chain RFQ-M trades.
    struct RFQMQuote {
        /// @notice The address of the HashflowPool to trade against.
        address pool;
        /**
         * @notice The external account linked to the HashflowPool.
         * If the HashflowPool holds funds, this should be address(0).
         */
        address externalAccount;
        /// @notice The account that will be debited baseToken / credited quoteToken.
        address trader;
        /// @notice The token that the trader sells.
        address baseToken;
        /// @notice The token that the trader buys.
        address quoteToken;
        /// @notice The amount of baseToken sold.
        uint256 baseTokenAmount;
        /// @notice The amount of quoteToken bought.
        uint256 quoteTokenAmount;
        /// @notice The Unix timestamp (in seconds) when the quote expires.
        /// @dev This gets checked against block.timestamp.
        uint256 quoteExpiry;
        /// @notice Unique identifier for the quote.
        /// @dev Generated off-chain via a distributed UUID generator.
        bytes32 txid;
        /// @notice Signature provided by the trader (EIP-712).
        bytes takerSignature;
        /// @notice Signature provided by the market maker (EIP-191).
        bytes makerSignature;
    }

    /// @notice Used for cross-chain RFQ-T trades.
    struct XChainRFQTQuote {
        /// @notice The Hashflow Chain ID of the source chain.
        uint16 srcChainId;
        /// @notice The Hashflow Chain ID of the destination chain.
        uint16 dstChainId;
        /// @notice The address of the HashflowPool to trade against on the source chain.
        address srcPool;
        /// @notice The HashflowPool to disburse funds on the destination chain.
        /// @dev This is bytes32 in order to anticipate non-EVM chains.
        bytes32 dstPool;
        /**
         * @notice The external account linked to the HashflowPool on the source chain.
         * If the HashflowPool holds funds, this should be address(0).
         */
        address srcExternalAccount;
        /**
         * @notice The external account linked to the HashflowPool on the destination chain.
         * If the HashflowPool holds funds, this should be bytes32(0).
         */
        bytes32 dstExternalAccount;
        /// @notice The recipient of the quoteToken on the destination chain.
        bytes32 dstTrader;
        /// @notice The token that the trader sells on the source chain.
        address baseToken;
        /// @notice The token that the trader buys on the destination chain.
        bytes32 quoteToken;
        /**
         * @notice The amount of baseToken sold in this trade. The exchange rate
         * is going to be preserved as the quoteTokenAmount / baseTokenAmount ratio.
         *
         * Most commonly, effectiveBaseTokenAmount will == baseTokenAmount.
         */
        uint256 effectiveBaseTokenAmount;
        /// @notice The amount of baseToken sold.
        uint256 baseTokenAmount;
        /// @notice The amount of quoteToken bought.
        uint256 quoteTokenAmount;
        /**
         * @notice The Unix timestamp (in seconds) when the quote expire. Only enforced
         * on the source chain.
         */
        /// @dev This gets checked against block.timestamp.
        uint256 quoteExpiry;
        /// @notice The nonce used by this trader.
        uint256 nonce;
        /// @notice Unique identifier for the quote.
        /// @dev Generated off-chain via a distributed UUID generator.
        bytes32 txid;
        /**
         * @notice The address of the IHashflowXChainMessenger contract used for
         * cross-chain communication.
         */
        address xChainMessenger;
        /// @notice Signature provided by the market maker (EIP-191).
        bytes signature;
    }

    /// @notice Used for Cross-Chain RFQ-M trades.
    struct XChainRFQMQuote {
        /// @notice The Hashflow Chain ID of the source chain.
        uint16 srcChainId;
        /// @notice The Hashflow Chain ID of the destination chain.
        uint16 dstChainId;
        /// @notice The address of the HashflowPool to trade against on the source chain.
        address srcPool;
        /// @notice The HashflowPool to disburse funds on the destination chain.
        /// @dev This is bytes32 in order to anticipate non-EVM chains.
        bytes32 dstPool;
        /**
         * @notice The external account linked to the HashflowPool on the source chain.
         * If the HashflowPool holds funds, this should be address(0).
         */
        address srcExternalAccount;
        /**
         * @notice The external account linked to the HashflowPool on the destination chain.
         * If the HashflowPool holds funds, this should be bytes32(0).
         */
        bytes32 dstExternalAccount;
        /// @notice The account that will be debited baseToken on the source chain.
        address trader;
        /// @notice The recipient of the quoteToken on the destination chain.
        bytes32 dstTrader;
        /// @notice The token that the trader sells on the source chain.
        address baseToken;
        /// @notice The token that the trader buys on the destination chain.
        bytes32 quoteToken;
        /// @notice The amount of baseToken sold.
        uint256 baseTokenAmount;
        /// @notice The amount of quoteToken bought.
        uint256 quoteTokenAmount;
        /**
         * @notice The Unix timestamp (in seconds) when the quote expire. Only enforced
         * on the source chain.
         */
        /// @dev This gets checked against block.timestamp.
        uint256 quoteExpiry;
        /// @notice Unique identifier for the quote.
        /// @dev Generated off-chain via a distributed UUID generator.
        bytes32 txid;
        /**
         * @notice The address of the IHashflowXChainMessenger contract used for
         * cross-chain communication.
         */
        address xChainMessenger;
        /// @notice Signature provided by the trader (EIP-712).
        bytes takerSignature;
        /// @notice Signature provided by the market maker (EIP-191).
        bytes makerSignature;
    }
}

// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165Upgradeable.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721Upgradeable is IERC165Upgradeable {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

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

// File: @openzeppelin/contracts/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
     * 0 before setting it to a non-zero value.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

// File: @openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// File: @openzeppelin/contracts/utils/Address.sol



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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

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

// File: contracts/core/RenovaQuest.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/Context.sol';

import '../interfaces/core/IRenovaCommandDeckBase.sol';
import '../interfaces/core/IRenovaQuest.sol';
import '../interfaces/nft/IRenovaAvatarBase.sol';

/// @title RenovaQuest
/// @author Victor Ionescu
/// @notice See {IRenovaQuest}
contract RenovaQuest is IRenovaQuest, Context, ReentrancyGuard {
    using SafeERC20 for IERC20;
    using Address for address payable;

    address private immutable _renovaCommandDeck;
    address private immutable _renovaAvatar;
    address private immutable _hashflowRouter;

    /// @inheritdoc IRenovaQuest
    uint256 public immutable startTime;

    /// @inheritdoc IRenovaQuest
    uint256 public immutable endTime;

    /// @inheritdoc IRenovaQuest
    address public immutable depositToken;

    /// @inheritdoc IRenovaQuest
    uint256 public immutable minDepositAmount;

    /// @inheritdoc IRenovaQuest
    address public immutable questOwner;

    /// @inheritdoc IRenovaQuest
    mapping(address => bool) public registered;

    /// @inheritdoc IRenovaQuest
    mapping(address => bool) public allowedTokens;

    /// @inheritdoc IRenovaQuest
    uint256 public numRegisteredPlayers;

    /// @inheritdoc IRenovaQuest
    mapping(address => mapping(address => uint256))
        public portfolioTokenBalances;

    uint256 public constant MAX_QUEST_LENGTH = (1 days) * 31 * 4;

    constructor(
        address renovaAvatar,
        address hashflowRouter,
        uint256 _startTime,
        uint256 _endTime,
        address _depositToken,
        uint256 _minDepositAmount,
        address _questOwner
    ) {
        _renovaCommandDeck = _msgSender();

        require(
            _startTime > block.timestamp,
            'RenovaQuest::constructor Start time should be in the future.'
        );
        require(
            _endTime > _startTime,
            'RenovaQuest::constructor End time should be after start time.'
        );
        require(
            (_endTime - _startTime) <= MAX_QUEST_LENGTH,
            'RenovaQuest::constructor Quest too long.'
        );

        startTime = _startTime;
        endTime = _endTime;
        depositToken = _depositToken;
        minDepositAmount = _minDepositAmount;

        allowedTokens[depositToken] = true;

        questOwner = _questOwner;

        _renovaAvatar = renovaAvatar;
        _hashflowRouter = hashflowRouter;

        emit UpdateTokenAuthorizationStatus(depositToken, true);
    }

    /// @dev Fallback function to receive native token.
    receive() external payable {}

    /// @inheritdoc IRenovaQuest
    function updateTokenAuthorization(
        address token,
        bool status
    ) external override {
        require(
            _msgSender() == questOwner,
            'RenovaQuest::updateTokenAuthorization Sender must be quest owner.'
        );

        allowedTokens[token] = status;

        emit UpdateTokenAuthorizationStatus(token, status);
    }

    /// @inheritdoc IRenovaQuest
    function depositAndEnter(
        uint256 depositAmount
    ) external payable override nonReentrant {
        _depositAndEnter(_msgSender(), depositAmount);
    }

    /// @inheritdoc IRenovaQuest
    function withdrawTokens(
        address[] memory tokens
    ) external override nonReentrant {
        for (uint256 i = 0; i < tokens.length; i++) {
            uint256 amount = portfolioTokenBalances[_msgSender()][tokens[i]];
            if (amount == 0) {
                continue;
            }
            portfolioTokenBalances[_msgSender()][tokens[i]] = 0;

            emit WithdrawToken(_msgSender(), tokens[i], amount);

            if (tokens[i] == address(0)) {
                payable(_msgSender()).sendValue(amount);
            } else {
                IERC20(tokens[i]).safeTransfer(_msgSender(), amount);
            }
        }
    }

    /// @inheritdoc IRenovaQuest
    function trade(
        IHashflowRouter.RFQTQuote memory quote
    ) external override nonReentrant {
        require(
            block.timestamp >= startTime && block.timestamp < endTime,
            'RenovaQuest::trade Quest is not ongoing.'
        );
        require(
            allowedTokens[quote.quoteToken],
            'RenovaQuest::trade Quote Token not allowed.'
        );

        require(
            registered[_msgSender()],
            'RenovaQuest::trade Player not registered.'
        );

        require(
            portfolioTokenBalances[_msgSender()][quote.baseToken] >=
                quote.effectiveBaseTokenAmount,
            'RenovaQuest::trade Insufficient balance'
        );

        require(
            quote.trader == address(this),
            'RenovaQuest::trade Trader should be Quest contract.'
        );

        require(
            quote.effectiveTrader == _msgSender(),
            'RenovaQuest::trade Effective Trader should be player.'
        );

        uint256 quoteTokenAmount = quote.quoteTokenAmount;
        if (quote.effectiveBaseTokenAmount < quote.baseTokenAmount) {
            quoteTokenAmount =
                (quote.effectiveBaseTokenAmount * quote.quoteTokenAmount) /
                quote.baseTokenAmount;
        }

        portfolioTokenBalances[_msgSender()][quote.baseToken] -= quote
            .effectiveBaseTokenAmount;
        portfolioTokenBalances[_msgSender()][
            quote.quoteToken
        ] += quoteTokenAmount;

        emit Trade(
            _msgSender(),
            quote.baseToken,
            quote.quoteToken,
            quote.effectiveBaseTokenAmount,
            quoteTokenAmount
        );

        uint256 msgValue = 0;

        if (quote.baseToken == address(0)) {
            msgValue = quote.effectiveBaseTokenAmount;
        } else {
            IERC20(quote.baseToken).forceApprove(
                _hashflowRouter,
                quote.effectiveBaseTokenAmount
            );
        }

        uint256 balanceBefore = _questBalanceOf(quote.quoteToken);

        IHashflowRouter(_hashflowRouter).tradeRFQT{value: msgValue}(quote);

        uint256 balanceAfter = _questBalanceOf(quote.quoteToken);

        require(
            balanceBefore + quoteTokenAmount == balanceAfter,
            'RenovaQuest::trade Did not receive enough quote token.'
        );
    }

    /// @notice Deposits tokens and registers the player for the Quest.
    /// @param player The address of the player depositing tokens.
    /// @param depositAmount The amount of token to deposit.
    function _depositAndEnter(address player, uint256 depositAmount) internal {
        require(
            block.timestamp < endTime,
            'RenovaQuest::_depositAndEnter Can only deposit before the quest ends.'
        );
        require(
            depositAmount >= minDepositAmount,
            'RenovaQuest::_depositAndEnter Deposit amount too low.'
        );
        require(
            !registered[player],
            'RenovaQuest::_depositAndEnter Player has already entered the quest.'
        );

        uint256 avatarTokenId = IRenovaAvatarBase(_renovaAvatar).tokenIds(
            player
        );
        require(
            avatarTokenId != 0,
            'RenovaQuest::_depositAndEnter Player has not minted Avatar.'
        );

        if (depositToken == address(0)) {
            require(
                msg.value == depositAmount,
                'RenovaQuest::_depositAndEnter msg.value should equal amount.'
            );
        } else {
            require(
                msg.value == 0,
                'RenovaQuest::_depositAndEnter msg.value should be 0.'
            );
        }

        registered[player] = true;
        portfolioTokenBalances[player][depositToken] += depositAmount;
        numRegisteredPlayers++;

        emit DepositToken(player, depositToken, depositAmount);
        emit RegisterPlayer(player);

        if (depositToken != address(0)) {
            uint256 balanceBefore = IERC20(depositToken).balanceOf(
                address(this)
            );

            IRenovaCommandDeckBase(_renovaCommandDeck).depositTokenForQuest(
                player,
                depositAmount
            );

            uint256 balanceAfter = IERC20(depositToken).balanceOf(
                address(this)
            );

            require(
                balanceAfter == balanceBefore + depositAmount,
                'RenovaQuest::_depositAndEnter Balance mismatch.'
            );
        }
    }

    /// @notice Returns the amount of token that this Quest currently holds.
    /// @param token The token to return the balance for.
    /// @return The balance.
    function _questBalanceOf(address token) internal view returns (uint256) {
        if (token == address(0)) {
            return address(this).balance;
        } else {
            return IERC20(token).balanceOf(address(this));
        }
    }
}

// File: contracts/interfaces/core/IRenovaCommandDeckBase.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

import './IRenovaQuest.sol';

/// @title IRenovaCommandDeckBase
/// @author Victor Ionescu
/**

The Command Deck contract is a central point of command in the Hashverse.
It handles:
- official contract addresses for the Item and the Avatar
- minting of Hashverse Items post Quest completion
- creation of Quests

The Command Deck exists on every chain, however only the main chain
Command Deck can mint items.
*/
interface IRenovaCommandDeckBase {
    /// @notice Emitted every time the Hashflow Router is updated.
    /// @param newRouter The address of the new Hashflow Router.
    /// @param oldRouter The address of the old Hashflow Router.
    event UpdateHashflowRouter(address newRouter, address oldRouter);

    /// @notice Emitted every time the Quest Owner changes.
    /// @param newQuestOwner The address of the new Quest Owner.
    /// @param oldQuestOwner The address of the old Quest Owner.
    event UpdateQuestOwner(address newQuestOwner, address oldQuestOwner);

    /// @notice Emitted every time a Quest is created.
    /// @param questId The Quest ID.
    /// @param questAddress The address of the contract handling the Quest logic.
    /// @param startTime The quest start time, in unix seconds.
    /// @param endTime The quest end time, in unix seconds.
    /// @param depositToken The token to be deposited to enter.
    /// @param minDepositAmount The minimum ampount to be deposited to enter.
    event CreateQuest(
        bytes32 questId,
        address questAddress,
        uint256 startTime,
        uint256 endTime,
        address depositToken,
        uint256 minDepositAmount
    );

    /// @notice Returns the Avatar contract address.
    /// @return The address of the Avatar contract.
    function renovaAvatar() external view returns (address);

    /// @notice Returns the Item contract address.
    /// @return The address of the Item contract.
    function renovaItem() external view returns (address);

    /// @notice Returns the Router contract address.
    /// @return The address of the Router contract.
    function hashflowRouter() external view returns (address);

    /// @notice Returns the Quest Owner address.
    /// @return The address of the Quest Owner.
    function questOwner() external view returns (address);

    /// @notice Returns the deployment contract address for a quest ID.
    /// @param questId The Quest ID.
    /// @return The deployed contract address if the quest ID is valid.
    function questDeploymentAddresses(
        bytes32 questId
    ) external view returns (address);

    /// @notice Returns the ID of a quest deployed at a particular address.
    /// @param questAddress The address of the Quest contract.
    /// @return The quest ID.
    function questIdsByDeploymentAddress(
        address questAddress
    ) external view returns (bytes32);

    /// @notice Deposits tokens into a Quest.
    /// @param player The address of the player depositing the tokens.
    /// @param depositAmount The deposit amount.
    /// @dev This function helps save gas by only setting allowance to this contract.
    function depositTokenForQuest(
        address player,
        uint256 depositAmount
    ) external;

    /// @notice Creates a Quest in the Hashverse.
    /// @param questId The Quest ID.
    /// @param startTime The quest start time, in Unix seconds.
    /// @param endTime The quest end time, in Unix seconds.
    /// @param depositToken The token that needs to be deposited in order for a player to enter.
    /// @param minDepositAmount The min amount deposited.
    function createQuest(
        bytes32 questId,
        uint256 startTime,
        uint256 endTime,
        address depositToken,
        uint256 minDepositAmount
    ) external;

    /// @notice Updates the Hashflow Router contract address.
    /// @param hashflowRouter The new Hashflow Router contract address.
    function updateHashflowRouter(address hashflowRouter) external;

    /// @notice Updates the Quest Owner address.
    /// @param questOwner The new Quest Owner address.
    function updateQuestOwner(address questOwner) external;
}

// File: contracts/interfaces/core/IRenovaQuest.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

import '@hashflow/contracts-evm/contracts/interfaces/IHashflowRouter.sol';
import '../nft/IRenovaAvatarBase.sol';

/// @title IRenovaQuest
/// @author Victor Ionescu
/**
@notice Contract that represents one Quest. Every Quest gets deployed by the Command Deck.

Quests have a start time and end time. Trading happens during those time bounds.

Quests each have a deposit token and a minimum deposit amount.
Only one deposit is allowed.

Deposits can occur at any time prior to quest end. Withdrawals can occur at any time.

Players register by depositing.
*/
interface IRenovaQuest {
    /// @notice Emitted when a token authorization status changes.
    /// @param token The address of the token.
    /// @param status Whether the token is allowed for trading.
    event UpdateTokenAuthorizationStatus(address token, bool status);

    /// @notice Emitted when a player registers for a quest.
    /// @param player The player registering for the quest.
    event RegisterPlayer(address indexed player);

    /// @notice Emitted when a player deposits a token for a Quest.
    /// @param player The player who deposits the token.
    /// @param token The address of the token (0x0 for native token).
    /// @param amount The amount of token being deposited.
    event DepositToken(address indexed player, address token, uint256 amount);

    /// @notice Emitted when a player withdraws a token from a Quest.
    /// @param player The player who withdraws the token.
    /// @param token The address of the token (0x0 for native token).
    /// @param amount The amount of token being withdrawn.
    event WithdrawToken(address indexed player, address token, uint256 amount);

    /// @notice Emitted when a player trades as part of the Quest.
    /// @param player The player who traded.
    /// @param baseToken The address of the token the player sold.
    /// @param quoteToken The address of the token the player bought.
    /// @param baseTokenAmount The amount sold.
    /// @param quoteTokenAmount The amount bought.
    event Trade(
        address indexed player,
        address baseToken,
        address quoteToken,
        uint256 baseTokenAmount,
        uint256 quoteTokenAmount
    );

    /// @notice Returns the Quest start time.
    /// @return The Quest start time.
    function startTime() external view returns (uint256);

    /// @notice Returns the Quest end time.
    /// @return The Quest end time.
    function endTime() external view returns (uint256);

    /// @notice Returns the token to deposit to enter.
    /// @return The address of the deposit token.
    function depositToken() external view returns (address);

    /// @notice Return the minimum deposit amount to enter.
    /// @return The minimum deposit amount.
    function minDepositAmount() external view returns (uint256);

    /// @notice Returns the address that has authority over the quest.
    /// @return The address that has authority over the quest.
    function questOwner() external view returns (address);

    /// @notice Returns whether a player has registered for the Quest.
    /// @param player The address of the player.
    /// @return Whether the player has registered.
    function registered(address player) external view returns (bool);

    /// @notice Used by the owner to allow / disallow a token for trading.
    /// @param token The address of the token.
    /// @param status The authorization status.
    function updateTokenAuthorization(address token, bool status) external;

    /// @notice Returns whether a token is allowed for deposits / trading.
    /// @param token The address of the token.
    /// @return Whether the token is allowed for trading.
    function allowedTokens(address token) external view returns (bool);

    /// @notice Returns the number of registered players.
    /// @return The number of registered players.
    function numRegisteredPlayers() external view returns (uint256);

    /// @notice Returns the token balance for each token the player has in the Quest.
    /// @param player The address of the player.
    /// @param token The address of the token.
    /// @return The player's token balance for this Quest.
    function portfolioTokenBalances(
        address player,
        address token
    ) external view returns (uint256);

    /// @notice Deposits tokens prior to the beginning of the Quest.
    /// @param depositAmount The amount of depositToken to deposit.
    function depositAndEnter(uint256 depositAmount) external payable;

    /// @notice Withdraws the full balance of the selected tokens from the Quest.
    /// @param tokens The addresses of the tokens to withdraw.
    function withdrawTokens(address[] memory tokens) external;

    /// @notice Trades within the Quest.
    /// @param quote The Hashflow Quote.
    function trade(IHashflowRouter.RFQTQuote memory quote) external;
}

// File: contracts/interfaces/external/erc/IERC4906Upgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol';

/// @title EIP-721 Metadata Update Extension
interface IERC4906Upgradeable is IERC165Upgradeable, IERC721Upgradeable {
    /// @dev This event emits when the metadata of a token is changed.
    /// So that the third-party platforms such as NFT market could
    /// timely update the images and related attributes of the NFT.
    event MetadataUpdate(uint256 _tokenId);

    /// @dev This event emits when the metadata of a range of tokens is changed.
    /// So that the third-party platforms such as NFT market could
    /// timely update the images and related attributes of the NFTs.
    event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
}

// File: contracts/interfaces/nft/IRenovaAvatarBase.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;

import '../external/erc/IERC4906Upgradeable.sol';

/// @title IRenovaAvatarBase
/// @author Victor Ionescu
/**
@notice NFT base contract holding Avatars. In order to play in the Hashverse players
have to mint an Avatar. Avatars are soul-bound (non-transferrable) and represent
the entirety of a player's journey in the Hashverse.

Avatars can be minted on multiple chains. Minting new Avatars can only happen on the
main chain. Once an Avatar is minted on the main chain, it can be minted on satellite
chains by making cross-chain calls.

Players have to mint Avatars on each chain if they want to enter a quest that is
occurring on that particular chain.
*/
interface IRenovaAvatarBase is IERC4906Upgradeable {
    enum RenovaFaction {
        RESISTANCE,
        SOLUS
    }

    /// @notice Emitted when an Avatar is minted.
    /// @param player The owner of the Avatar.
    /// @param tokenId The Token ID minted.
    /// @param faction The faction of the Avatar.
    /// @param characterId The character ID minted.
    event Mint(
        address indexed player,
        uint256 tokenId,
        RenovaFaction faction,
        uint256 characterId
    );

    /// @notice Emitted when the Custom Metadata URI is updated.
    /// @param uri The new URI.
    event UpdateCustomURI(string uri);

    /// @notice Returns the faction of a player.
    /// @param player The player.
    /// @return The faction.
    function factions(address player) external view returns (RenovaFaction);

    /// @notice Returns the character ID of a player.
    /// @param player The player.
    /// @return The character ID.
    function characterIds(address player) external view returns (uint256);

    /// @notice Returns the token ID of a player.
    /// @param player The player.
    /// @return The token ID.
    function tokenIds(address player) external view returns (uint256);

    /// @notice Sets a custom base URI for the token metadata.
    /// @param customBaseURI The new Custom URI.
    function setCustomBaseURI(string memory customBaseURI) external;

    /// @notice Emits a refresh metadata event for a token.
    /// @param tokenId The ID of the token.
    function refreshMetadata(uint256 tokenId) external;

    /// @notice Emits a refresh metadata event for all tokens.
    function refreshAllMetadata() external;
}