// File: contracts/EricOrb.sol



// SPDX-License-Identifier: MIT
/*..............................................................................


                          ./         (@@@@@@@@@@@@@@@@@,
                     &@@@@       /@@@@&.        *&@@@@@@@@@@*
                 %@@@@@@.      (@@@                  &@@@@@@@@@&
              .@@@@@@@@       @@@                      ,@@@@@@@@@@/
            *@@@@@@@@@       (@%                         &@@@@@@@@@@/
           @@@@@@@@@@/       @@                           (@@@@@@@@@@@
          @@@@@@@@@@@        &@                            %@@@@@@@@@@@
         @@@@@@@@@@@#         @                             @@@@@@@@@@@@
        #@@@@@@@@@@@.                                       /@@@@@@@@@@@@
        @@@@@@@@@@@@                                         @@@@@@@@@@@@
        @@@@@@@@@@@@                                         @@@@@@@@@@@@
        @@@@@@@@@@@@.                                        @@@@@@@@@@@@
        @@@@@@@@@@@@%                                       ,@@@@@@@@@@@@
        ,@@@@@@@@@@@@                                       @@@@@@@@@@@@/
         %@@@@@@@@@@@&                                     .@@@@@@@@@@@@
          #@@@@@@@@@@@#                                    @@@@@@@@@@@&
           .@@@@@@@@@@@&                                 ,@@@@@@@@@@@,
             *@@@@@@@@@@@,                              @@@@@@@@@@@#
                @@@@@@@@@@@*                          @@@@@@@@@@@.
                  .&@@@@@@@@@@*                   .@@@@@@@@@@@.
                       &@@@@@@@@@@@%*..   ..,#@@@@@@@@@@@@@*
                     ,@@@@   ,#&@@@@@@@@@@@@@@@@@@#*     &@@@#
                    @@@@@                                 #@@@@.
                   @@@@@*           Eric's Orb             @@@@@,
                  @@@@@@@(                               .@@@@@@@
                  (@@@@@@@@@@@@@@%/*,.       ..,/#@@@@@@@@@@@@@@@
                     #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%
                             ./%@@@@@@@@@@@@@@@@@@@%/,


..............................................................................*/
pragma solidity ^0.8.17;

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";

/**
 * @title   Eric's Orb - Harberger Tax NFT with auction and on-chain triggers and responses
 * @author  Jonas Lekevicius, Eric Wall
 * @dev     Supports ERC-721 interface, does not support token transfers.
 *          Uses {Ownable}'s {owner()} to identify the issuer of the Orb.
 * @notice  Eric's Orb is a basic Q&A-type Orb. The holder has the right to submit a text-based question to
 *          Eric and the right to receive a text-based response. The question is limited to 280 characters but
 *          responses may come in any length. Questions and answers are hash-committed to the Ethereum blockchain
 *          so that the track record cannot be changed. The Orb has a 1-week cooldown.
 *
 *          The Orb uses Harberger Tax and is always on sale. This means that when you purchase the Orb, you must
 *          also set a price which you’re willing to sell the Orb at. However, you must pay 10% of that amount to
 *          the Orb smart contract per year in order to maintain the Orb ownership. This amount is accounted for
 *          per second, and user funds need to be topped up before the foreclosure time to maintain ownership.
 */
contract EricOrb is ERC721, Ownable {
    ////////////////////////////////////////////////////////////////////////////////
    //  EVENTS
    ////////////////////////////////////////////////////////////////////////////////

    // Auction Events
    event AuctionStarted(uint256 startTime, uint256 endTime);
    event NewBid(address indexed from, uint256 price);
    event UpdatedAuctionEnd(uint256 endTime);
    event AuctionFinalized(address indexed winner, uint256 price);

    // Fund Management, Holding and Purchasing Events
    event Deposit(address indexed sender, uint256 amount);
    event Withdrawal(address indexed recipient, uint256 amount);
    event Settlement(address indexed from, address indexed to, uint256 amount);
    event NewPrice(uint256 from, uint256 to);
    event Purchase(address indexed from, address indexed to, uint256 price);
    event Foreclosure(address indexed from, bool indexed voluntary);

    // Triggering and Responding Events
    event Triggered(address indexed from, uint256 indexed triggerId, bytes32 contentHash, uint256 time);
    event Responded(address indexed from, uint256 indexed triggerId, bytes32 contentHash, uint256 time);
    event CleartextRecorded(uint256 indexed triggerId, string cleartext);
    event ResponseFlagged(address indexed from, uint256 indexed responseId);

    ////////////////////////////////////////////////////////////////////////////////
    //  ERRORS
    ////////////////////////////////////////////////////////////////////////////////

    // ERC-721 Errors
    error TransferringNotSupported();

    // Authorization Errors
    error AlreadyHolder();
    error NotHolder();
    error ContractHoldsOrb();
    error ContractDoesNotHoldOrb();
    error BeneficiaryDisallowed();

    // Funds-Related Authorization Errors
    error HolderSolvent();
    error HolderInsolvent();
    error InsufficientFunds(uint256 fundsAvailable, uint256 fundsRequired);

    // Auction Errors
    error AuctionNotRunning();
    error AuctionRunning();
    error AuctionNotStarted();
    error NotPermittedForWinningBidder();
    error InsufficientBid(uint256 bidProvided, uint256 bidRequired);

    // Purchasing Errors
    error CurrentPriceIncorrect(uint256 priceProvided, uint256 currentPrice);
    error InvalidNewPrice(uint256 priceProvided);

    // Triggering and Responding Errors
    error CooldownIncomplete(uint256 timeRemaining);
    error CleartextTooLong(uint256 cleartextLength, uint256 maxLength);
    error CleartextHashMismatch(bytes32 cleartextHash, bytes32 contentHash);
    error TriggerNotFound(uint256 triggerId);
    error ResponseNotFound(uint256 triggerId);
    error ResponseExists(uint256 triggerId);
    error FlaggingPeriodExpired(uint256 triggerId, uint256 currentTimeValue, uint256 timeValueLimit);
    error ResponseAlreadyFlagged(uint256 triggerId);

    ////////////////////////////////////////////////////////////////////////////////
    //  STORAGE
    ////////////////////////////////////////////////////////////////////////////////

    // CONSTANTS AND IMMUTABLES

    // Beneficiary receives all Orb proceeds
    address public immutable beneficiary;

    // Public Constants
    // Cooldown: how often Orb can be triggered.
    uint256 public immutable cooldown;
    // Response Flagging Period: how long after resonse was recorded it can be flagged by the holder.
    uint256 public immutable responseFlaggingPeriod;
    // Maximum length for trigger cleartext content; tweet length.
    uint256 public constant MAX_CLEARTEXT_LENGTH = 280;

    // Fee Nominator: basis points. Other fees are in relation to this.
    uint256 public constant FEE_DENOMINATOR = 10000;
    // Harberger Tax for holding. Value: 10%.
    uint256 public immutable holderTaxNumerator;
    // Harberger Tax period: for how long the Tax Rate applies. Value: 1 year. So, 10% of price per year.
    uint256 public constant HOLDER_TAX_PERIOD = 365 days;
    // Secondary sale (royalties) to issuer: 10% of the sale price.
    uint256 public immutable saleRoyaltiesNumerator;

    // Auction starting price.
    uint256 public immutable startingPrice;
    // Each bid has to increase over previous bid by at least this much.
    uint256 public immutable minimumBidStep;
    // Auction will run for at least this long.
    uint256 public immutable minimumAuctionDuration;
    // If remaining time is less than this after a bid is made, auction will continue for at least this long.
    uint256 public immutable bidAuctionExtension;

    // Internal Constants
    // Eric's Orb tokenId. Can be whatever arbitrary number, only one token will ever exist. Value: nice.
    uint256 internal constant ERIC_ORB_ID = 69;
    // Base URL for tokenURL JSONs.
    string internal constant BASE_URL = "https://static.orb.land/eric/";
    // Special value returned when foreclosure time is "never".
    uint256 internal constant INFINITY = type(uint256).max;
    // Maximum orb price, limited to prevent potential overflows.
    uint256 internal constant MAX_PRICE = 2 ** 128;

    // STATE

    // Funds tracker, per address. Modified by deposits, withdrawals and settlements.
    // The value is without settlement. It means effective user funds (withdrawable) would be different
    // for holder (subtracting owedSinceLastSettlement) and beneficiary (adding owedSinceLastSettlement).
    // If Orb is held by the creator, funds are not subtracted, as Harberger Tax does not apply to the creator.
    mapping(address => uint256) public fundsOf;

    // Price of the Orb. No need for mapping, as only one token is very minted.
    // Also used during auction to store future purchase price.
    // Shouldn't be useful is orb is held by the contract.
    uint256 public price;
    // Last time orb holder's funds were settled.
    // Shouldn't be useful is orb is held by the contract.
    uint256 public lastSettlementTime;

    // Auction State Variables
    // Start Time: when the auction was started. Stays fixed during the auction, otherwise 0.
    uint256 public startTime;
    // End Time: when the auction ends, can be extended by late bids. 0 not during the auction.
    uint256 public endTime;
    // Winning Bidder: address that currently has the highest bid. 0 not during the auction and before first bid.
    address public winningBidder;
    // Winning Bid: highest current bid. 0 not during the auction and before first bid.
    uint256 public winningBid;

    // Trigger and Response State Variables

    // Struct used to track response information: content hash and timestamp.
    // Timestamp is used to determine if the response can be flagged by the holder.
    // Trigger timestamp doesn't need to be tracked, as nothing is done with it.
    struct HashTime {
        // keccak256 hash of the cleartext
        bytes32 contentHash;
        uint256 timestamp;
    }

    // Holder Receive Time: When the orb was last transferred, except to this contract.
    uint256 public holderReceiveTime;
    // Last Trigger Time: when the orb was last triggered. Used together with Cooldown constant.
    uint256 public lastTriggerTime;
    // Mapping for Triggers (Orb Invocations): triggerId to contentHash (bytes32).
    mapping(uint256 => bytes32) public triggers;
    // Count of triggers made. Used to calculate triggerId of the next trigger.
    uint256 public triggersCount = 0;
    // Mapping for Responses (Replies to Triggers): matching triggerId to HashTime struct.
    mapping(uint256 => HashTime) public responses;
    // Additional mapping for flagged (reported) Responses. Used by the holder not satisfied with a response.
    mapping(uint256 => bool) public responseFlagged;
    // A convencience count of total responses made. Not used by the contract itself.
    uint256 public flaggedResponsesCount = 0;

    ////////////////////////////////////////////////////////////////////////////////
    //  CONSTRUCTOR
    ////////////////////////////////////////////////////////////////////////////////

    /**
     * @dev  When deployed, contract mints the only token that will ever exist, to itself.
     *       This token represents the Orb and is called the Orb elsewhere in the contract.
     *       {Ownable} sets the deployer to be the owner, and also the issuer in the orb context.
     * @param cooldown_  How often Orb can be triggered.
     * @param responseFlaggingPeriod_  How long after resonse was recorded it can be flagged by the holder.
     * @param minimumAuctionDuration_  Minimum length for an auction.
     * @param bidAuctionExtension_  If remaining time is less than this after a bid is made,
     *        auction will continue for at least this long.
     * @param beneficiary_  Beneficiary receives all Orb proceeds.
     */
    constructor(
        uint256 cooldown_,
        uint256 responseFlaggingPeriod_,
        uint256 minimumAuctionDuration_,
        uint256 bidAuctionExtension_,
        address beneficiary_,
        uint256 holderTaxNumerator_,
        uint256 saleRoyaltiesNumerator_,
        uint256 startingPrice_,
        uint256 minimumBidStep_
    ) ERC721("Eric Orb", "ORB") {
        cooldown = cooldown_;
        responseFlaggingPeriod = responseFlaggingPeriod_;
        minimumAuctionDuration = minimumAuctionDuration_;
        bidAuctionExtension = bidAuctionExtension_;
        beneficiary = beneficiary_;
        holderTaxNumerator = holderTaxNumerator_;
        saleRoyaltiesNumerator = saleRoyaltiesNumerator_;
        startingPrice = startingPrice_;
        minimumBidStep = minimumBidStep_;

        _safeMint(address(this), ERIC_ORB_ID);
    }

    ////////////////////////////////////////////////////////////////////////////////
    //  MODIFIERS
    ////////////////////////////////////////////////////////////////////////////////

    // AUTHORIZATION MODIFIERS

    /**
     * @notice  Contract inherits {onlyOwner} modifier from {Ownable}.
     */

    /**
     * @dev  Ensures that the caller owns the orb.
     *       Should only be used in conjuction with {onlyHolderHeld} or on external functions,
     *       otherwise does not make sense.
     */
    modifier onlyHolder() {
        if (msg.sender != ERC721.ownerOf(ERIC_ORB_ID)) {
            revert NotHolder();
        }
        _;
    }

    // ORB STATE MODIFIERS

    /**
     * @dev  Ensures that the orb belongs to someone, not the contract itself.
     */
    modifier onlyHolderHeld() {
        if (address(this) == ERC721.ownerOf(ERIC_ORB_ID)) {
            revert ContractHoldsOrb();
        }
        _;
    }

    /**
     * @dev  Ensures that the orb belongs to the contract itself, either because it hasn't been auctioned,
     *       or because it has returned to the contract due to {exit()} or {foreclose()}
     */
    modifier onlyContractHeld() {
        if (address(this) != ERC721.ownerOf(ERIC_ORB_ID)) {
            revert ContractDoesNotHoldOrb();
        }
        _;
    }

    // AUCTION MODIFIERS

    /**
     * @dev  Ensures that an auction is currently running.
     */
    modifier onlyDuringAuction() {
        if (!auctionRunning()) {
            revert AuctionNotRunning();
        }
        _;
    }

    /**
     * @dev  Ensures that an auction is currently not running.
     *       Can be multiple states: auction not started, auction over but not finalized, or auction finalized.
     */
    modifier notDuringAuction() {
        if (auctionRunning()) {
            revert AuctionRunning();
        }
        _;
    }

    /**
     * @dev  Ensures that the caller is not currently winning the auction.
     *       User winning the auction cannot withdraw funds, as funds include user's bid.
     */
    modifier notWinningBidder() {
        if (msg.sender == winningBidder) {
            revert NotPermittedForWinningBidder();
        }
        _;
    }

    // FUNDS-RELATED MODIFIERS

    /**
     * @dev  Ensures that the current orb holder has enough funds to cover Harberger tax until now.
     */
    modifier onlyHolderSolvent() {
        if (!holderSolvent()) {
            revert HolderInsolvent();
        }
        _;
    }

    /**
     * @dev  Ensures that the current orb holder has run out of funds to cover Harberger tax.
     */
    modifier onlyHolderInsolvent() {
        if (holderSolvent()) {
            revert HolderSolvent();
        }
        _;
    }

    /**
     * @dev  Modifier settles current orb holder's debt before executing the rest of the function.
     */
    modifier settles() {
        _settle();
        _;
    }

    /**
     * @dev  Modifier settles current orb holder's debt before executing the rest of the function,
     *       only if the caller is the orb holder. Useful for holder withdrawals.
     */
    modifier settlesIfHolder() {
        if (msg.sender == ERC721.ownerOf(ERIC_ORB_ID)) {
            _settle();
        }
        _;
    }

    ////////////////////////////////////////////////////////////////////////////////
    //  FUNCTIONS: ERC-721 OVERRIDES
    ////////////////////////////////////////////////////////////////////////////////

    function _baseURI() internal pure override returns (string memory) {
        return BASE_URL;
    }

    /**
     * @notice  Transfers the orb to another address. Not allowed, always reverts.
     * @dev     Always reverts. In future versions we might allow transfers.
     *          Transfers would settle (both accounts in multi-orb) and require the receiver to have deposit.
     */
    function transferFrom(address, address, uint256) public pure override {
        revert TransferringNotSupported();
    }

    /**
     * @dev  See {transferFrom()} above.
     */
    function safeTransferFrom(address, address, uint256) public pure override {
        revert TransferringNotSupported();
    }

    /**
     * @dev  See {transferFrom()} above.
     */
    function safeTransferFrom(address, address, uint256, bytes memory) public pure override {
        revert TransferringNotSupported();
    }

    /**
     * @notice  Transfers the ERC-20 token to the new address.
     *          If the new owner is not this contract (an actual user), updates holderReceiveTime.
     *          holderReceiveTime is used to limit response flagging window.
     */
    function _transferOrb(address oldAddress, address newAddress) internal {
        _transfer(oldAddress, newAddress, ERIC_ORB_ID);
        if (newAddress != address(this)) {
            holderReceiveTime = block.timestamp;
        }
    }

    ////////////////////////////////////////////////////////////////////////////////
    //  FUNCTIONS: AUCTION
    ////////////////////////////////////////////////////////////////////////////////

    /**
     * @notice  Returns if the auction is currently running. Use endTime() to check when it ends.
     * @dev     Start time will always be less than timestamp, as it resets to 0.
     *          Start time is only updated for auction progress tracking, not critical functionality.
     * @return  bool  If the auction is running.
     */
    function auctionRunning() public view returns (bool) {
        return endTime > block.timestamp && address(this) == ERC721.ownerOf(ERIC_ORB_ID);
    }

    /**
     * @notice  Minimum bid that would currently be accepted by {bid()}.
     * @dev     startingPrice if no bids were made, otherwise previous bid increased by minimumBidStep.
     * @return  uint256  Minimum bid required for {bid()}.
     */
    function minimumBid() public view returns (uint256) {
        if (winningBid == 0) {
            return startingPrice;
        } else {
            unchecked {
                return winningBid + minimumBidStep;
            }
        }
    }

    /**
     * @notice  Allow the Orb issuer to start the Orb Auction. Will run for at least minimumAuctionDuration.
     * @dev     Prevents repeated starts by checking the endTime.
     *          Important to set endTime to 0 after auction is finalized.
     *          Also, resets winningBidder and winningBid.
     *          Should not be necessary, as {finalizeAuction()} also does that.
     *          Emits AuctionStarted().
     */
    function startAuction() external onlyOwner onlyContractHeld notDuringAuction {
        if (endTime > 0) {
            revert AuctionRunning();
        }

        startTime = block.timestamp;
        endTime = block.timestamp + minimumAuctionDuration;
        winningBidder = address(0);
        winningBid = 0;

        emit AuctionStarted(startTime, endTime);
    }

    /**
     * @notice  Bids the provided amount, if there's enough funds across funds on contract and transaction value.
     *          Might extend the auction if the bid is near the end.
     *          Important: the winning bidder will not be able to withdraw funds until someone outbids them.
     * @dev     Emits NewBid().
     * @param   amount  The value to bid.
     * @param   priceIfWon  Price if the bid wins. Must be less than MAX_PRICE.
     */
    function bid(uint256 amount, uint256 priceIfWon) external payable onlyDuringAuction {
        if (msg.sender == beneficiary) {
            revert BeneficiaryDisallowed();
        }

        uint256 totalFunds = fundsOf[msg.sender] + msg.value;

        if (amount < minimumBid()) {
            revert InsufficientBid(amount, minimumBid());
        }

        if (totalFunds < amount) {
            revert InsufficientFunds(totalFunds, amount);
        }

        if (priceIfWon > MAX_PRICE) {
            revert InvalidNewPrice(priceIfWon);
        }

        fundsOf[msg.sender] = totalFunds;
        winningBidder = msg.sender;
        winningBid = amount;
        price = priceIfWon;

        emit NewBid(msg.sender, amount);

        if (block.timestamp + bidAuctionExtension > endTime) {
            endTime = block.timestamp + bidAuctionExtension;
            emit UpdatedAuctionEnd(endTime);
        }
    }

    /**
     * @notice  Finalizes the Auction, transferring the winning bid to the beneficiary, and the orb to the winner.
     *          Sets lastTriggerTime so that the Orb could be triggered immediately.
     *          The price has been set when bidding, now becomes relevant.
     *          If no bids were made, resets the state to allow the auction to be started again later.
     * @dev     Critical state transition function. Called after endTime, but only if it's not 0.
     *          Can be called by anyone, although probably will be called by the issuer or the winner.
     *          Emits NewPrice() and AuctionFinalized().
     */
    function finalizeAuction() external notDuringAuction {
        if (endTime == 0) {
            revert AuctionNotStarted();
        }

        if (winningBidder != address(0)) {
            fundsOf[winningBidder] -= winningBid;
            fundsOf[beneficiary] += winningBid;

            lastSettlementTime = block.timestamp;
            lastTriggerTime = block.timestamp - cooldown;

            emit AuctionFinalized(winningBidder, winningBid);
            emit NewPrice(0, price);
            // price has been set when bidding

            _transferOrb(address(this), winningBidder);
            winningBidder = address(0);
            winningBid = 0;
        } else {
            price = 0;
            emit AuctionFinalized(winningBidder, winningBid);
        }

        startTime = 0;
        endTime = 0;
    }

    ////////////////////////////////////////////////////////////////////////////////
    //  FUNCTIONS: FUNDS AND HOLDING
    ////////////////////////////////////////////////////////////////////////////////

    /**
     * @notice  Allows depositing funds on the contract. Not allowed for insolvent holders.
     * @dev     Deposits are not allowed for insolvent holders to prevent cheating via front-running.
     *          If the user becomes insolvent, the orb will always be returned to the contract as the next step.
     *          Emits Deposit().
     */
    function deposit() external payable {
        if (msg.sender == ERC721.ownerOf(ERIC_ORB_ID) && !holderSolvent()) {
            revert HolderInsolvent();
        }

        fundsOf[msg.sender] += msg.value;
        emit Deposit(msg.sender, msg.value);
    }

    /**
     * @notice  Function to withdraw all funds on the contract.
     *          Not recommended for current orb holders, they should call exit() to take out their funds.
     * @dev     Not allowed for the winning auction bidder.
     */
    function withdrawAll() external notWinningBidder settlesIfHolder {
        _withdraw(msg.sender, fundsOf[msg.sender]);
    }

    /**
     * @notice  Function to withdraw given amount from the contract.
     *          For current orb holders, reduces the time until foreclosure.
     * @dev     Not allowed for the winning auction bidder.
     */
    function withdraw(uint256 amount) external notWinningBidder settlesIfHolder {
        _withdraw(msg.sender, amount);
    }

    /**
     * @notice  Function to withdraw all beneficiary funds on the contract.
     * @dev     Allowed for anyone at any time, does not use msg.sender in its execution.
     */
    function withdrawAllForBeneficiary() external {
        _withdraw(beneficiary, fundsOf[beneficiary]);
    }

    /**
     * @notice  Settlements transfer funds from orb holder to the beneficiary.
     *          Orb accounting minimizes required transactions: orb holder's foreclosure time is only
     *          dependent on the price and available funds. Fund transfers are not necessary unless
     *          these variables (price, holder funds) are being changed. Settlement transfers funds owed
     *          since the last settlement, and a new period of virtual accounting begins.
     * @dev     Holder might owe more than they have funds available: it means that the holder is foreclosable.
     *          Settlement would transfer all holder funds to the beneficiary, but not more.
     *          Does nothing if the issuer holds the orb. Reverts if contract holds the orb.
     *          Emits Settlement().
     */
    function settle() external onlyHolderHeld {
        _settle();
    }

    /**
     * @dev     Returns if the current orb holder has enough funds to cover Harberger tax until now.
     *          Always true is issuer holds the orb.
     * @return  bool  If the current holder is solvent.
     */
    function holderSolvent() public view returns (bool) {
        address holder = ERC721.ownerOf(ERIC_ORB_ID);
        if (owner() == holder) {
            return true;
        }
        return fundsOf[holder] > _owedSinceLastSettlement();
    }

    /**
     * @dev     Calculates how much money orb holder owes orb issuer. This amount would be transferred between
     *          accounts during settlement.
     *          Owed amount can be higher than hodler's funds! It's important to check if holder has enough funds
     *          before transferring.
     * @return  bool  Wei orb holders owes orb issuer since the last settlement time.
     */
    function _owedSinceLastSettlement() internal view returns (uint256) {
        uint256 secondsSinceLastSettlement = block.timestamp - lastSettlementTime;
        return (price * holderTaxNumerator * secondsSinceLastSettlement) / (HOLDER_TAX_PERIOD * FEE_DENOMINATOR);
    }

    /**
     * @dev     Executes the withdrawal for a given amount, does the actual value transfer from the contract
     *          to user's wallet. The only function in the contract that sends value and has re-entrancy risk.
     *          Does not check if the address is payable, as the Address library reverts if it is not.
     *          Emits Withdrawal().
     * @param   receiver  The address to send the value to.
     * @param   amount_  The value in wei to withdraw from the contract.
     */
    function _withdraw(address receiver, uint256 amount_) internal {
        if (fundsOf[receiver] < amount_) {
            revert InsufficientFunds(fundsOf[receiver], amount_);
        }

        fundsOf[receiver] -= amount_;

        emit Withdrawal(receiver, amount_);

        Address.sendValue(payable(receiver), amount_);
    }

    /**
     * @dev  See {settle()}.
     */
    function _settle() internal {
        address holder = ERC721.ownerOf(ERIC_ORB_ID);

        if (owner() == holder) {
            return;
        }

        // Should never be reached if this contract holds the orb.
        assert(address(this) != holder);

        uint256 availableFunds = fundsOf[holder];
        uint256 owedFunds = _owedSinceLastSettlement();
        uint256 transferableToBeneficiary = availableFunds <= owedFunds ? availableFunds : owedFunds;

        fundsOf[holder] -= transferableToBeneficiary;
        fundsOf[beneficiary] += transferableToBeneficiary;

        lastSettlementTime = block.timestamp;

        emit Settlement(holder, beneficiary, transferableToBeneficiary);
    }

    ////////////////////////////////////////////////////////////////////////////////
    //  FUNCTIONS: PURCHASING
    ////////////////////////////////////////////////////////////////////////////////

    /**
     * @notice  Sets the new purchase price for the orb. Harberger tax means the asset is always for sale.
     *          The price can be set to zero, making foreclosure time to be never.
     * @dev     Can only be called by a solvent holder.
     *          Settles before adjusting the price, as the new price will change foreclosure time.
     *          Does not check if the new price differs from the previous price: no risk.
     *          Limits the price to MAX_PRICE to prevent potential overflows in math.
     *          Emits NewPrice().
     * @param   newPrice  New price for the orb.
     */
    function setPrice(uint256 newPrice) external onlyHolder onlyHolderSolvent settles {
        _setPrice(newPrice);
    }

    /**
     * @notice  Purchasing is the mechanism to take over the orb. With Harberger tax, an orb can always be
     *          purchased from its holder.
     *          Purchasing is only allowed while the holder is solvent. If not, the orb has to be foreclosed and
     *          re-auctioned.
     *          Purchaser is required to have more funds than the price itself, but the exact amount is left for the
     *          user interface implementation to calculate and send along.
     *          Purchasing sends Sale Royalties part to the beneficiary, 10% by default.
     * @dev     Requires to provide the current price as the first parameter to prevent front-running: without current
     *          price requirement someone could purchase the orb ahead of someone else, set the price higher, and
     *          profit from the purchase.
     *          Does not modify last trigger time, unlike buying from the auction.
     *          Does not allow purchasing from yourself.
     *          Emits NewPrice() and Purchase().
     * @param   currentPrice  Current price, to prevent front-running.
     * @param   newPrice  New price to use after the purchase.
     */
    function purchase(uint256 currentPrice, uint256 newPrice)
        external
        payable
        onlyHolderHeld
        onlyHolderSolvent
        settles
    {
        if (currentPrice != price) {
            revert CurrentPriceIncorrect(currentPrice, price);
        }

        address holder = ERC721.ownerOf(ERIC_ORB_ID);

        if (msg.sender == holder) {
            revert AlreadyHolder();
        }
        if (msg.sender == beneficiary) {
            revert BeneficiaryDisallowed();
        }

        fundsOf[msg.sender] += msg.value;
        uint256 totalFunds = fundsOf[msg.sender];

        if (totalFunds < currentPrice) {
            revert InsufficientFunds(totalFunds, currentPrice);
        }

        fundsOf[msg.sender] -= currentPrice;

        if (owner() == holder) {
            fundsOf[beneficiary] += currentPrice;
        } else {
            uint256 beneficiaryRoyalties = (currentPrice * saleRoyaltiesNumerator) / FEE_DENOMINATOR;
            uint256 currentOwnerShare = currentPrice - beneficiaryRoyalties;

            fundsOf[beneficiary] += beneficiaryRoyalties;
            fundsOf[holder] += currentOwnerShare;
        }

        lastSettlementTime = block.timestamp;

        _setPrice(newPrice);

        emit Purchase(holder, msg.sender, currentPrice);

        _transferOrb(holder, msg.sender);
    }

    /**
     * @dev  See {setPrice()}.
     */
    function _setPrice(uint256 newPrice_) internal {
        if (newPrice_ > MAX_PRICE) {
            revert InvalidNewPrice(newPrice_);
        }

        uint256 oldPrice = price;
        price = newPrice_;

        emit NewPrice(oldPrice, newPrice_);
    }

    ////////////////////////////////////////////////////////////////////////////////
    //  FUNCTIONS: FORECLOSURE
    ////////////////////////////////////////////////////////////////////////////////

    /**
     * @notice  Exit is a voluntary giving up of the orb. It's a combination of withdrawing all funds not owed to
     *          the issuer since last settlement, and foreclosing yourself after.
     *          Most useful if the issuer themselves hold the orb and want to re-auction it.
     *          For any other holder, setting the price to zero would be more practical.
     * @dev     Calls _withdraw(), which does value transfer from the contract.
     *          Emits Foreclosure() and Withdrawal().
     */
    function exit() external onlyHolder onlyHolderSolvent settles {
        price = 0;

        emit Foreclosure(msg.sender, true);

        _transferOrb(msg.sender, address(this));
        _withdraw(msg.sender, fundsOf[msg.sender]);
    }

    /**
     * @notice  Foreclose can be called by anyone after the orb holder runs out of funds to cover the Harberger tax.
     *          It returns the orb to the contract, readying it for re-auction.
     * @dev     Emits Foreclosure().
     */
    function foreclose() external onlyHolderHeld onlyHolderInsolvent settles {
        address holder = ERC721.ownerOf(ERIC_ORB_ID);
        price = 0;
        emit Foreclosure(holder, false);
        _transferOrb(holder, address(this));
    }

    /**
     * @notice  Foreclosure time is time when the current holder will no longer have enough funds to cover the
     *          Harberger tax and can be foreclosed.
     * @dev     Only valid if someone, not the contract, holds the orb.
     *          If orb is held by the issuer or if the price is zero, foreclosure time is a special value INFINITY.
     * @return  uint256  Timestamp of the foreclosure time.
     */
    function foreclosureTime() external view returns (uint256) {
        address holder = ERC721.ownerOf(ERIC_ORB_ID);
        if (owner() == holder) {
            return INFINITY;
        }

        // Avoid division by zero.
        if (price == 0) {
            return INFINITY;
        }

        uint256 remainingSeconds =
            (fundsOf[holder] * HOLDER_TAX_PERIOD * FEE_DENOMINATOR) / (price * holderTaxNumerator);
        return lastSettlementTime + remainingSeconds;
    }

    ////////////////////////////////////////////////////////////////////////////////
    //  FUNCTIONS: TRIGGERING AND RESPONDING
    ////////////////////////////////////////////////////////////////////////////////

    /**
     * @notice  Time remaining until the orb can be triggered again.
     *          Returns zero if the cooldown has expired and the orb is ready.
     * @dev     This function is only meaningful if the orb is not held by contract, and the holder is solvent.
     *          Contract itself cannot trigger the orb, so the response would be meaningless.
     * @return  uint256  Time in seconds until the orb is ready to be triggered.
     */
    function cooldownRemaining() external view returns (uint256) {
        uint256 cooldownExpires = lastTriggerTime + cooldown;
        if (block.timestamp >= cooldownExpires) {
            return 0;
        } else {
            return cooldownExpires - block.timestamp;
        }
    }

    /**
     * @notice  Triggers the orb (otherwise known as Orb Invocation). Allows the holder to submit cleartext.
     * @param   cleartext  Required cleartext.
     */
    function triggerWithCleartext(string memory cleartext) external {
        uint256 length = bytes(cleartext).length;
        if (length > MAX_CLEARTEXT_LENGTH) {
            revert CleartextTooLong(length, MAX_CLEARTEXT_LENGTH);
        }
        emit CleartextRecorded(triggersCount, cleartext);
        triggerWithHash(keccak256(abi.encodePacked(cleartext)));
    }

    /**
     * @notice  Triggers the orb (otherwise known as Orb Invocation). Allows the holder to submit content hash,
     *          that represents a question to the orb issuer.
     *          Puts the orb on cooldown.
     *          The Orb can only be triggered by solvent holders.
     * @dev     Content hash is keccak256 of the cleartext.
     *          triggersCount is used to track the id of the next trigger.
     *          Emits Triggered().
     * @param   contentHash  Required keccak256 hash of the cleartext.
     */
    function triggerWithHash(bytes32 contentHash) public onlyHolder onlyHolderHeld onlyHolderSolvent {
        if (block.timestamp < lastTriggerTime + cooldown) {
            revert CooldownIncomplete(lastTriggerTime + cooldown - block.timestamp);
        }

        uint256 triggerId = triggersCount;

        triggers[triggerId] = contentHash;
        lastTriggerTime = block.timestamp;
        triggersCount += 1;

        emit Triggered(msg.sender, triggerId, contentHash, block.timestamp);
    }

    /**
     * @notice  Function allows the holder to reveal cleartext later, either because it was challenged by the
     *          issuer, or just for posterity. This function can also be used to reveal empty-string content hashes.
     * @dev     Only holders can reveal cleartext on-chain. Anyone could potentially figure out the trigger cleartext
     *          from the content hash via brute force, but publishing this on-chain is only allowed by the holder
     *          themselves, introducing a reasonable privacy protection.
     *          If the content hash is of a cleartext that is longer than maximum cleartext length, the contract will
     *          never record this cleartext, as it is invalid.
     *          Allows overwriting. Assuming no hash collisions, this poses no risk, just wastes holder gas.
     * @param   triggerId  Triggred id, matching the one that was emitted when calling {trigger()}.
     * @param   cleartext  Cleartext, limited to tweet length. Must match the content hash.
     */
    function recordTriggerCleartext(uint256 triggerId, string memory cleartext) external onlyHolder onlyHolderSolvent {
        uint256 cleartextLength = bytes(cleartext).length;

        if (cleartextLength > MAX_CLEARTEXT_LENGTH) {
            revert CleartextTooLong(cleartextLength, MAX_CLEARTEXT_LENGTH);
        }

        bytes32 recordedContentHash = triggers[triggerId];
        bytes32 cleartextHash = keccak256(abi.encodePacked(cleartext));

        if (recordedContentHash != cleartextHash) {
            revert CleartextHashMismatch(cleartextHash, recordedContentHash);
        }

        emit CleartextRecorded(triggerId, cleartext);
    }

    /**
     * @notice  The Orb issuer can use this function to respond to any existing trigger, no matter how long ago
     *          it was made. A response to a trigger can only be written once. There is no way to record response
     *          cleartext on-chain.
     * @dev     Emits Responded().
     * @param   triggerId  ID of a trigger to which the response is being made.
     * @param   contentHash  keccak256 hash of the response text.
     */
    function respond(uint256 triggerId, bytes32 contentHash) external onlyOwner {
        if (triggerId >= triggersCount) {
            revert TriggerNotFound(triggerId);
        }

        if (_responseExists(triggerId)) {
            revert ResponseExists(triggerId);
        }

        responses[triggerId] = HashTime(contentHash, block.timestamp);

        emit Responded(msg.sender, triggerId, contentHash, block.timestamp);
    }

    /**
     * @notice  Orb holder can flag a response during Response Flagging Period, counting from when the response is made.
     *          Flag indicates a "report", that the orb holder was not satisfied with the response provided.
     *          This is meant to act as a social signal to future orb holders. It also increments flaggedResponsesCount,
     *          allowing anyone to quickly look up how many responses were flagged.
     * @dev     Only existing responses (with non-zero timestamps) can be flagged.
     *          Responses can only be flagged by solvent holders to keep it consistent with {trigger()}.
     *          Also, the holder must have received the orb after the response was made;
     *          this is to prevent holders from flagging responses that were made in response to others' triggers.
     *          Emits ResponseFlagged().
     * @param   triggerId  ID of a trigger to which the response is being flagged.
     */
    function flagResponse(uint256 triggerId) external onlyHolder onlyHolderSolvent {
        if (!_responseExists(triggerId)) {
            revert ResponseNotFound(triggerId);
        }

        // Response Flagging Period starts counting from when the response is made.
        uint256 responseTime = responses[triggerId].timestamp;
        if (block.timestamp - responseTime > responseFlaggingPeriod) {
            revert FlaggingPeriodExpired(triggerId, block.timestamp - responseTime, responseFlaggingPeriod);
        }
        if (holderReceiveTime >= responseTime) {
            revert FlaggingPeriodExpired(triggerId, holderReceiveTime, responseTime);
        }
        if (responseFlagged[triggerId]) {
            revert ResponseAlreadyFlagged(triggerId);
        }

        responseFlagged[triggerId] = true;
        flaggedResponsesCount += 1;

        emit ResponseFlagged(msg.sender, triggerId);
    }

    /**
     * @dev     Returns if a response to a trigger exists, based on the timestamp of the response being non-zero.
     * @param   triggerId_  ID of a trigger to which to check the existance of a response of.
     * @return  bool  If a response to a trigger exists or not.
     */
    function _responseExists(uint256 triggerId_) internal view returns (bool) {
        if (responses[triggerId_].timestamp != 0) {
            return true;
        }
        return false;
    }
}

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



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

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: address zero is not a valid owner");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _owners[tokenId];
        require(owner != address(0), "ERC721: invalid token ID");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireMinted(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not token owner nor approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        _requireMinted(tokenId);

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved");
        _safeTransfer(from, to, tokenId, data);
    }

    /**
     * @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.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _owners[tokenId] != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId);

        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId);

        // Clear approvals
        _approve(address(0), tokenId);

        _balances[owner] -= 1;
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` has not been minted yet.
     */
    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "ERC721: invalid token ID");
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``'s `tokenId` will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {}
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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
     * ====
     *
     * [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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(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) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(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) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason 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 {
            // 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/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/Strings.sol



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

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * 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/ERC165.sol



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

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

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