// File: Graveyard.sol



// * ————————————————————————————————————————————————————————————————————————————————— *
// |                                                                                   |
// |    SSSSS K    K EEEEEE L      EEEEEE PPPPP  H    H U    U N     N K    K  SSSSS   |
// |   S      K   K  E      L      E      P    P H    H U    U N N   N K   K  S        |
// |    SSSS  KKKK   EEE    L      EEE    PPPPP  HHHHHH U    U N  N  N KKKK    SSSS    |
// |        S K   K  E      L      E      P      H    H U    U N   N N K   K       S   |
// |   SSSSS  K    K EEEEEE LLLLLL EEEEEE P      H    H  UUUU  N     N K    K SSSSS    |
// |                                                                                   |
// | * AN ETHEREUM-BASED INDENTITY PLATFORM BROUGHT TO YOU BY NEUROMANTIC INDUSTRIES * |
// |                                                                                   |
// |                             @@@@@@@@@@@@@@@@@@@@@@@@                              |
// |                             @@@@@@@@@@@@@@@@@@@@@@@@                              |
// |                          @@@,,,,,,,,,,,,,,,,,,,,,,,,@@@                           |
// |                       @@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@@                        |
// |                       @@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@@                        |
// |                       @@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@@                        |
// |                       @@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@@                        |
// |                       @@@@@@@@@@,,,,,,,,,,@@@@@@,,,,,,,@@@                        |
// |                       @@@@@@@@@@,,,,,,,,,,@@@@@@,,,,,,,@@@                        |
// |                       @@@@@@@@@@,,,,,,,,,,@@@@@@,,,,,,,@@@                        |
// |                       @@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@@                        |
// |                       @@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@@                        |
// |                       @@@,,,,,,,@@@@@@,,,,,,,,,,,,,,,,,@@@                        |
// |                       @@@,,,,,,,@@@@@@,,,,,,,,,,,,,,,,,@@@                        |
// |                          @@@,,,,,,,,,,,,,,,,,,,,,,,,@@@                           |
// |                          @@@,,,,,,,,,,,,,,,,,,,,@@@@@@@                           |
// |                             @@@@@@@@@@@@@@@@@@@@@@@@@@@                           |
// |                             @@@@@@@@@@@@@@@@@@@@@@@@@@@                           |
// |                             @@@@,,,,,,,,,,,,,,,,@@@@,,,@@@                        |
// |                                 @@@@@@@@@@@@@@@@,,,,@@@                           |
// |                                           @@@,,,,,,,,,,@@@                        |
// |                                           @@@,,,,,,,,,,@@@                        |
// |                                              @@@,,,,@@@                           |
// |                                           @@@,,,,,,,,,,@@@                        |
// |                                                                                   |
// |                                                                                   |
// |   for more information visit skelephunks.com  |  follow @skelephunks on twitter   |
// |                                                                                   |
// * ————————————————————————————————————————————————————————————————————————————————— *
   
   
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    //                                           |  The Graveyard is a place you can send a Skelephunk    //
    //  The Skelephunks Graveyard Contract       |  and get back a fresh mint from the "Crypt" reserves.  //
    //  By Autopsyop,for Neuromantic Industries  |  This is called "burying" instead of burning a token.  //
    //  Part of the Skelephunks Platform         |  Once a token is buried it can also be purchased at    //
    //                                           |  mint price or reserved to swap in for your next bury  //                                                 //  
    ////////////////////////////////////////////////////////////////////////////////////////////////////////                                    


// SPDX-License-Identifier: MIT
// ************************* ERROR CODES ***************************/
// aa: already authorized
// na: must be authorized
// oa: Must be owner or authorized address
// as: skelephunksContract is already set to that value
// rs: no skelephunks contract linked
// os: you can only send skelephunks to the Graveyard
// ap: Paused already set to that value
// ao: minterOnly already set to that value
// ar: allowRemint already set to that value
// am: already reminted more than that
// ge: the graveyard is empty
// aw: per-wallet maximum already set to that value
// au: useSnapshot is already set to that value
// nb: token is not buried
// tr: token is reserved
// al: allowReservations is already set to that value
// nr: reservations are not currently allowed
// ur: address has nothing reserved
// nm: no mints left in crypt
// mr: maximum remints already granted
// mx: wallet has already max reminted
// sn: token was minted after snapshot
// cb: the graveyard cannot bury your skelephunk at this time
// nc: contracts are not allowed to send tokens to the graveyard
// a$: allowPurchase is already set to that value
// a@: purchasePrice already set to that value
// np: purchasing not currently allowed
// pr: Poor
// cf: could not forward payment to the skelephunks contract
// *****************************************************************/
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

interface ISkelephunks is IERC721{
    function mintedAt(uint256 _tokenId) external view returns (uint256);
    function minterOf(uint256 _tokenId) external view returns (address);
    function getGenderAndDirection(uint256 _tokenId) external view returns (uint256);
    function tokenOfOwnerByIndex( address _owner, uint256 _index) external view returns (uint256);
    function numMintedReserve() external view returns (uint256);
    function maxReserveSupply() external view returns (uint256);
    function mintReserve(address _to, uint256 _quantity, uint256 _genderDirection) external;
    function mintPrice () external view returns (uint256);
    function owner () external view returns (address);
}

contract Graveyard is IERC721Receiver, Ownable {
// packed storage variables
    uint256 public snapshot;

    uint64 private purchasePrice;
    uint16 public totalRemints;
    uint16 private maxRemints;
    uint16 public totalBurials;
    uint16 private maxRemintsPerWallet;
    uint8 public holdLengthMinutes;// max 256 minutes 
    bool public paused;
    bool public minterOnly;
    bool public allowRemint;
    bool public useSnapshot;
    bool public allowReservations;
    bool public allowPurchase;

    ISkelephunks public skelephunksContract;

    mapping (address => bool) private authorizedAddresses;

    mapping (address => uint16) public totalRemintsByWallet;

    mapping ( address => uint16 ) private reservations;

    mapping ( uint16 => uint256 ) private expirations;
    constructor () {
        paused = false;

        allowRemint = true;
        minterOnly = false;
        maxRemints = 0;
        maxRemintsPerWallet = 0;

        useSnapshot = true;
        snapshot = block.timestamp;

        allowReservations = false;
        holdLengthMinutes = 60;//1 hour hold for reservations

        allowPurchase = false;
        skelephunksContract = ISkelephunks(address(0x7db8cD89308A295bb2D7F809B05DB6389e9a6d88));// MAINNET
        // skelephunksContract = ISkelephunks(address(0xbaC6C9F6b0d7be7a46EDb82237991Fb990459748));// GOERLI
        transferOwnership( skelephunksContract.owner() );
    }

    /**
        authorized addresses can exhume buried skelephunks
    **/
    function setAuthorization( 
        address _addr,
        bool _auth
    ) public onlyOwner {
        require(authorizedAddresses[_addr]!=_auth,"aa");
        authorizedAddresses[_addr] = _auth;

    }
    function isAuthorized(
        address _addr
    ) public view returns (bool){
        return authorizedAddresses[_addr];
    }
    modifier onlyAuthorized{
        require(authorizedAddresses[msg.sender],"na");
        _;
    }
    modifier ownerOrAuthorized{
        require( owner() == msg.sender || isAuthorized(msg.sender), "oa");
        _;
    }
    /**
        The skele contract
    **/    

    function setSkelephunksContract( 
        address _contract 
    ) external onlyOwner {
        require(address(skelephunksContract)!= _contract, "as");
        skelephunksContract = ISkelephunks( _contract );
    }
    /**
        function requires the skele contract
    **/    
    modifier requiresSkelephunks {
        require( ISkelephunks(address(0)) != skelephunksContract , "rs" );
        _;
    }
    /**
        Redeem for mint requires the crypt to have supply // protect the final 666
    **/
    function getMaxCryptMints(
    ) private view returns (uint16){
        return  uint16(skelephunksContract.maxReserveSupply() - skelephunksContract.numMintedReserve() - 666);
    }
    function cryptHasMints(
    ) private view returns (bool){
        return 0 != getMaxCryptMints() ;
    }

    /**
        function will only receive ERC721 from skele contract
    **/
    modifier onlyReceiveSkelephunks {
        require( address(msg.sender) == address(skelephunksContract), "os" );
        _;
    }
    /**
        pause stuff 
    **/

    function setPaused(
        bool _paused
    ) public onlyOwner {
        require( paused != _paused, "ap" );
        paused = _paused;
    }

    modifier pausable {
      require(!paused);
      _;
   }

    /**
        only accept ERC721 from skele minter 
    **/

    function setMinterOnly( 
        bool _minterOnly 
    ) public onlyOwner {
        require( minterOnly != _minterOnly, "ao" );
        minterOnly = _minterOnly;
    }


    /**
        allowRemints 
    **/

    function setAllowRemint( 
        bool _allow 
    ) public onlyOwner {
        require( allowRemint != _allow, "ar" );
        allowRemint = _allow;
    }

    /**
        buried tokens
    **/    
    function isBuried(
        uint16 _tokenId
    ) public view requiresSkelephunks returns ( bool ){
        return skelephunksContract.ownerOf(_tokenId) == address(this);
    }

    /**
        remints
    **/
    function getMaxRemints(
    ) public view returns (uint16){
        if(!allowRemint){
            return 0;
        }
        if(maxRemints == 0){
            return getMaxCryptMints();
        }
        return maxRemints;
    }

    function setMaxRemints( 
        uint16 _max 
    ) public onlyOwner {
        require( _max == 0 || _max > totalRemints, "am" );
        maxRemints = _max;
    }

    /**
       Number of tokens currently owned by the Graveyard
    **/    
    function getNumBuried(
    ) public view returns ( uint16 ){
        return uint16(skelephunksContract.balanceOf( address( this ) ));
    }

    modifier notEmpty {
        require(0 < getNumBuried(), "ge");
        _;
    }

    function getMaxRemintsPerWallet(
    )public view returns (uint16){
        if(maxRemintsPerWallet == 0){
            return getRemainingRemints();
        }
        return maxRemintsPerWallet;
    }
    function setMaxRemintsPerWallet( 
        uint16 _max 
    ) public onlyOwner {
        require(maxRemintsPerWallet != _max, "aw");
        maxRemintsPerWallet = _max;
    }

    function getRemainingRemints(
    ) public view returns (uint16) {
        if (!cryptHasMints() || !allowRemint){
            return 0;
        }
        if (maxRemints == 0){
            return getMaxCryptMints();
        }
        return maxRemints - totalRemints;
    }

    function getRemainingRemintsForWallet(
        address _wallet
    ) public view returns(uint16){
        if (!cryptHasMints() || !allowRemint){
            return 0;
        }
        if (maxRemintsPerWallet == 0){
            return getMaxRemints();
        }
        return maxRemintsPerWallet - totalRemintsByWallet[_wallet];
    }

    /**
       snapshot (timestamp) - no new tokens after this timestamp can be buried
    **/  

    function setUseSnapshot(
        bool _bool
    ) public onlyOwner {
        require (useSnapshot != _bool, "au" );
        useSnapshot = _bool;
    }
    function takeSnapshot( 
        uint256 _timestamp 
    ) public onlyOwner {
        useSnapshot = true;
        if (_timestamp == 0) {
            snapshot = block.timestamp;
        } else {
            snapshot = _timestamp;
        }
    }

    /**
       reservation hold period (seconds) - for how long is a reservation exclusive
    **/  
    
    function setHoldLengthMinutes(
        uint8 _mins
    ) public onlyOwner {
        holdLengthMinutes = _mins;
    }

    /**
       an available token is buried and outside of any reservation window
    **/  
    function tokenIsAvailable(
        uint16 _tokenId
    ) public view returns (bool) {
        return isBuried(_tokenId) && !isReserved(_tokenId);
    }

    function requireAvailable(
        uint16 _tokenId
    ) private view {
        require(isBuried(_tokenId), "nb");
        require(!isReserved(_tokenId) || reservations[msg.sender] == _tokenId, "tr");

    }
    function setAllowReservations(
        bool _allow
    )public onlyOwner{
        require(allowReservations != _allow, "al");
        allowReservations = _allow;
    }

    /**
       a reserved token will be sent upon redeem instead of a new mint
    **/  
    function isReserved(
        uint16 _tokenId
    ) public view returns (bool){
        return block.timestamp < expirations[ _tokenId ];
    }
    /**
       you can only reserve one token at a time
    **/  
    function reserveToken( 
        uint16 _tokenId 
    ) public pausable notEmpty{
        requireAvailable(_tokenId);
        require(allowReservations, "nr");
        if(0 < getReservationFor(msg.sender)){
            unlockToken(getReservationFor(msg.sender));
        }
        reservations[msg.sender] = _tokenId;
        lockToken(_tokenId);
    }
    function lockToken (
        uint16 _tokenId
    ) private {
            expirations[_tokenId] = block.timestamp + holdLengthMinutes*60 ;
    }
    function getReservationFor(
        address _wallet
    ) public view returns (uint16) {
        return reservations[_wallet];
    }
    
    function unlockToken(
        uint16 _tokenId
    ) private{
        delete expirations[_tokenId];
    }

    function clearMyReservation(
    ) public pausable {
        clearReservationFrom(msg.sender);
    }
    function clearReservationFrom(
        address _address
    ) private {
        require( getReservationFor( _address ) != 0, "ur" );
        unlockToken(reservations[_address]);
        delete reservations[_address];
    }

    /**
       a buried token is owned by this contract, and can be reserved for redemption or purchased
    **/  

    function buriedTokenByIndex(
        uint16 _index
    ) public view requiresSkelephunks returns (uint16) {
        return uint16(skelephunksContract.tokenOfOwnerByIndex(address(this), uint256(_index)));
    }

    /**
       an exhumed token was buried but later transferred out to a new owner
    **/  
    function exhumeToken(
        address _to, 
        uint16 _tokenId
    ) private notEmpty requiresSkelephunks {
        skelephunksContract.safeTransferFrom(address(this), _to, _tokenId);
    }

    function exhumeTo(
        address _to,
        uint16 _tokenId
    ) public ownerOrAuthorized {
        requireAvailable(_tokenId);
        exhumeToken(_to,_tokenId);
    }
/**
    exhume all tokens to a single address
    if _reserved is false, skip reserved tokens
**/
    function exhumeAllTo(
        address _to,
        bool _includeReserved
    ) public onlyOwner notEmpty {
        uint16 num = getNumBuried();
        for (uint16 i = 0; i < num ; i++ ){
            uint16 tokenId = buriedTokenByIndex(i);
            if(_includeReserved || tokenIsAvailable(tokenId)){
                exhumeToken( _to, tokenId);
            }
        }
    }

    function exhumeReserved(
        address _to
    ) private notEmpty{
        require(getReservationFor(_to) != 0, "ur" );
        exhumeToken(_to,getReservationFor(_to));
        clearReservationFrom(_to);
    }

    function exhumeRandom(
        address _to
    ) private requiresSkelephunks notEmpty{
        uint256 random = uint256(
            keccak256(
                abi.encode(
                    _to,
                    tx.gasprice,
                    block.number,
                    block.timestamp,
                    block.prevrandao,
                    blockhash(block.number - 1),
                    address(this),
                    getNumBuried()
                )
            )
        );
        uint16 index = uint16(getNumBuried() == 1 ? 0 : random % (getNumBuried() - 1)); // max index was just buried
        uint16 tokenID = uint16(skelephunksContract.tokenOfOwnerByIndex(address(this),index));
        exhumeToken(_to,tokenID);
    }

    /**
       the graveyard enables a wallet to exhange a skelephunk for a new mint from the reserves
    **/  
    function remintFromCrypt(
        address _to, 
        uint8 _gad
    ) private requiresSkelephunks {
        require( cryptHasMints(),"nm");
        require( totalRemints < getRemainingRemints(), "mr" );
        require( 0 < getRemainingRemintsForWallet(_to), "mx");
        skelephunksContract.mintReserve(_to, 1, _gad);
        totalRemints++;
        totalRemintsByWallet[ _to ]++;
    }

    function burySkelephunk(
        uint16 _tokenId, 
        address _wallet 
    ) private requiresSkelephunks{
        require( !useSnapshot || 0 == snapshot || skelephunksContract.mintedAt( _tokenId ) < snapshot, "sn" );
    
        if(_wallet == owner()){
            // contract owner can send without reward to populate the graveyard
        }else if( 0 < getReservationFor(_wallet)){ // settle reservations first
            exhumeReserved(_wallet); 
        }else if (// if remints are available and allowed, send a new mint from the crypt
            allowRemint &&
            cryptHasMints() && 
            0 < getRemainingRemints() && 
            0 < getRemainingRemintsForWallet(_wallet) && 
            (!minterOnly || skelephunksContract.minterOf( _tokenId ) == _wallet)
        ){
            remintFromCrypt(_wallet,uint8(skelephunksContract.getGenderAndDirection(uint256(_tokenId))));
        }else if(1 < getNumBuried()){// otherwise, send a random buried token
            exhumeRandom(_wallet);
        }else{
            revert("cb");
        }
        totalBurials++;
    }

    function onERC721Received(
        address, 
        address _from, 
        uint256 _tokenId, 
        bytes calldata 
    ) external onlyReceiveSkelephunks returns (bytes4) {
        require(_from == tx.origin, "nc");
        burySkelephunk(uint16(_tokenId), _from);
        return this.onERC721Received.selector;
    }


    /**
       the graveyard enables a wallet to purchase a previously buried skelephunk at mint price
    **/  
    function setAllowPurchase (
        bool _allow
    ) public onlyOwner{
        require(allowPurchase !=_allow, "a$");
        allowPurchase = _allow;
    }

    function setPurchasePrice(
        uint64 _price
    ) public onlyOwner {
        require(purchasePrice != _price, "a@");
        purchasePrice = _price;
    }
    function getPurchasePrice(

    )public view returns (uint64){
        if(purchasePrice == 0){
            return uint64(skelephunksContract.mintPrice());
        }else{
            return purchasePrice;
        }
    }
    function buyBuriedSkelephunk (
        uint16 _tokenId
    ) public payable pausable requiresSkelephunks{
        uint64 price = getPurchasePrice();
        require( allowPurchase, "np");
        require( price <= msg.value, "pr");
        requireAvailable(_tokenId);
        (bool outcome,) = address(skelephunksContract).call{value: price}("");
        require(outcome,"cf");
        exhumeToken(msg.sender,_tokenId);
        uint256 refund = msg.value - price;
        if(0 < refund){
            payable(msg.sender).transfer(refund);//give back change for overpayment
        }
    }
}
// File: @openzeppelin/contracts/access/Ownable.sol



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

pragma solidity ^0.8.0;

import "../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.
 *
 * By default, the owner account will be the one that deploys the contract. 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;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @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 {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing 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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _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/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/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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/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: @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;
    }
}