// File: WoofWorkStaking.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

/* STRUCTS */

struct Pool {
    uint232 tvl;
    uint24 participants;
}

struct Option {
    uint128 apr;
    uint128 range;
}

struct Staking {
    bool nft;
    uint16 tokenId;
    uint232 amount;
    uint256 end;
    uint256 earning;
    uint256 revenuePerSecond;
    Option option;
}

/* EVENTS */

event WoofSet(address woof);
event WoofworkerStakingDenied();
event WoofworkerStakingAllowed();
event WoofworkerAddressSet(address woofworkerAddress);
event OptionsUpdated(uint128[] aprs, uint128[] ranges);
event StakedWithoutNFT(address indexed wallet, uint256 amount, uint128 apr, uint128 range);
event UnstakeWithoutNFT(address indexed wallet, uint256 burnedAmount, uint256 withdrawnAmount);
event StakedWithNFT(address indexed wallet, uint96 indexed tokenId, uint256 amount, uint128 apr, uint128 range);
event UnstakeWithNFT(address indexed wallet, uint96 indexed tokenId, uint256 burnedAmount, uint256 withdrawnAmount);

/* ERRORS */

error NoContracts();
error NotStakedYet();
error NotTokenOwner();
error AlreadyStaked();
error NothingStaked();
error WithdrawFailed();
error NotAvailableYet();
error NotEnoughBalance();
error CoinTransferFailed();
error InvalidWoofworkerId();
error ExceedsOptionsLimit();
error InputsLengthsMismatch();
error WoofworkerAlreadyStaked();

/*
                                         __       __   ______    ______   ________  __       __   ______   _______   __    __                                                            
                                        |  \  _  |  \ /      \  /      \ |        \|  \  _  |  \ /      \ |       \ |  \  /  \                                                           
                                        | $$ / \ | $$|  $$$$$$\|  $$$$$$\| $$$$$$$$| $$ / \ | $$|  $$$$$$\| $$$$$$$\| $$ /  $$       __                                                  
                                        | $$/  $\| $$| $$  | $$| $$  | $$| $$__    | $$/  $\| $$| $$  | $$| $$__| $$| $$/  $$       |  \                                                 
                                        | $$  $$$\ $$| $$  | $$| $$  | $$| $$  \   | $$  $$$\ $$| $$  | $$| $$    $$| $$  $$         \$$                                                 
                                        | $$ $$\$$\$$| $$  | $$| $$  | $$| $$$$$   | $$ $$\$$\$$| $$  | $$| $$$$$$$\| $$$$$\         __                                                  
                                        | $$$$  \$$$$| $$__/ $$| $$__/ $$| $$      | $$$$  \$$$$| $$__/ $$| $$  | $$| $$ \$$\       |  \                                                 
                                        | $$$    \$$$ \$$    $$ \$$    $$| $$      | $$$    \$$$ \$$    $$| $$  | $$| $$  \$$\       \$$                                                 
                                         \$$      \$$  \$$$$$$   \$$$$$$  \$$       \$$      \$$  \$$$$$$  \$$   \$$ \$$   \$$                                                                                                                                                                                                                                                                                                                                                                                                                           
     __       __   ______    ______   ________              __        __       __   ______    ______   ________         ______  ________   ______   __    __  ______  __    __   ______  
    |  \  _  |  \ /      \  /      \ |        \            /  \      |  \  _  |  \ /      \  /      \ |        \       /      \|        \ /      \ |  \  /  \|      \|  \  |  \ /      \ 
    | $$ / \ | $$|  $$$$$$\|  $$$$$$\| $$$$$$$$           /  $$      | $$ / \ | $$|  $$$$$$\|  $$$$$$\| $$$$$$$$      |  $$$$$$\\$$$$$$$$|  $$$$$$\| $$ /  $$ \$$$$$$| $$\ | $$|  $$$$$$\
    | $$/  $\| $$| $$  | $$| $$  | $$| $$__              /  $$       | $$/  $\| $$| $$  | $$| $$  | $$| $$__          | $$___\$$  | $$   | $$__| $$| $$/  $$   | $$  | $$$\| $$| $$ __\$$
    | $$  $$$\ $$| $$  | $$| $$  | $$| $$  \            /  $$        | $$  $$$\ $$| $$  | $$| $$  | $$| $$  \          \$$    \   | $$   | $$    $$| $$  $$    | $$  | $$$$\ $$| $$|    \
    | $$ $$\$$\$$| $$  | $$| $$  | $$| $$$$$           /  $$         | $$ $$\$$\$$| $$  | $$| $$  | $$| $$$$$          _\$$$$$$\  | $$   | $$$$$$$$| $$$$$\    | $$  | $$\$$ $$| $$ \$$$$
    | $$$$  \$$$$| $$__/ $$| $$__/ $$| $$             /  $$          | $$$$  \$$$$| $$__/ $$| $$__/ $$| $$            |  \__| $$  | $$   | $$  | $$| $$ \$$\  _| $$_ | $$ \$$$$| $$__| $$
    | $$$    \$$$ \$$    $$ \$$    $$| $$            |  $$           | $$$    \$$$ \$$    $$ \$$    $$| $$             \$$    $$  | $$   | $$  | $$| $$  \$$\|   $$ \| $$  \$$$ \$$    $$
     \$$      \$$  \$$$$$$   \$$$$$$  \$$             \$$             \$$      \$$  \$$$$$$   \$$$$$$  \$$              \$$$$$$    \$$    \$$   \$$ \$$   \$$ \$$$$$$ \$$   \$$  \$$$$$$ 
                                                                                                                                                                                                                                                                                                                                                                                                                                                      
*/

/// @title Woofwork Staking WOOF (https://steaking.woofwork.io/)
/// @author bc.army (https://bc.army/)
/// @notice Platform to stake $WOOF (+ $WOOFWORKER) and earn revenue in $WOOF.
contract WoofworkStakingWOOF is Ownable, Pausable, ReentrancyGuard {
    /* INITIALIZATION */

    constructor() Ownable(msg.sender) {
    }

    /* MAPPINGS */

    mapping(uint256 => Option) private _options;
    mapping(address => Staking) private _stakings;

    /* VARIABLES */

    Pool private pool;
    bool private _nftStaking;
    IERC721 private $WOOFWORKER;

    uint80 private constant OPTIONS_LIMIT = 4;
    uint88 private constant UNIT_PERCENTAGE = 100;
    uint88 private constant PENALTY_PERCENTAGE = 10;

    IERC20 private $WOOF;
    uint96 private constant TOKEN_MAX_SUPPLY = 1000;

    uint96 private constant YEAR_TIMESTAMP = 365 days;
    address private constant DEAD_ADDRESS = address(0xdead);

    /* MODIFIERS */

    modifier noContracts() {
        if (msg.sender != tx.origin) revert NoContracts();
        _;
    }

    modifier canStakeWoofworker() {
        if (!_nftStaking) revert NotAvailableYet();
        _;
    }

    modifier isValidToken(uint256 tokenId) {
        if (tokenId == 0 || tokenId > TOKEN_MAX_SUPPLY) {
            revert InvalidWoofworkerId();
        }
        _;
    }

    modifier isTokenOwner(uint256 tokenId) {
        if (msg.sender != $WOOFWORKER.ownerOf(tokenId)) {
            revert NotTokenOwner();
        }
        _;
    }

    modifier isValidOption(uint256 optionId) {
        if (OPTIONS_LIMIT <= optionId) revert ExceedsOptionsLimit();
        _;
    }

    modifier checkWoofBalance(uint256 amount) {
        if ($WOOF.balanceOf(msg.sender) < amount) revert NotEnoughBalance();
        _;
    }

    /* GETTERS */

    function getPoolData() public view returns (Pool memory) {
        return pool;
    }

    function getWalletStakingData() public view returns (Staking memory) {
        return _stakings[msg.sender];
    }

    /* SETTERS */

    function pause() external payable onlyOwner {
        _pause();
    }

    function unpause() external payable onlyOwner {
        _unpause();
    }

    function setWoof(address woof) external payable onlyOwner {
        $WOOF = IERC20(woof);
        emit WoofSet(woof);
    }    

    function withdraw() external payable onlyOwner nonReentrant {
        (bool success,) = (msg.sender).call{value: address(this).balance}("");
        if (!success) revert WithdrawFailed();
    }

    function allowStakingWoofworker() external payable onlyOwner {
        _nftStaking = true;
        emit WoofworkerStakingAllowed();
    }

    function denyStakingWoofworker() external payable onlyOwner {
        _nftStaking = false;
        emit WoofworkerStakingDenied();
    }

    function setWoofworker(address woofworker) external payable onlyOwner {
        $WOOFWORKER = IERC721(woofworker);
        emit WoofworkerAddressSet(woofworker);
    }

    function updateOptions(uint128[] memory aprs, uint128[] memory ranges) external payable onlyOwner {
        uint256 length = aprs.length;
        if (length != ranges.length || length != OPTIONS_LIMIT) {
            revert InputsLengthsMismatch();
        }
        for (uint256 i; i < length;) {
            _options[i] = Option(aprs[i], ranges[i]);
            assembly {
                i := add(i, 1)
            }
        }
        emit OptionsUpdated(aprs, ranges);
    }

    /**
     * @dev Stake tokens for the first time.
     *
     * Requirements:
     *
     * - '_paused' must be false.
     * - 'optionId' must be in range.
     * - 'tx.origin' must be 'msg.sender' to avoid contract calls.
     * - user WOOF balance must be equal or greater than 'amount'.
     *
     * Emits a {StakedWithoutNFT} event.
     */
    function firstStakeWithoutNFT(uint24 optionId, uint232 amount)
        external
        payable
        noContracts
        nonReentrant
        whenNotPaused
        isValidOption(optionId)
        checkWoofBalance(amount)
    {
        // Get Staking Data
        Staking storage staking = _stakings[msg.sender];

        // Check Conditions
        if (staking.amount != 0) revert AlreadyStaked();

        // Execute Transfers
        if (!$WOOF.transferFrom(msg.sender, address(this), amount)) {
            revert CoinTransferFailed();
        }

        // Get Option Data
        Option memory option = _options[optionId];

        // Set Local Variables
        uint128 apr = option.apr;
        uint128 range = option.range;

        unchecked {
            // Update Staking Data
            staking.amount = amount;
            staking.option.apr = apr;
            staking.option.range = range;
            staking.end = block.timestamp + range;
            staking.revenuePerSecond = (amount * apr / UNIT_PERCENTAGE) / YEAR_TIMESTAMP;

            // Update Pool Data
            pool.tvl += amount;
            ++pool.participants;
        }

        // Emit Event
        emit StakedWithoutNFT(msg.sender, amount, apr, range);
    }

    /**
     * @dev Stake tokens and NFT for the first time.
     *
     * Requirements:
     *
     * - '_paused' must be false.
     * - 'optionId' must be in range.
     * - WOOF must be not already staked by user.
     * - 'tokenId' must exists and 'msg.sender' must be the owner.
     * - 'tx.origin' must be 'msg.sender' to avoid contract calls.
     * - user WOOF balance must be equal or greater than 'amount'.
     *
     * Emits a {StakedWithNFT} event.
     */
    function firstStakeWithNFT(uint8 optionId, uint16 tokenId, uint232 amount)
        external
        payable
        noContracts
        nonReentrant
        whenNotPaused
        canStakeWoofworker
        isValidToken(tokenId)
        isTokenOwner(tokenId)
        isValidOption(optionId)
        checkWoofBalance(amount)
    {
        // Get Staking Data
        Staking storage staking = _stakings[msg.sender];

        // Check Conditions
        if (staking.amount != 0) revert AlreadyStaked();

        // Execute Transfers
        if (!$WOOF.transferFrom(msg.sender, address(this), amount)) {
            revert CoinTransferFailed();
        }
        $WOOFWORKER.transferFrom(msg.sender, address(this), tokenId);

        // Get Option Data
        Option memory option = _options[optionId];

        uint128 apr;
        uint128 range;

        unchecked {
            // Set Local Variables
            range = option.range;
            apr = option.apr + ((option.apr * _retrieveTokenBoost(tokenId)) / UNIT_PERCENTAGE);

            // Update Staking Data
            staking.nft = true;
            staking.amount = amount;
            staking.option.apr = apr;
            staking.tokenId = tokenId;
            staking.option.range = range;
            staking.end = block.timestamp + range;
            staking.revenuePerSecond = (amount * apr / UNIT_PERCENTAGE) / YEAR_TIMESTAMP;

            // Update Pool Data
            pool.tvl += amount;
            ++pool.participants;
        }

        // Emit Event
        emit StakedWithNFT(msg.sender, tokenId, amount, apr, range);
    }

    /**
     * @dev Add tokens to current staking.
     *
     * Requirements:
     *
     * - '_paused' must be false.
     * - 'optionId' must be in range.
     * - WOOF must be already staked by user.
     * - 'tokenId' must exists and 'msg.sender' must be the owner.
     * - 'tx.origin' must be 'msg.sender' to avoid contract calls.
     * - user WOOF balance must be equal or greater than 'amount'.
     *
     * Emits a {StakedWithoutNFT} event.
     */
    function secondaryStakeWithoutNFT(uint232 amount)
        external
        payable
        noContracts
        nonReentrant
        whenNotPaused
        checkWoofBalance(amount)
    {
        // Get Staking Data
        Staking storage staking = _stakings[msg.sender];

        // Check Conditions
        if (staking.amount == 0) revert NotStakedYet();

        // Execute Transfers
        if (!$WOOF.transferFrom(msg.sender, address(this), amount)) {
            revert CoinTransferFailed();
        }

        // Set Local Variables
        uint256 end = staking.end;
        uint128 apr = staking.option.apr;
        uint128 range = staking.option.range;

        unchecked {
            // Update Staking Data
            staking.amount += amount;
            staking.end = block.timestamp + range;
            staking.revenuePerSecond = (staking.amount * apr / UNIT_PERCENTAGE) / YEAR_TIMESTAMP;
            staking.earning +=
                staking.revenuePerSecond * (block.timestamp < end ? range - (end - block.timestamp) : range);

            // Update Pool Data
            pool.tvl += amount;
        }

        // Emit Event
        emit StakedWithoutNFT(msg.sender, amount, apr, range);
    }

    /**
     * @dev Add tokens and NFT to current staking.
     *
     * Requirements:
     *
     * - '_paused' must be false.
     * - 'optionId' must be in range.
     * - WOOF must be already staked by user.
     * - NFT must be not already staked by user.
     * - 'tokenId' must exists and 'msg.sender' must be the owner.
     * - 'tx.origin' must be 'msg.sender' to avoid contract calls.
     * - user WOOF balance must be equal or greater than 'amount'.
     *
     * Emits a {StakedWithNFT} event.
     */
    function secondaryStakeWithNFT(uint16 tokenId, uint232 amount)
        external
        payable
        noContracts
        nonReentrant
        whenNotPaused
        canStakeWoofworker
        isValidToken(tokenId)
        isTokenOwner(tokenId)
        checkWoofBalance(amount)
    {
        // Get Staking Data
        Staking storage staking = _stakings[msg.sender];

        // Check Conditions
        if (staking.nft) revert WoofworkerAlreadyStaked();
        if (staking.amount == 0) revert NotStakedYet();

        // Execute Transfers
        if (!$WOOF.transferFrom(msg.sender, address(this), amount)) {
            revert CoinTransferFailed();
        }
        $WOOFWORKER.transferFrom(msg.sender, address(this), tokenId);

        // Set Local Variables
        uint256 end = staking.end;
        uint128 apr = staking.option.apr;
        uint128 range = staking.option.range;
        uint128 aprBoosted = apr + ((apr * _retrieveTokenBoost(tokenId)) / UNIT_PERCENTAGE);

        unchecked {
            // Update Staking Data
            staking.nft = true;
            staking.amount += amount;
            staking.tokenId = tokenId;
            staking.option.apr = aprBoosted;
            staking.end = block.timestamp + range;
            staking.earning +=
                staking.revenuePerSecond * (block.timestamp < end ? range - (end - block.timestamp) : range);
            staking.revenuePerSecond = (staking.amount * aprBoosted / UNIT_PERCENTAGE) / YEAR_TIMESTAMP;

            // Update Pool Data
            pool.tvl += amount;
        }

        // Emit Event
        emit StakedWithNFT(msg.sender, tokenId, amount, apr, range);
    }

    /**
     * @dev Unstake tokens.
     *
     * Requirements:
     *
     * - WOOF must be already staked by user.
     * - 'tx.origin' must be 'msg.sender' to avoid contract calls.
     *
     * Emits a {UnstakeWithNFT} or {UnstakeWithoutNFT} event.
     */
    function unstake() external payable noContracts nonReentrant {
        // Get Staking Data
        Staking storage staking = _stakings[msg.sender];

        // Check Conditions
        if (staking.amount == 0) revert NothingStaked();

        // Set Local Variables
        uint256 burnedAmount;
        uint256 withdrawnAmount;
        uint256 amount = staking.amount;

        unchecked {
            // Check conditions
            if (block.timestamp < staking.end) {
                burnedAmount = amount / PENALTY_PERCENTAGE;
                withdrawnAmount = amount - burnedAmount;

                if (!$WOOF.transfer(DEAD_ADDRESS, burnedAmount)) {
                    revert CoinTransferFailed();
                }
            } else {
                withdrawnAmount = amount + (staking.revenuePerSecond * staking.option.range);
            }

            if (!$WOOF.transfer(msg.sender, withdrawnAmount)) {
                revert CoinTransferFailed();
            }

            if (staking.nft) {
                $WOOFWORKER.transferFrom(address(this), msg.sender, staking.tokenId);
                emit UnstakeWithNFT(msg.sender, staking.tokenId, burnedAmount, withdrawnAmount);
            } else {
                emit UnstakeWithoutNFT(msg.sender, withdrawnAmount, burnedAmount);
            }

            // Update pool data
            pool.tvl -= uint232(amount);
            --pool.participants;
        }

        // Delete staking data
        delete _stakings[msg.sender];
    }

    /* HELPERS */

    /**
     * @dev Return the percentage boost according to the NFT 'tokenId'.
     */
    function _retrieveTokenBoost(uint256 tokenId) private pure returns (uint128 boost) {
        if ((tokenId < 26) || (tokenId > 225 && tokenId < 251)) return 30;
        if ((tokenId > 25 && tokenId < 76) || (tokenId > 175 && tokenId < 226) || (tokenId > 500 && tokenId < 601)) {
            return 20;
        }
        if ((tokenId > 75 && tokenId < 176) || (tokenId > 600 && tokenId < 701)) {
            return 10;
        }
        if ((tokenId > 250 && tokenId < 501) || (tokenId > 750 && tokenId < 1001)) return 5;
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @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;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    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
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // 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/ERC721/IERC721.sol



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

pragma solidity ^0.8.20;

import {IERC165} from "../../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 address zero.
     *
     * 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/ERC20/IERC20.sol



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

pragma solidity ^0.8.20;

/**
 * @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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @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);
}