// File: /contracts/BoredBoxNFT.sol



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

//          +--------------------------------------------------+
//         /|                                                 /|
//        / |                                                / |
//       *--+-----------------------------------------------*  |
//       |  |                                               |  |
//       |  |                                               |  |
//       |  |                                               |  |
//       |  |   ██████╗  ██████╗ ██████╗ ███████╗██████╗    |  |
//       |  |   ██╔══██╗██╔═══██╗██╔══██╗██╔════╝██╔══██╗   |  |
//       |  |   ██████╔╝██║   ██║██████╔╝█████╗  ██║  ██║   |  |
//       |  |   ██╔══██╗██║   ██║██╔══██╗██╔══╝  ██║  ██║   |  |
//       |  |   ██████╔╝╚██████╔╝██║  ██║███████╗██████╔╝   |  |
//       |  |   ╚═════╝  ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═════╝    |  |
//       |  |                                               |  |
//       |  |                                               |  |
//       |  |                                               |  |
//       |  +-----------------------------------------------+--+
//       | /                                                | /
//       |/                                                 |/
//       *--------------------------------------------------*

import { BoredBoxStorage } from "@boredbox-solidity-contracts/bored-box-storage/contracts/BoredBoxStorage.sol";
import { IBoredBoxNFT_Functions } from "@boredbox-solidity-contracts/interface-bored-box-nft/contracts/IBoredBoxNFT.sol";
import { IValidateMint } from "@boredbox-solidity-contracts/interface-validate-mint/contracts/IValidateMint.sol";
import { Ownable } from "@boredbox-solidity-contracts/ownable/contracts/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { ERC721 } from "../contracts/token/ERC721/ERC721.sol";

/// @title Tracks BoredBox token ownership and coordinates minting
/// @author S0AndS0
/// @custom:link https://boredbox.io/
contract BoredBoxNFT is IBoredBoxNFT_Functions, BoredBoxStorage, ERC721, Ownable, ReentrancyGuard {
    uint256 public constant VALIDATE_STATUS__NA = 0;
    uint256 public constant VALIDATE_STATUS__PASS = 1;
    uint256 public constant VALIDATE_STATUS__FAIL = 2;

    /// Emitted after validateMint checks pass
    event Mint(address indexed to, uint256 indexed tokenId);

    /// Emitted after assets are fully distributed
    // @param tokenId pointer into `token__owner`, `token__opened_timestamp`, `token__status`, `token__generation`
    event Opened(uint256 indexed tokenId);

    /// Emitted when client requests a Box to be opened
    // @param from address of `msg.sender`
    // @param to address of `token__owner[tokenId]`
    // @param tokenId pointer into storage; `token__owner`, `token__opened_timestamp`, `token__status`, `token__generation`
    event RequestOpen(address indexed from, address indexed to, uint256 indexed tokenId);

    modifier onlyAuthorized() {
        require(
            msg.sender == this.owner() || (coordinator != address(0) && msg.sender == coordinator),
            "Not authorized"
        );
        _;
    }

    /// Called via `new BoredBoxNFT(/* ... */)`
    /// @param name_ NFT name to store in `name`
    /// @param symbol_ NFT symbol to pass to `ERC721` parent contract
    /// @param coordinator_ Address to store in `coordinator`
    /// @param uri_root string pointing to IPFS directory of JSON metadata files
    /// @param quantity Amount of tokens available for first generation
    /// @param price Exact `{ value: _price_ }` required by `mint()` function
    /// @param sale_time The `block.timestamp` to allow general requests to `mint()` function
    /// @param ref_validators List of addresses referencing `ValidateMint` contracts
    /// @param cool_down Time to add to current `block.timestamp` after `token__status` is set to `TOKEN_STATUS__OPENED`
    /// @custom:throw "Open time must be after sale time"
    constructor(
        address owner_,
        string memory name_,
        string memory symbol_,
        address coordinator_,
        string memory uri_root,
        uint256 quantity,
        uint256 price,
        uint256 sale_time,
        uint256 open_time,
        address[] memory ref_validators,
        uint256 cool_down
    ) ERC721(name_, symbol_) Ownable(owner_) {
        require(open_time >= sale_time, "Open time must be after sale time");

        coordinator = coordinator_;

        box__uri_root[1] = uri_root;
        box__lower_bound[1] = 1;
        box__upper_bound[1] = quantity;
        box__quantity[1] = quantity;
        box__price[1] = price;
        box__sale_time[1] = sale_time;
        box__cool_down[1] = cool_down;
        box__open_time[1] = open_time;
        box__validators[1] = ref_validators;

        current_box = 1;
    }

    /// @dev See {IBoredBoxNFT_Functions-mint}
    function mint(uint256 boxId, bytes memory auth) external payable {
        require(msg.value == box__price[boxId], "Incorrect amount sent");
        return _mintBox(msg.sender, boxId, auth);
    }

    /// Mutates `token__status` storage if checks pass
    /// @dev See {IBoredBoxNFT_Functions-setPending}
    function setPending(uint256[] memory tokenIds) external payable onlyAuthorized {
        uint256 length = tokenIds.length;
        require(length > 0, "No token IDs provided");

        uint256 tokenId;
        uint256 current__token__status;
        uint256 boxId;
        for (uint256 i; i < length; ) {
            tokenId = tokenIds[i];
            require(tokenId > 0, "Invalid token ID");

            unchecked {
                ++i;
            }

            current__token__status = token__status[tokenId];
            if (current__token__status == TOKEN_STATUS__PENDING) {
                continue;
            }

            require(current__token__status != TOKEN_STATUS__OPENED, "Already opened");

            boxId = token__generation[tokenId];
            require(boxId > 0, "Box does not exist");
            require(block.timestamp >= box__open_time[boxId], "Not time yet");

            token__status[tokenId] = TOKEN_STATUS__PENDING;
            emit RequestOpen(msg.sender, token__owner[tokenId], tokenId);
        }
    }

    /// @dev See {IBoredBoxNFT_Functions-box__allValidators}
    function box__allValidators(uint256 boxId) external view virtual returns (address[] memory) {
        return box__validators[boxId];
    }

    /// @dev See {IBoredBoxNFT_Functions-setOpened}
    function setOpened(uint256[] memory tokenIds) external payable onlyAuthorized {
        uint256 length = tokenIds.length;
        require(length > 0, "No token IDs provided");

        uint256 tokenId;
        for (uint256 i; i < length; ) {
            tokenId = tokenIds[i];
            require(tokenId > 0, "Invalid token ID");

            require(token__generation[tokenId] > 0, "Box does not exist");

            require(token__status[tokenId] == TOKEN_STATUS__PENDING, "Not yet pending delivery");

            token__status[tokenId] = 1;
            token__opened_timestamp[tokenId] = block.timestamp;

            emit Opened(tokenId);

            unchecked {
                ++i;
            }
        }
    }

    /// @dev See {IBoredBoxNFT_Functions-setOpened}
    function setBoxURI(uint256 boxId, string memory uri_root) external payable onlyAuthorized {
        require(boxId > 0, "Box does not exist");
        box__uri_root[boxId] = uri_root;
    }

    /// @dev See {IBoredBoxNFT_Functions-setIsPaused}
    function setIsPaused(uint256 boxId, bool is_paused) external payable onlyAuthorized {
        box__is_paused[boxId] = is_paused;
    }

    /// @dev See {IBoredBoxNFT_Functions-setAllPaused}
    function setAllPaused(bool is_paused) external payable onlyAuthorized {
        all_paused = is_paused;
    }

    /// @dev See {IBoredBoxNFT_Functions-setAllPaused}
    function setCoordinator(address coordinator_) external payable onlyOwner {
        coordinator = coordinator_;
    }

    /// @dev See {IBoredBoxNFT_Functions-setValidator}
    function setValidator(
        uint256 boxId,
        uint256 index,
        address ref_validator
    ) external payable onlyOwner {
        require(all_paused || box__is_paused[boxId], "Not paused");
        box__validators[boxId][index] = ref_validator;
    }

    /// @dev See {IBoredBoxNFT_Functions-newBox}
    function newBox(
        string memory uri_root,
        uint256 quantity,
        uint256 price,
        uint256 sale_time,
        uint256 open_time,
        address[] memory ref_validators,
        uint256 cool_down
    ) external payable onlyOwner {
        require(!all_paused, "New boxes are paused");
        require(open_time >= sale_time, "Open time must be after sale time");

        uint256 last_boxId = current_box;
        uint256 next_boxId = 1 + last_boxId;
        uint256 last_upper_bound = box__upper_bound[last_boxId];

        box__lower_bound[next_boxId] += 1 + last_upper_bound;
        box__upper_bound[next_boxId] = last_upper_bound + quantity;
        box__quantity[next_boxId] = quantity;
        box__price[next_boxId] = price;
        box__uri_root[next_boxId] = uri_root;
        box__validators[next_boxId] = ref_validators;
        box__sale_time[next_boxId] = sale_time;
        box__open_time[next_boxId] = open_time;
        box__cool_down[next_boxId] = cool_down;

        current_box = next_boxId;
    }

    /// @dev See {IBoredBoxNFT_Functions-withdraw}
    function withdraw(address payable to, uint256 amount) external payable onlyOwner nonReentrant {
        (bool success, ) = to.call{ value: amount }("");
        require(success, "Transfer failed");
    }

    /// @dev See {IERC721Metadata-tokenURI}
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(token__owner[tokenId] != address(0), "ERC721Metadata: URI query for nonexistent token");

        uint256 boxId = token__generation[tokenId];

        string memory uri_root = box__uri_root[boxId];
        require(bytes(uri_root).length > 0, "URI not set");

        uint256 current__token__status = token__status[tokenId];
        string memory uri_path;

        if (current__token__status == TOKEN_STATUS__CLOSED) {
            uri_path = "closed";
        } else if (current__token__status == TOKEN_STATUS__OPENED) {
            uri_path = "opened";
        } else if (current__token__status == TOKEN_STATUS__PENDING) {
            uri_path = "pending";
        }

        return string(abi.encodePacked("ipfs://", uri_root, "/", uri_path, ".json"));
    }

    /// @dev See {ERC721-_beforeTokenTransfer}
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual override {
        if (from == address(0)) {
            return;
        }

        uint256 current__token__status = token__status[tokenId];
        require(current__token__status != TOKEN_STATUS__PENDING, "Pending delivery");

        if (to == address(0)) {
            require(current__token__status == TOKEN_STATUS__OPENED, "Cannot burn un-opened Box");
            return;
        }

        if (current__token__status == TOKEN_STATUS__OPENED) {
            uint256 boxId = token__generation[tokenId];
            require(
                block.timestamp >= token__opened_timestamp[tokenId] + box__cool_down[boxId],
                "Need to let things cool down"
            );
        }
    }

    function _mintBox(
        address to,
        uint256 boxId,
        bytes memory auth
    ) internal nonReentrant {
        require(boxId > 0, "validateMint: boxId must be greater than zero");
        require(!all_paused && !box__is_paused[boxId], "Minting is paused");

        bytes32 hash_of_auth = sha256(auth);
        require(hash__auth_token[hash_of_auth] == 0, "Auth already used");

        uint256 quantity = box__quantity[boxId];
        require(quantity > 0, "No more for this round");
        uint256 tokenId = (box__upper_bound[boxId] + 1) - quantity;

        uint256 original_owner = token__original_owner[boxId][to];
        require(
            original_owner < box__lower_bound[boxId] || original_owner > box__upper_bound[boxId],
            "Limited to one mint per address"
        );

        bool all_validators_passed;
        uint256 validate_status;
        address[] memory _ref_validators = box__validators[boxId];
        uint256 length = _ref_validators.length;

        for (uint256 i; i < length; ) {
            if (_ref_validators[i] == address(0)) {
                all_validators_passed = false;
                break;
            }

            validate_status = IValidateMint(_ref_validators[i]).validate(to, boxId, tokenId, auth);
            unchecked {
                ++i;
            }

            if (validate_status == VALIDATE_STATUS__NA) {
                continue;
            } else if (validate_status == VALIDATE_STATUS__FAIL) {
                all_validators_passed = false;
                break;
            } else if (validate_status == VALIDATE_STATUS__PASS && length == i + 1) {
                all_validators_passed = true;
            }
        }

        if (!all_validators_passed) {
            require(box__sale_time[boxId] <= block.timestamp, "Please wait till sale time");
        }

        super._safeMint(to, tokenId);
        box__quantity[boxId] -= 1;
        hash__auth_token[hash_of_auth] = tokenId;
        token__generation[tokenId] = boxId;
        token__original_owner[boxId][to] = tokenId;
        emit Mint(to, tokenId);
    }
}

// File: /contracts/token/ERC721/ERC721.sol



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

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/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 ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Collection name
    string public name;

    // Collection symbol
    string public symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) public token__owner;

    // Mapping owner address to token count
    mapping(address => uint256) public balanceOf;

    // 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-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = token__owner[tokenId];
        require(owner != address(0), "ERC721: owner query for nonexistent token");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        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 overriden 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(
            msg.sender == owner || isApprovedForAll(owner, msg.sender),
            "ERC721: approve caller is not owner nor approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        require(_exists(tokenId), "ERC721: approved query for nonexistent token");

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(msg.sender, 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(msg.sender, tokenId), "ERC721: transfer caller is not 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(msg.sender, tokenId), "ERC721: transfer caller is not 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 token__owner[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) {
        require(_exists(tokenId), "ERC721: operator query for nonexistent token");
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, 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);

        balanceOf[to] += 1;
        token__owner[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);

        balanceOf[owner] -= 1;
        delete token__owner[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);

        balanceOf[from] -= 1;
        balanceOf[to] += 1;
        token__owner[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits a {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 a {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 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(msg.sender, 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 {
                    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/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/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/utils/Strings.sol



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

pragma solidity ^0.8.0;

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

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

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



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

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// 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/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.6.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 be 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/security/ReentrancyGuard.sol



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

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

        _;

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

// File: @boredbox-solidity-contracts/ownable/contracts/interfaces/IOwnable.sol



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

interface IOwnable_Variables {
    function owner() external view returns (address);
}

interface IOwnable_Functions {
    function transferOwnership(address newOwner) external;
}

interface IOwnable is IOwnable_Functions, IOwnable_Variables {}

// File: @boredbox-solidity-contracts/ownable/contracts/Ownable.sol



// SPDX-License-Identifier: MIT
// Inspired by OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import { IOwnable_Functions } from "./interfaces/IOwnable.sol";

abstract contract Ownable is IOwnable_Functions {
    address public owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor(address owner_) {
        owner = owner_ == address(0) ? msg.sender : owner_;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner == msg.sender, "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) external virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        address oldOwner = owner;
        owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @boredbox-solidity-contracts/interface-validate-mint/contracts/IValidateMint.sol



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

/// Completely optional contract that customizes mint requirements
interface IValidateMint {
    /// Throws `revert` or `require` error message to halt execution
    /// Returns 0 VALIDATE_STATUS__NA
    /// Returns 1 VALIDATE_STATUS__PASS
    /// Returns 2 VALIDATE_STATUS__FAIL
    /// It is up to caller to figure out what to do with returned `bool`
    /// @param to Address that will receive NFT if operation is valid
    /// @param boxId Generation key to possibly use internally or by checking calling contract strage
    /// @param tokenId Specific token ID that needs to be minted
    /// @param auth Optional extra data to require for validation process
    function validate(
        address to,
        uint256 boxId,
        uint256 tokenId,
        bytes memory auth
    ) external view returns (uint256 validate_status);
}

// File: @boredbox-solidity-contracts/interface-bored-box-nft/contracts/IBoredBoxNFT.sol



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

import { IBoredBoxStorage } from "@boredbox-solidity-contracts/bored-box-storage/contracts/interfaces/IBoredBoxStorage.sol";
import { IOwnable } from "@boredbox-solidity-contracts/ownable/contracts/interfaces/IOwnable.sol";

import { IERC721Metadata } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";

/* Function definitions */
interface IBoredBoxNFT_Functions {

    /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

    /// Attempt to mint new token for `current_box` generation
    /// @dev Sets `boxId` to `current_box` before passing execution to `_mintBox()` function
    /// @param auth Forwarded to any `ValidateMint` contract references set at `box__validators[boxId]`
    /// @custom:throw "Incorrect amount sent"
    function mint(
        uint256 boxId,
        bytes memory auth
    ) external payable;

    /// Bulk request array of `tokenIds` to have assets delivered
    /// @dev See {IBoredBoxNFT_Functions-open}
    /// @custom:throw "No token IDs provided"
    /// @custom:throw "Not authorized" if `msg.sender` is not contract owner
    /// @custom:throw "Invalid token ID" if `tokenId` is not greater than `0`
    /// @custom:throw "Not time yet" if `block.timestamp` is less than `box__open_time[boxId]`
    /// @custom:throw "Already opened"
    /// @custom:throw "Pending delivery"
    /// @custom:throw "Box does not exist"
    function setPending(uint256[] memory tokenIds) external payable;

    /// Attempt to set `token__status` and `token__opened_timestamp` storage
    /// @dev See {IBoredBoxNFT_Functions-setOpened}
    /// @custom:throw "No token IDs provided"
    /// @custom:throw "Not authorized"
    /// @custom:throw "Invalid token ID"
    /// @custom:throw "Box does not exist"
    /// @custom:throw "Not yet pending delivery"
    /// @custom:emit Opened
    /// @custom:emit PermanentURI
    function setOpened(uint256[] memory tokenIds) external payable;

    /// Set `box__uri_root` for given `tokenId` to `uri_root` value
    /// @custom:throw "Not authorized" if `msg.sender` is not contract owner
    /// @custom:throw "Box does not exist"
    function setBoxURI(uint256 boxId, string memory uri_root) external payable;

    /// Attempt to set `all__paused` storage
    /// @param is_paused Value to assign to storage
    /// @custom:throw "Not authorized"
    function setAllPaused(bool is_paused) external payable;

    /// Attempt to set `box__is_paused` storage
    /// @custom:throw "Not authorized"
    function setIsPaused(uint256 boxId, bool is_paused) external payable;

    /// Overwrite `coordinator` address
    /// @custom:throw "Ownable: caller is not the owner"
    function setCoordinator(address coordinator_) external payable;

    /// Insert reference address to validat-mint contract
    /// @param boxId Generation to insert data within `box__validators` mapping
    /// @param index Where in array of `box__validators[boxId]` to set reference
    /// @param ref_validator Address for ValidateMint contract
    /// @custom:throw "Ownable: caller is not the owner"
    /// @dev See {IValidateMint}
    function setValidator(
        uint256 boxId,
        uint256 index,
        address ref_validator
    ) external payable;

    /// @param uri_root String pointing to IPFS directory of JSON metadata files
    /// @param quantity Amount of tokens available for first generation
    /// @param price Exact `{ value: _price_ }` required by `mint()` function
    /// @param sale_time The `block.timestamp` to allow general requests to `mint()` function
    /// @param open_time The `block.timestamp` to allow `open` requests
    /// @param ref_validators List of addresses referencing `ValidateMint` contracts
    /// @param cool_down Add time to `block.timestamp` to prevent `transferFrom` after opening
    /// @custom:throw "Not authorized"
    /// @custom:throw "New boxes are paused"
    /// @custom:throw "Open time must be after sale time"
    function newBox(
        string memory uri_root,
        uint256 quantity,
        uint256 price,
        uint256 sale_time,
        uint256 open_time,
        address[] memory ref_validators,
        uint256 cool_down
    ) external payable;

    /// Helper function to return Array of all validation contract addresses for `boxId`
    /// @param boxId Generation key to get array from `box__validators` storage
    function box__allValidators(uint256 boxId) external view returns (address[] memory);

    /// Send amount of Ether from `this.balance` to some address
    /// @custom:throw "Ownable: caller is not the owner"
    /// @custom:throw "Transfer failed"
    function withdraw(address payable to, uint256 amount) external payable;
}

///
interface IBoredBoxNFT is IBoredBoxNFT_Functions, IBoredBoxStorage, IOwnable, IERC721Metadata {
    /* From ERC721 */
    // function balanceOf(address owner) external view returns (uint256 balance);
    // function ownerOf(uint256 tokenId) external view returns (address);
    // function transferFrom(address from, address to, uint256 tokenId) external;

    // @dev See {IERC721Metadata-tokenURI}.
    // function tokenURI(uint256 tokenId) external view returns (string memory);

    /// Attempt to retrieve `name` from storage
    /// @return Name for given `boxId` generation
    function name() external view returns (string memory);

    /* Function definitions from @openzeppelin/contracts/access/Ownable.sol */
    // function owner() external view returns (address);

    // function transferOwnership(address newOwner) external;

    /* Variable getters from contracts/tokens/ERC721/ERC721.sol */
    function token__owner(uint256) external view returns (address);
}

// File: @boredbox-solidity-contracts/bored-box-storage/contracts/interfaces/IBoredBoxStorage.sol



// SPDX-License-Identifier: MIT
// vim: textwidth=119
pragma solidity 0.8.11;

/* Variable getters */
interface IBoredBoxStorage {
    function current_box() external view returns (uint256);

    function coordinator() external view returns (address);

    function all_paused() external view returns (bool);

    /// Get paused state for given `boxId`
    function box__is_paused(uint256) external view returns (bool);

    /// Get latest URI root/hash for given `boxId`
    function box__uri_root(uint256) external view returns (string memory);

    /// Get first token ID allowed to be minted for given `boxId`
    function box__lower_bound(uint256) external view returns (uint256);

    /// Get last token ID allowed to be minted for given `boxId`
    function box__upper_bound(uint256) external view returns (uint256);

    /// Get remaining quantity of tokens for given `boxId`
    function box__quantity(uint256) external view returns (uint256);

    /// Get price for given `boxId`
    function box__price(uint256) external view returns (uint256);

    /// Get address to Validate contract for given `boxId` and array index
    function box__validators(uint256, uint256) external view returns (address);

    /// Get `block.timestamp` given `boxId` generation allows tokens to be sold
    function box__sale_time(uint256) external view returns (uint256);

    /// Get `block.timestamp` given `boxId` generation allows tokens to be opened
    function box__open_time(uint256) external view returns (uint256);

    /// Get amount of time added to `block.timestamp` for `boxId` when token is opened
    function box__cool_down(uint256) external view returns (uint256);

    /// Get token ID for given hash of auth
    function hash__auth_token(bytes32) external view returns (uint256);

    /// Get `block.timestamp` a given `tokenId` was opened
    function token__opened_timestamp(uint256) external view returns (uint256);

    /// Get _TokenStatus_ value for given `tokenId`
    function token__status(uint256) external view returns (uint256);

    /// Get `boxId` for given `tokenId`
    function token__generation(uint256) external view returns (uint256);

    /// Get `tokenId` for given `boxId` and owner
    function token__original_owner(uint256, address) external view returns (uint256);
}

// File: @boredbox-solidity-contracts/bored-box-storage/contracts/BoredBoxStorage.sol



// SPDX-License-Identifier: MIT
// vim: textwidth=119
pragma solidity 0.8.11;

/// Define additional data storage for BoredBoxNFT
abstract contract BoredBoxStorage {
    uint256 public constant TOKEN_STATUS__CLOSED = 0;
    uint256 public constant TOKEN_STATUS__OPENED = 1;
    uint256 public constant TOKEN_STATUS__PENDING = 2;

    // TODO: rename to something like `box__current_generation`
    uint256 public current_box;

    // Authorized to preform certain actions
    address public coordinator;

    bool public all_paused;

    // Mapping boxId to is paused state
    mapping(uint256 => bool) public box__is_paused;

    // Mapping boxId to URI IPFS root
    mapping(uint256 => string) public box__uri_root;

    // Mapping boxId to tokenId bounds
    mapping(uint256 => uint256) public box__lower_bound;
    mapping(uint256 => uint256) public box__upper_bound;

    // Mapping boxId to quantity
    mapping(uint256 => uint256) public box__quantity;

    // Mapping boxId to price
    mapping(uint256 => uint256) public box__price;

    // Mapping boxId to array of Validate contract references
    mapping(uint256 => address[]) public box__validators;

    // Mapping boxId to open sale
    mapping(uint256 => uint256) public box__sale_time;

    // Mapping boxId to open time
    mapping(uint256 => uint256) public box__open_time;

    // Mapping boxId to cool down after mint
    mapping(uint256 => uint256) public box__cool_down;

    // Mapping hash of auth to tokenId
    mapping(bytes32 => uint256) public hash__auth_token;

    // Mapping tokenId to opened timestamp
    mapping(uint256 => uint256) public token__opened_timestamp;

    // Mapping from tokenId to TokenStatus_{Closed,Opened,Pending} states
    mapping(uint256 => uint256) public token__status;

    // Mapping boxId to owner to tokenId
    mapping(uint256 => mapping(address => uint256)) public token__original_owner;

    // Mapping from tokenId to boxId
    mapping(uint256 => uint256) public token__generation;
}