ETH Price: $2,520.04 (+0.36%)

Transaction Decoder

Block:
17516497 at Jun-19-2023 09:36:23 PM +UTC
Transaction Fee:
0.001163912924323602 ETH $2.93
Gas Used:
82,318 Gas / 14.139227439 Gwei

Emitted Events:

302 ValhallaReserve.TransferSingle( operator=[Receiver] DNAV2, from=[Sender] 0x87b68015ed5f4891c20054703afb709ff4396ca6, to=0x00000000...000000000, id=1, value=1 )
303 DNAV2.Bought( tokenId=420, traitId=2, tokenDna=198092420628556068181655419679987903578045781425430432754319694639152, boosterVal=66380295596430784534475918110077311701130729036722874228898689753140240646498 )

Account State Difference:

  Address   Before After State Difference Code
5.880225687366801326 Eth5.880233919166801326 Eth0.0000082318
0x6417Bb5e...11f1860Ad
0x87B68015...Ff4396Ca6
0.005430747472105563 Eth
Nonce: 176
0.004266834547781961 Eth
Nonce: 177
0.001163912924323602
0xd1B68763...796A18a17

Execution Trace

DNAV2.reroll( tokenId=420, rerollTraitId=2 )
  • Valhalla.ownerOf( tokenId=420 ) => ( 0x87B68015Ed5F4891c20054703AFB709Ff4396Ca6 )
  • ValhallaReserve.approvedBurn( spender=0x87B68015Ed5F4891c20054703AFB709Ff4396Ca6, tokenId=1, amount=1 )
    • OperatorFilterRegistry.isOperatorAllowed( registrant=0xd1B68763C7170B963Ac6cA6B1C2EA25796A18a17, operator=0x6417Bb5ea597948ec4082D21a489e3e11f1860Ad ) => ( True )
      reroll[DNAV2 (ln:327)]
      File 1 of 4: DNAV2
      // 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);
          }
      }
      // 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;
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.18;
      import "@openzeppelin/contracts/access/Ownable.sol";
      import "erc721a/contracts/ERC721A.sol";
      /////////////////////////////////////////////////////////////////////////////
      //                                                                         //
      //                                                                         //
      //    ██╗░░░██╗░█████╗░██╗░░░░░██╗░░██╗░█████╗░██╗░░░░░██╗░░░░░░█████╗░    //
      //    ██║░░░██║██╔══██╗██║░░░░░██║░░██║██╔══██╗██║░░░░░██║░░░░░██╔══██╗    //
      //    ╚██╗░██╔╝███████║██║░░░░░███████║███████║██║░░░░░██║░░░░░███████║    //
      //    ░╚████╔╝░██╔══██║██║░░░░░██╔══██║██╔══██║██║░░░░░██║░░░░░██╔══██║    //
      //    ░░╚██╔╝░░██║░░██║███████╗██║░░██║██║░░██║███████╗███████╗██║░░██║    //
      //    ░░░╚═╝░░░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝╚══════╝╚══════╝╚═╝░░╚═╝    //
      //                                                                         //
      //                                                                         //
      /////////////////////////////////////////////////////////////////////////////
      /**
       * Subset of a Utility token contract with only the methods that the dna contract will call.
       */
      interface Utility {
          function approvedBurn(
              address spender,
              uint256 tokenId,
              uint256 amount
          ) external;
      }
      contract DNAV2 is Ownable {
          // =============================================================
          //                           CONSTANTS
          // =============================================================
          // Checks the `ownerOf` method of this address for tokenId reroll eligibility
          address public immutable TOKEN_CONTRACT;
          // Hash for the initial revealed tokens
          string public constant MINT_PROVENANCE_HASH =
              "037226b21636376001dbfd22f52d1dd72845efa9613baf51a6a011ac731b2327";
          // Hash for the tokens post armory v1 event
          string public constant ARMORY_V1_PROVENANCE_HASH =
              "60a731c1259c12c40f6eafee058235cb54eaed74593c7401b3568af30b74c65b";
          // Proof of hash will be given after all tokens are auctioned
          string public constant AUCTION_PROVENANCE_HASH =
              "eb8c88969a4b776d757de962a194f5b4ffaaadb991ecfbb24d806c7bc6397d30";
          // The Initial DNA is composed of 128 bits for each token
          // with each trait taking up 8 bits
          uint256 private constant _BITMASK_INITIAL_DNA = (1 << 8) - 1;
          // Offset in bits where the booster information will start
          uint256 private constant _BOOSTER_OFFSET = 128;
          // 11 rerollable traits will fit in 4 bits
          uint256 private constant _BITLEN_BOOSTER_TRAIT = 4;
          uint256 private constant _BITMASK_BOOSTER_TRAIT =
              (1 << _BITLEN_BOOSTER_TRAIT) - 1;
          uint256 private constant _BITLEN_SINGLE_BOOST = 10;
          uint256 private constant _BITMASK_SINGLE_BOOST =
              (1 << _BITLEN_SINGLE_BOOST) - 1;
          uint256 private constant _BITLEN_TRAIT_BOOST = 11;
          uint256 private constant _BITMASK_TRAIT_BOOST =
              (1 << _BITLEN_TRAIT_BOOST) - 1;
          // =============================================================
          //                            STORAGE
          // =============================================================
          // This IPFS code hash will have a function that can translate any token's
          // DNA into the corresponding traits. This logic is put here instead of on the
          // contract so that the gas fee for rerolling is minimal for the user.
          string public dnaTranslatorCodeHash;
          // Each call to reroll will give this many options to select during boost
          uint256 public numBoosts;
          // Defines what token is required to reroll traits
          address public utilityAddress;
          uint256 public utilityTokenId;
          // Only address allowed to change a token's dna.
          address public dnaInjectorAddress;
          // A token's dna cannot be changed unless both of these are active.
          bool public rerollActive;
          bool public boostingActive;
          // Mapping from traitId to whether it is rerollable
          mapping(uint256 => bool) public traitIdRerollable;
          // For pseudo-rng
          uint256 private _seed;
          // Mapping tokenId to DNA information. An extra bit is needed for
          // each trait because the random boosterValue does have a small
          // but non-zero probability to roll a 0. (1 in 1024)
          //
          // Bits Layout:
          // - [0..127]   `initialDna`
          // - [128]      `hasHairBooster`
          // - [129..138] `hairBooster`
          // - [139]      `hasClothesBooster`
          // - [140..149] `clothesBooster`
          // - [150]      `hasPrimaryBooster`
          // - [151..160] `primaryBooster`
          // - [161]      `hasHeadgearBooster`
          // - [162..171] `headgearBooster`
          // - [172]      `hasFaceBooster`
          // - [173..182] `faceBooster`
          // - [183]      `hasFaceAccBooster`
          // - [184..193] `faceAccBooster`
          // - [194]      `hasEyeBooster`
          // - [195..204] `eyeBooster`
          // - [205]      `hasMouthBooster`
          // - [206..215] `mouthBooster`
          // - [216]      `hasEarBooster`
          // - [217..226] `earBooster`
          // - [227]      `hasNeckBooster`
          // - [228..237] `neckBooster`
          // - [238]      `hasTattooBooster`
          // - [239..248] `tattooBooster`
          // - [249..255]  Extra Unused Bits
          mapping(uint256 => uint256) private _dna;
          // Bits Layout:
          // - [0..3]     `boosterIdx`
          // - [4..13]    `boosterRoll`
          // - [14..23]   `boosterRoll`
          // - [24..33]   `boosterRoll`
          // - [34..256]   Extra unused bits or more boosterRolls
          mapping(uint256 => uint256) public activeBooster;
          // =============================================================
          //                         Events
          // =============================================================
          event Bought(
              uint256 indexed tokenId,
              uint256 indexed traitId,
              uint256 tokenDna,
              uint256 boosterVal
          );
          event Boost(uint256 indexed tokenId, uint256 boosterId, uint256 tokenDna);
          // =============================================================
          //                         Constructor
          // =============================================================
          constructor(address tokenAddress) {
              TOKEN_CONTRACT = tokenAddress;
          }
          // =============================================================
          //                          Only Owner
          // =============================================================
          /**
           * @notice Allows the owner to update the IPFS code hash with a
           * function providing the translation between DNA and token traits.
           */
          function setDnaTranslatorCodeHash(
              string memory codeHash
          ) external onlyOwner {
              dnaTranslatorCodeHash = codeHash;
          }
          /**
           * @notice Allows the owner to change the number of selectable options per boost.
           */
          function setNumBoosts(uint256 updatedNumBoosts) external onlyOwner {
              numBoosts = updatedNumBoosts;
          }
          /**
           * @notice Allows the owner to change the dna of any tokenId and is used for initial dna injection.
           */
          function injectDna(
              uint256[] memory dna,
              uint256[] memory tokenIds
          ) external {
              if (msg.sender != dnaInjectorAddress) revert NotDnaInjector();
              for (uint i = 0; i < tokenIds.length; ) {
                  _dna[tokenIds[i]] = dna[i];
                  unchecked {
                      ++i;
                  }
              }
          }
          /**
           * @notice Allows the owner to update the dna translator script.
           */
          function setDnaInjector(address dnaInjector) external onlyOwner {
              dnaInjectorAddress = dnaInjector;
          }
          /**
           * @notice Allows the owner to select an address and token that must be burned to alter a token's
           * dna. This address must have an {approvedBurn} method that is callable by this contract for
           * another user's tokens.
           */
          function setRerollToken(address token, uint256 tokenId) external onlyOwner {
              utilityAddress = token;
              utilityTokenId = tokenId;
          }
          /**
           * @notice Allows the owner to enable or disable token owners from rolling their dna.
           */
          function setRerollActive(bool active) external onlyOwner {
              rerollActive = active;
          }
          /**
           * @notice Allows the owner to enable or disable token owners from finalizing rolls into their dna.
           */
          function setBoostingActive(bool active) external onlyOwner {
              boostingActive = active;
          }
          /**
           * @notice Allows the owner to set which traitIds are rerollable.
           */
          function setTraitIdRerollable(
              uint256 traitId,
              bool rerollable
          ) external onlyOwner {
              traitIdRerollable[traitId] = rerollable;
          }
          // =============================================================
          //                    Dna Interactions
          // =============================================================
          /**
           * @dev Returns the saved token dna for a given id. This dna can be translated into
           * metadata using the scripts that are part of the DNA_TRANSLATOR_CODE_HASH constant.
           */
          function getTokenDna(uint256 tokenId) external view returns (uint256) {
              return _dna[tokenId];
          }
          /**
           * @dev Adds an activeBooster to a given tokenId for a certain trait. The caller cannot be
           * a contract address and they must own both the Valhalla tokenId as well as the corresponding
           * Utility token to be burned.
           *
           * Note:
           * - A token CANNOT reroll a trait they do not have
           * - A token CAN override an existing activeBooster with another roll without calling {boost}
           * - The override is true even if a different rerollTraitId is selected from the first roll
           *
           * @param tokenId tokenId that the booster is attached to
           * @param rerollTraitId follows the mapping:
           * 0: Hair
           * 1: Clothes
           * 2: Primary
           * 3: Headgear
           * 4: Face
           * 5: FaceAcc
           * 6: Eye
           * 7: Mouth
           * 8: Ear
           * 9: Neck
           * 10: Tattoo
           */
          function reroll(uint256 tokenId, uint256 rerollTraitId) external {
              if (!rerollActive) revert RerollInactive();
              if (msg.sender != tx.origin) revert NotEOA();
              if (!traitIdRerollable[rerollTraitId]) revert TraitNotRerollable();
              if (IERC721A(TOKEN_CONTRACT).ownerOf(tokenId) != msg.sender)
                  revert NotTokenOwner();
              Utility(utilityAddress).approvedBurn(msg.sender, utilityTokenId, 1);
              // Cheaper gaswise to do left bitshift by 3 than to multiply rerollTraitId by 8
              if (
                  _dna[tokenId] &
                      (_BITMASK_INITIAL_DNA <<
                          (_correctedRerollTraitId(rerollTraitId) << 3)) ==
                  0
              ) revert TraitNotOnToken();
              // Shift _randomNumber up to make room for reroll traitId
              uint256 boosterVal = _randomNumber() << _BITLEN_BOOSTER_TRAIT;
              boosterVal = boosterVal | rerollTraitId;
              activeBooster[tokenId] = boosterVal;
              emit Bought(tokenId, rerollTraitId, _dna[tokenId], boosterVal);
          }
          /**
           * @dev Selects one of the boosters rolled from the {reroll} method and replaces the appropriate
           * section in the token dna's bits with one of the new values that was randomly rolled.
           */
          function boost(uint256 tokenId, uint256 boosterIdx) external {
              if (!boostingActive) revert BoostingInactive();
              if (IERC721A(TOKEN_CONTRACT).ownerOf(tokenId) != msg.sender)
                  revert NotTokenOwner();
              uint256 boosterVal = activeBooster[tokenId];
              if (boosterVal == 0) revert NoBoosterAtIdx();
              activeBooster[tokenId] = 0;
              if (boosterIdx >= numBoosts) revert InvalidBoostIdx();
              uint256 selectedVal = (boosterVal >>
                  (boosterIdx * _BITLEN_SINGLE_BOOST + _BITLEN_BOOSTER_TRAIT)) &
                  _BITMASK_SINGLE_BOOST;
              // This shifts the value up one bit and adds a flag to show that this trait has been boosted.
              // This is needed on the small chance that random value generated is exactly 0.
              selectedVal = (selectedVal << 1) | 1;
              uint256 rerollTraitId = boosterVal & _BITMASK_BOOSTER_TRAIT;
              uint256 traitShiftAmount = _correctedRerollTraitId(rerollTraitId) *
                  _BITLEN_TRAIT_BOOST +
                  _BOOSTER_OFFSET;
              _dna[tokenId] =
                  (_dna[tokenId] & ~(_BITMASK_TRAIT_BOOST << traitShiftAmount)) |
                  (selectedVal << traitShiftAmount);
              emit Boost(tokenId, boosterIdx, _dna[tokenId]);
          }
          /**
           * @dev Returns the corrected index of where rerollTraitId is located in the initial dna.
           * This is needed because Identity, Background, and Aura traits are not rerollable and thus the
           * rerollTraitId might not always match its location in the dna.
           */
          function _correctedRerollTraitId(
              uint256 _rerollTraitId
          ) internal pure returns (uint256) {
              if (_rerollTraitId < 3) return _rerollTraitId;
              return _rerollTraitId + 2;
          }
          /**
           * @dev Makes a pseudo-random number. Although there is some room for the block.timestamp to be
           * manipulated by miners, the random number used here is not used to determine something with high
           * impact such as determining a lottery winner.
           *
           * Implementing a more secure random number generator would lead to a worse reroll experience.
           */
          function _randomNumber() internal returns (uint256) {
              return
                  uint256(
                      keccak256(
                          abi.encodePacked(block.timestamp, block.prevrandao, ++_seed)
                      )
                  );
          }
          error BoostingInactive();
          error InvalidBoostIdx();
          error NoBoosterAtIdx();
          error NotDnaInjector();
          error NotEOA();
          error NotTokenOwner();
          error RerollInactive();
          error TraitNotRerollable();
          error TraitNotOnToken();
      }
      // SPDX-License-Identifier: MIT
      // ERC721A Contracts v4.2.3
      // Creator: Chiru Labs
      pragma solidity ^0.8.4;
      import './IERC721A.sol';
      /**
       * @dev Interface of ERC721 token receiver.
       */
      interface ERC721A__IERC721Receiver {
          function onERC721Received(
              address operator,
              address from,
              uint256 tokenId,
              bytes calldata data
          ) external returns (bytes4);
      }
      /**
       * @title ERC721A
       *
       * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
       * Non-Fungible Token Standard, including the Metadata extension.
       * Optimized for lower gas during batch mints.
       *
       * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
       * starting from `_startTokenId()`.
       *
       * Assumptions:
       *
       * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
       * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
       */
      contract ERC721A is IERC721A {
          // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
          struct TokenApprovalRef {
              address value;
          }
          // =============================================================
          //                           CONSTANTS
          // =============================================================
          // Mask of an entry in packed address data.
          uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
          // The bit position of `numberMinted` in packed address data.
          uint256 private constant _BITPOS_NUMBER_MINTED = 64;
          // The bit position of `numberBurned` in packed address data.
          uint256 private constant _BITPOS_NUMBER_BURNED = 128;
          // The bit position of `aux` in packed address data.
          uint256 private constant _BITPOS_AUX = 192;
          // Mask of all 256 bits in packed address data except the 64 bits for `aux`.
          uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
          // The bit position of `startTimestamp` in packed ownership.
          uint256 private constant _BITPOS_START_TIMESTAMP = 160;
          // The bit mask of the `burned` bit in packed ownership.
          uint256 private constant _BITMASK_BURNED = 1 << 224;
          // The bit position of the `nextInitialized` bit in packed ownership.
          uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;
          // The bit mask of the `nextInitialized` bit in packed ownership.
          uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;
          // The bit position of `extraData` in packed ownership.
          uint256 private constant _BITPOS_EXTRA_DATA = 232;
          // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
          uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
          // The mask of the lower 160 bits for addresses.
          uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;
          // The maximum `quantity` that can be minted with {_mintERC2309}.
          // This limit is to prevent overflows on the address data entries.
          // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}
          // is required to cause an overflow, which is unrealistic.
          uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
          // The `Transfer` event signature is given by:
          // `keccak256(bytes("Transfer(address,address,uint256)"))`.
          bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
              0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
          // =============================================================
          //                            STORAGE
          // =============================================================
          // The next token ID to be minted.
          uint256 private _currentIndex;
          // The number of tokens burned.
          uint256 private _burnCounter;
          // Token name
          string private _name;
          // Token symbol
          string private _symbol;
          // Mapping from token ID to ownership details
          // An empty struct value does not necessarily mean the token is unowned.
          // See {_packedOwnershipOf} implementation for details.
          //
          // Bits Layout:
          // - [0..159]   `addr`
          // - [160..223] `startTimestamp`
          // - [224]      `burned`
          // - [225]      `nextInitialized`
          // - [232..255] `extraData`
          mapping(uint256 => uint256) private _packedOwnerships;
          // Mapping owner address to address data.
          //
          // Bits Layout:
          // - [0..63]    `balance`
          // - [64..127]  `numberMinted`
          // - [128..191] `numberBurned`
          // - [192..255] `aux`
          mapping(address => uint256) private _packedAddressData;
          // Mapping from token ID to approved address.
          mapping(uint256 => TokenApprovalRef) private _tokenApprovals;
          // Mapping from owner to operator approvals
          mapping(address => mapping(address => bool)) private _operatorApprovals;
          // =============================================================
          //                          CONSTRUCTOR
          // =============================================================
          constructor(string memory name_, string memory symbol_) {
              _name = name_;
              _symbol = symbol_;
              _currentIndex = _startTokenId();
          }
          // =============================================================
          //                   TOKEN COUNTING OPERATIONS
          // =============================================================
          /**
           * @dev Returns the starting token ID.
           * To change the starting token ID, please override this function.
           */
          function _startTokenId() internal view virtual returns (uint256) {
              return 0;
          }
          /**
           * @dev Returns the next token ID to be minted.
           */
          function _nextTokenId() internal view virtual returns (uint256) {
              return _currentIndex;
          }
          /**
           * @dev Returns the total number of tokens in existence.
           * Burned tokens will reduce the count.
           * To get the total number of tokens minted, please see {_totalMinted}.
           */
          function totalSupply() public view virtual override returns (uint256) {
              // Counter underflow is impossible as _burnCounter cannot be incremented
              // more than `_currentIndex - _startTokenId()` times.
              unchecked {
                  return _currentIndex - _burnCounter - _startTokenId();
              }
          }
          /**
           * @dev Returns the total amount of tokens minted in the contract.
           */
          function _totalMinted() internal view virtual returns (uint256) {
              // Counter underflow is impossible as `_currentIndex` does not decrement,
              // and it is initialized to `_startTokenId()`.
              unchecked {
                  return _currentIndex - _startTokenId();
              }
          }
          /**
           * @dev Returns the total number of tokens burned.
           */
          function _totalBurned() internal view virtual returns (uint256) {
              return _burnCounter;
          }
          // =============================================================
          //                    ADDRESS DATA OPERATIONS
          // =============================================================
          /**
           * @dev Returns the number of tokens in `owner`'s account.
           */
          function balanceOf(address owner) public view virtual override returns (uint256) {
              if (owner == address(0)) revert BalanceQueryForZeroAddress();
              return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
          }
          /**
           * Returns the number of tokens minted by `owner`.
           */
          function _numberMinted(address owner) internal view returns (uint256) {
              return (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
          }
          /**
           * Returns the number of tokens burned by or on behalf of `owner`.
           */
          function _numberBurned(address owner) internal view returns (uint256) {
              return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
          }
          /**
           * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
           */
          function _getAux(address owner) internal view returns (uint64) {
              return uint64(_packedAddressData[owner] >> _BITPOS_AUX);
          }
          /**
           * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
           * If there are multiple variables, please pack them into a uint64.
           */
          function _setAux(address owner, uint64 aux) internal virtual {
              uint256 packed = _packedAddressData[owner];
              uint256 auxCasted;
              // Cast `aux` with assembly to avoid redundant masking.
              assembly {
                  auxCasted := aux
              }
              packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
              _packedAddressData[owner] = packed;
          }
          // =============================================================
          //                            IERC165
          // =============================================================
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30000 gas.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
              // The interface IDs are constants representing the first 4 bytes
              // of the XOR of all function selectors in the interface.
              // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
              // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
              return
                  interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
                  interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
                  interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
          }
          // =============================================================
          //                        IERC721Metadata
          // =============================================================
          /**
           * @dev Returns the token collection name.
           */
          function name() public view virtual override returns (string memory) {
              return _name;
          }
          /**
           * @dev Returns the token collection symbol.
           */
          function symbol() public view virtual override returns (string memory) {
              return _symbol;
          }
          /**
           * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
           */
          function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
              if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
              string memory baseURI = _baseURI();
              return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
          }
          /**
           * @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, it can be overridden in child contracts.
           */
          function _baseURI() internal view virtual returns (string memory) {
              return '';
          }
          // =============================================================
          //                     OWNERSHIPS OPERATIONS
          // =============================================================
          /**
           * @dev Returns the owner of the `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function ownerOf(uint256 tokenId) public view virtual override returns (address) {
              return address(uint160(_packedOwnershipOf(tokenId)));
          }
          /**
           * @dev Gas spent here starts off proportional to the maximum mint batch size.
           * It gradually moves to O(1) as tokens get transferred around over time.
           */
          function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
              return _unpackedOwnership(_packedOwnershipOf(tokenId));
          }
          /**
           * @dev Returns the unpacked `TokenOwnership` struct at `index`.
           */
          function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
              return _unpackedOwnership(_packedOwnerships[index]);
          }
          /**
           * @dev Initializes the ownership slot minted at `index` for efficiency purposes.
           */
          function _initializeOwnershipAt(uint256 index) internal virtual {
              if (_packedOwnerships[index] == 0) {
                  _packedOwnerships[index] = _packedOwnershipOf(index);
              }
          }
          /**
           * Returns the packed ownership data of `tokenId`.
           */
          function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) {
              uint256 curr = tokenId;
              unchecked {
                  if (_startTokenId() <= curr)
                      if (curr < _currentIndex) {
                          uint256 packed = _packedOwnerships[curr];
                          // If not burned.
                          if (packed & _BITMASK_BURNED == 0) {
                              // Invariant:
                              // There will always be an initialized ownership slot
                              // (i.e. `ownership.addr != address(0) && ownership.burned == false`)
                              // before an unintialized ownership slot
                              // (i.e. `ownership.addr == address(0) && ownership.burned == false`)
                              // Hence, `curr` will not underflow.
                              //
                              // We can directly compare the packed value.
                              // If the address is zero, packed will be zero.
                              while (packed == 0) {
                                  packed = _packedOwnerships[--curr];
                              }
                              return packed;
                          }
                      }
              }
              revert OwnerQueryForNonexistentToken();
          }
          /**
           * @dev Returns the unpacked `TokenOwnership` struct from `packed`.
           */
          function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
              ownership.addr = address(uint160(packed));
              ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
              ownership.burned = packed & _BITMASK_BURNED != 0;
              ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
          }
          /**
           * @dev Packs ownership data into a single uint256.
           */
          function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
              assembly {
                  // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                  owner := and(owner, _BITMASK_ADDRESS)
                  // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
                  result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
              }
          }
          /**
           * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
           */
          function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
              // For branchless setting of the `nextInitialized` flag.
              assembly {
                  // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
                  result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
              }
          }
          // =============================================================
          //                      APPROVAL OPERATIONS
          // =============================================================
          /**
           * @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) public payable virtual override {
              address owner = ownerOf(tokenId);
              if (_msgSenderERC721A() != owner)
                  if (!isApprovedForAll(owner, _msgSenderERC721A())) {
                      revert ApprovalCallerNotOwnerNorApproved();
                  }
              _tokenApprovals[tokenId].value = to;
              emit Approval(owner, to, tokenId);
          }
          /**
           * @dev Returns the account approved for `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function getApproved(uint256 tokenId) public view virtual override returns (address) {
              if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
              return _tokenApprovals[tokenId].value;
          }
          /**
           * @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) public virtual override {
              _operatorApprovals[_msgSenderERC721A()][operator] = approved;
              emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
          }
          /**
           * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
           *
           * See {setApprovalForAll}.
           */
          function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
              return _operatorApprovals[owner][operator];
          }
          /**
           * @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. See {_mint}.
           */
          function _exists(uint256 tokenId) internal view virtual returns (bool) {
              return
                  _startTokenId() <= tokenId &&
                  tokenId < _currentIndex && // If within bounds,
                  _packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned.
          }
          /**
           * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
           */
          function _isSenderApprovedOrOwner(
              address approvedAddress,
              address owner,
              address msgSender
          ) private pure returns (bool result) {
              assembly {
                  // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                  owner := and(owner, _BITMASK_ADDRESS)
                  // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
                  msgSender := and(msgSender, _BITMASK_ADDRESS)
                  // `msgSender == owner || msgSender == approvedAddress`.
                  result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
              }
          }
          /**
           * @dev Returns the storage slot and value for the approved address of `tokenId`.
           */
          function _getApprovedSlotAndAddress(uint256 tokenId)
              private
              view
              returns (uint256 approvedAddressSlot, address approvedAddress)
          {
              TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
              // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
              assembly {
                  approvedAddressSlot := tokenApproval.slot
                  approvedAddress := sload(approvedAddressSlot)
              }
          }
          // =============================================================
          //                      TRANSFER OPERATIONS
          // =============================================================
          /**
           * @dev Transfers `tokenId` from `from` to `to`.
           *
           * 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
          ) public payable virtual override {
              uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
              if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
              (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
              // The nested ifs save around 20+ gas over a compound boolean condition.
              if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                  if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
              if (to == address(0)) revert TransferToZeroAddress();
              _beforeTokenTransfers(from, to, tokenId, 1);
              // Clear approvals from the previous owner.
              assembly {
                  if approvedAddress {
                      // This is equivalent to `delete _tokenApprovals[tokenId]`.
                      sstore(approvedAddressSlot, 0)
                  }
              }
              // Underflow of the sender's balance is impossible because we check for
              // ownership above and the recipient's balance can't realistically overflow.
              // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
              unchecked {
                  // We can directly increment and decrement the balances.
                  --_packedAddressData[from]; // Updates: `balance -= 1`.
                  ++_packedAddressData[to]; // Updates: `balance += 1`.
                  // Updates:
                  // - `address` to the next owner.
                  // - `startTimestamp` to the timestamp of transfering.
                  // - `burned` to `false`.
                  // - `nextInitialized` to `true`.
                  _packedOwnerships[tokenId] = _packOwnershipData(
                      to,
                      _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
                  );
                  // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                  if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                      uint256 nextTokenId = tokenId + 1;
                      // If the next slot's address is zero and not burned (i.e. packed value is zero).
                      if (_packedOwnerships[nextTokenId] == 0) {
                          // If the next slot is within bounds.
                          if (nextTokenId != _currentIndex) {
                              // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                              _packedOwnerships[nextTokenId] = prevOwnershipPacked;
                          }
                      }
                  }
              }
              emit Transfer(from, to, tokenId);
              _afterTokenTransfers(from, to, tokenId, 1);
          }
          /**
           * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId
          ) public payable virtual override {
              safeTransferFrom(from, to, tokenId, '');
          }
          /**
           * @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 memory _data
          ) public payable virtual override {
              transferFrom(from, to, tokenId);
              if (to.code.length != 0)
                  if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
                      revert TransferToNonERC721ReceiverImplementer();
                  }
          }
          /**
           * @dev Hook that is called before a set of serially-ordered token IDs
           * are about to be transferred. This includes minting.
           * And also called before burning one token.
           *
           * `startTokenId` - the first token ID to be transferred.
           * `quantity` - the amount to be transferred.
           *
           * 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, `tokenId` will be burned by `from`.
           * - `from` and `to` are never both zero.
           */
          function _beforeTokenTransfers(
              address from,
              address to,
              uint256 startTokenId,
              uint256 quantity
          ) internal virtual {}
          /**
           * @dev Hook that is called after a set of serially-ordered token IDs
           * have been transferred. This includes minting.
           * And also called after one token has been burned.
           *
           * `startTokenId` - the first token ID to be transferred.
           * `quantity` - the amount to be transferred.
           *
           * Calling conditions:
           *
           * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
           * transferred to `to`.
           * - When `from` is zero, `tokenId` has been minted for `to`.
           * - When `to` is zero, `tokenId` has been burned by `from`.
           * - `from` and `to` are never both zero.
           */
          function _afterTokenTransfers(
              address from,
              address to,
              uint256 startTokenId,
              uint256 quantity
          ) internal virtual {}
          /**
           * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
           *
           * `from` - Previous owner of the given token ID.
           * `to` - Target address that will receive the token.
           * `tokenId` - Token ID to be transferred.
           * `_data` - Optional data to send along with the call.
           *
           * Returns whether the call correctly returned the expected magic value.
           */
          function _checkContractOnERC721Received(
              address from,
              address to,
              uint256 tokenId,
              bytes memory _data
          ) private returns (bool) {
              try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
                  bytes4 retval
              ) {
                  return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
              } catch (bytes memory reason) {
                  if (reason.length == 0) {
                      revert TransferToNonERC721ReceiverImplementer();
                  } else {
                      assembly {
                          revert(add(32, reason), mload(reason))
                      }
                  }
              }
          }
          // =============================================================
          //                        MINT OPERATIONS
          // =============================================================
          /**
           * @dev Mints `quantity` tokens and transfers them to `to`.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - `quantity` must be greater than 0.
           *
           * Emits a {Transfer} event for each mint.
           */
          function _mint(address to, uint256 quantity) internal virtual {
              uint256 startTokenId = _currentIndex;
              if (quantity == 0) revert MintZeroQuantity();
              _beforeTokenTransfers(address(0), to, startTokenId, quantity);
              // Overflows are incredibly unrealistic.
              // `balance` and `numberMinted` have a maximum limit of 2**64.
              // `tokenId` has a maximum limit of 2**256.
              unchecked {
                  // Updates:
                  // - `balance += quantity`.
                  // - `numberMinted += quantity`.
                  //
                  // We can directly add to the `balance` and `numberMinted`.
                  _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                  // Updates:
                  // - `address` to the owner.
                  // - `startTimestamp` to the timestamp of minting.
                  // - `burned` to `false`.
                  // - `nextInitialized` to `quantity == 1`.
                  _packedOwnerships[startTokenId] = _packOwnershipData(
                      to,
                      _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
                  );
                  uint256 toMasked;
                  uint256 end = startTokenId + quantity;
                  // Use assembly to loop and emit the `Transfer` event for gas savings.
                  // The duplicated `log4` removes an extra check and reduces stack juggling.
                  // The assembly, together with the surrounding Solidity code, have been
                  // delicately arranged to nudge the compiler into producing optimized opcodes.
                  assembly {
                      // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
                      toMasked := and(to, _BITMASK_ADDRESS)
                      // Emit the `Transfer` event.
                      log4(
                          0, // Start of data (0, since no data).
                          0, // End of data (0, since no data).
                          _TRANSFER_EVENT_SIGNATURE, // Signature.
                          0, // `address(0)`.
                          toMasked, // `to`.
                          startTokenId // `tokenId`.
                      )
                      // The `iszero(eq(,))` check ensures that large values of `quantity`
                      // that overflows uint256 will make the loop run out of gas.
                      // The compiler will optimize the `iszero` away for performance.
                      for {
                          let tokenId := add(startTokenId, 1)
                      } iszero(eq(tokenId, end)) {
                          tokenId := add(tokenId, 1)
                      } {
                          // Emit the `Transfer` event. Similar to above.
                          log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
                      }
                  }
                  if (toMasked == 0) revert MintToZeroAddress();
                  _currentIndex = end;
              }
              _afterTokenTransfers(address(0), to, startTokenId, quantity);
          }
          /**
           * @dev Mints `quantity` tokens and transfers them to `to`.
           *
           * This function is intended for efficient minting only during contract creation.
           *
           * It emits only one {ConsecutiveTransfer} as defined in
           * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
           * instead of a sequence of {Transfer} event(s).
           *
           * Calling this function outside of contract creation WILL make your contract
           * non-compliant with the ERC721 standard.
           * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
           * {ConsecutiveTransfer} event is only permissible during contract creation.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - `quantity` must be greater than 0.
           *
           * Emits a {ConsecutiveTransfer} event.
           */
          function _mintERC2309(address to, uint256 quantity) internal virtual {
              uint256 startTokenId = _currentIndex;
              if (to == address(0)) revert MintToZeroAddress();
              if (quantity == 0) revert MintZeroQuantity();
              if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
              _beforeTokenTransfers(address(0), to, startTokenId, quantity);
              // Overflows are unrealistic due to the above check for `quantity` to be below the limit.
              unchecked {
                  // Updates:
                  // - `balance += quantity`.
                  // - `numberMinted += quantity`.
                  //
                  // We can directly add to the `balance` and `numberMinted`.
                  _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                  // Updates:
                  // - `address` to the owner.
                  // - `startTimestamp` to the timestamp of minting.
                  // - `burned` to `false`.
                  // - `nextInitialized` to `quantity == 1`.
                  _packedOwnerships[startTokenId] = _packOwnershipData(
                      to,
                      _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
                  );
                  emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
                  _currentIndex = startTokenId + quantity;
              }
              _afterTokenTransfers(address(0), to, startTokenId, quantity);
          }
          /**
           * @dev Safely mints `quantity` tokens and transfers them to `to`.
           *
           * Requirements:
           *
           * - If `to` refers to a smart contract, it must implement
           * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
           * - `quantity` must be greater than 0.
           *
           * See {_mint}.
           *
           * Emits a {Transfer} event for each mint.
           */
          function _safeMint(
              address to,
              uint256 quantity,
              bytes memory _data
          ) internal virtual {
              _mint(to, quantity);
              unchecked {
                  if (to.code.length != 0) {
                      uint256 end = _currentIndex;
                      uint256 index = end - quantity;
                      do {
                          if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
                              revert TransferToNonERC721ReceiverImplementer();
                          }
                      } while (index < end);
                      // Reentrancy protection.
                      if (_currentIndex != end) revert();
                  }
              }
          }
          /**
           * @dev Equivalent to `_safeMint(to, quantity, '')`.
           */
          function _safeMint(address to, uint256 quantity) internal virtual {
              _safeMint(to, quantity, '');
          }
          // =============================================================
          //                        BURN OPERATIONS
          // =============================================================
          /**
           * @dev Equivalent to `_burn(tokenId, false)`.
           */
          function _burn(uint256 tokenId) internal virtual {
              _burn(tokenId, false);
          }
          /**
           * @dev Destroys `tokenId`.
           * The approval is cleared when the token is burned.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           *
           * Emits a {Transfer} event.
           */
          function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
              uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
              address from = address(uint160(prevOwnershipPacked));
              (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
              if (approvalCheck) {
                  // The nested ifs save around 20+ gas over a compound boolean condition.
                  if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                      if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
              }
              _beforeTokenTransfers(from, address(0), tokenId, 1);
              // Clear approvals from the previous owner.
              assembly {
                  if approvedAddress {
                      // This is equivalent to `delete _tokenApprovals[tokenId]`.
                      sstore(approvedAddressSlot, 0)
                  }
              }
              // Underflow of the sender's balance is impossible because we check for
              // ownership above and the recipient's balance can't realistically overflow.
              // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
              unchecked {
                  // Updates:
                  // - `balance -= 1`.
                  // - `numberBurned += 1`.
                  //
                  // We can directly decrement the balance, and increment the number burned.
                  // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
                  _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
                  // Updates:
                  // - `address` to the last owner.
                  // - `startTimestamp` to the timestamp of burning.
                  // - `burned` to `true`.
                  // - `nextInitialized` to `true`.
                  _packedOwnerships[tokenId] = _packOwnershipData(
                      from,
                      (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
                  );
                  // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                  if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                      uint256 nextTokenId = tokenId + 1;
                      // If the next slot's address is zero and not burned (i.e. packed value is zero).
                      if (_packedOwnerships[nextTokenId] == 0) {
                          // If the next slot is within bounds.
                          if (nextTokenId != _currentIndex) {
                              // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                              _packedOwnerships[nextTokenId] = prevOwnershipPacked;
                          }
                      }
                  }
              }
              emit Transfer(from, address(0), tokenId);
              _afterTokenTransfers(from, address(0), tokenId, 1);
              // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
              unchecked {
                  _burnCounter++;
              }
          }
          // =============================================================
          //                     EXTRA DATA OPERATIONS
          // =============================================================
          /**
           * @dev Directly sets the extra data for the ownership data `index`.
           */
          function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
              uint256 packed = _packedOwnerships[index];
              if (packed == 0) revert OwnershipNotInitializedForExtraData();
              uint256 extraDataCasted;
              // Cast `extraData` with assembly to avoid redundant masking.
              assembly {
                  extraDataCasted := extraData
              }
              packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
              _packedOwnerships[index] = packed;
          }
          /**
           * @dev Called during each token transfer to set the 24bit `extraData` field.
           * Intended to be overridden by the cosumer contract.
           *
           * `previousExtraData` - the value of `extraData` before transfer.
           *
           * 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, `tokenId` will be burned by `from`.
           * - `from` and `to` are never both zero.
           */
          function _extraData(
              address from,
              address to,
              uint24 previousExtraData
          ) internal view virtual returns (uint24) {}
          /**
           * @dev Returns the next extra data for the packed ownership data.
           * The returned result is shifted into position.
           */
          function _nextExtraData(
              address from,
              address to,
              uint256 prevOwnershipPacked
          ) private view returns (uint256) {
              uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
              return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
          }
          // =============================================================
          //                       OTHER OPERATIONS
          // =============================================================
          /**
           * @dev Returns the message sender (defaults to `msg.sender`).
           *
           * If you are writing GSN compatible contracts, you need to override this function.
           */
          function _msgSenderERC721A() internal view virtual returns (address) {
              return msg.sender;
          }
          /**
           * @dev Converts a uint256 to its ASCII string decimal representation.
           */
          function _toString(uint256 value) internal pure virtual returns (string memory str) {
              assembly {
                  // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
                  // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
                  // We will need 1 word for the trailing zeros padding, 1 word for the length,
                  // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
                  let m := add(mload(0x40), 0xa0)
                  // Update the free memory pointer to allocate.
                  mstore(0x40, m)
                  // Assign the `str` to the end.
                  str := sub(m, 0x20)
                  // Zeroize the slot after the string.
                  mstore(str, 0)
                  // Cache the end of the memory to calculate the length later.
                  let end := str
                  // We write the string from rightmost digit to leftmost digit.
                  // The following is essentially a do-while loop that also handles the zero case.
                  // prettier-ignore
                  for { let temp := value } 1 {} {
                      str := sub(str, 1)
                      // Write the character to the pointer.
                      // The ASCII index of the '0' character is 48.
                      mstore8(str, add(48, mod(temp, 10)))
                      // Keep dividing `temp` until zero.
                      temp := div(temp, 10)
                      // prettier-ignore
                      if iszero(temp) { break }
                  }
                  let length := sub(end, str)
                  // Move the pointer 32 bytes leftwards to make room for the length.
                  str := sub(str, 0x20)
                  // Store the length.
                  mstore(str, length)
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // ERC721A Contracts v4.2.3
      // Creator: Chiru Labs
      pragma solidity ^0.8.4;
      /**
       * @dev Interface of ERC721A.
       */
      interface IERC721A {
          /**
           * The caller must own the token or be an approved operator.
           */
          error ApprovalCallerNotOwnerNorApproved();
          /**
           * The token does not exist.
           */
          error ApprovalQueryForNonexistentToken();
          /**
           * Cannot query the balance for the zero address.
           */
          error BalanceQueryForZeroAddress();
          /**
           * Cannot mint to the zero address.
           */
          error MintToZeroAddress();
          /**
           * The quantity of tokens minted must be more than zero.
           */
          error MintZeroQuantity();
          /**
           * The token does not exist.
           */
          error OwnerQueryForNonexistentToken();
          /**
           * The caller must own the token or be an approved operator.
           */
          error TransferCallerNotOwnerNorApproved();
          /**
           * The token must be owned by `from`.
           */
          error TransferFromIncorrectOwner();
          /**
           * Cannot safely transfer to a contract that does not implement the
           * ERC721Receiver interface.
           */
          error TransferToNonERC721ReceiverImplementer();
          /**
           * Cannot transfer to the zero address.
           */
          error TransferToZeroAddress();
          /**
           * The token does not exist.
           */
          error URIQueryForNonexistentToken();
          /**
           * The `quantity` minted with ERC2309 exceeds the safety limit.
           */
          error MintERC2309QuantityExceedsLimit();
          /**
           * The `extraData` cannot be set on an unintialized ownership slot.
           */
          error OwnershipNotInitializedForExtraData();
          // =============================================================
          //                            STRUCTS
          // =============================================================
          struct TokenOwnership {
              // The address of the owner.
              address addr;
              // Stores the start time of ownership with minimal overhead for tokenomics.
              uint64 startTimestamp;
              // Whether the token has been burned.
              bool burned;
              // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
              uint24 extraData;
          }
          // =============================================================
          //                         TOKEN COUNTERS
          // =============================================================
          /**
           * @dev Returns the total number of tokens in existence.
           * Burned tokens will reduce the count.
           * To get the total number of tokens minted, please see {_totalMinted}.
           */
          function totalSupply() external view returns (uint256);
          // =============================================================
          //                            IERC165
          // =============================================================
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30000 gas.
           */
          function supportsInterface(bytes4 interfaceId) external view returns (bool);
          // =============================================================
          //                            IERC721
          // =============================================================
          /**
           * @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`,
           * 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,
              bytes calldata data
          ) external payable;
          /**
           * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId
          ) external payable;
          /**
           * @dev Transfers `tokenId` 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 payable;
          /**
           * @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 payable;
          /**
           * @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);
          // =============================================================
          //                        IERC721Metadata
          // =============================================================
          /**
           * @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);
          // =============================================================
          //                           IERC2309
          // =============================================================
          /**
           * @dev Emitted when tokens in `fromTokenId` to `toTokenId`
           * (inclusive) is transferred from `from` to `to`, as defined in the
           * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
           *
           * See {_mintERC2309} for more details.
           */
          event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
      }
      

      File 2 of 4: ValhallaReserve
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.9;
      import "./token/ERC1155/ERC1155.sol";
      import "./utils/ERC2981.sol";
      import "./utils/IERC165.sol";
      import "./utils/Ownable.sol";
      import "./utils/ECDSA.sol";
      /////////////////////////////////////////////////////////////////////////////
      //                                                                         //
      //                                                                         //
      //    ██╗░░░██╗░█████╗░██╗░░░░░██╗░░██╗░█████╗░██╗░░░░░██╗░░░░░░█████╗░    //
      //    ██║░░░██║██╔══██╗██║░░░░░██║░░██║██╔══██╗██║░░░░░██║░░░░░██╔══██╗    //
      //    ╚██╗░██╔╝███████║██║░░░░░███████║███████║██║░░░░░██║░░░░░███████║    //
      //    ░╚████╔╝░██╔══██║██║░░░░░██╔══██║██╔══██║██║░░░░░██║░░░░░██╔══██║    //
      //    ░░╚██╔╝░░██║░░██║███████╗██║░░██║██║░░██║███████╗███████╗██║░░██║    //
      //    ░░░╚═╝░░░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝╚══════╝╚══════╝╚═╝░░╚═╝    //
      //                                                                         //
      //                                                                         //
      /////////////////////////////////////////////////////////////////////////////
      /**
       * Subset of the IOperatorFilterRegistry with only the methods that the main minting contract will call.
       * The owner of the collection is able to manage the registry subscription on the contract's behalf
       */
      interface IOperatorFilterRegistry {
          function isOperatorAllowed(
              address registrant,
              address operator
          ) external returns (bool);
      }
      contract ValhallaReserve is ERC1155, Ownable, ERC2981 {
          using ECDSA for bytes32;
          // =============================================================
          //                            STRUCTS
          // =============================================================
          // Compiler will pack this into a 256bit word.
          struct SaleData {
              // unitPrice for each token for the general sale
              uint96 price;
              // Optional value to prevent a transaction from buying too much supply
              uint64 txLimit;
              // startTime for the sale of the tokens
              uint48 startTimestamp;
              // endTime for the sale of the tokens
              uint48 endTimestamp;
          }
          // =============================================================
          //                            STORAGE
          // =============================================================
          // Address that houses the implemention to check if operators are allowed or not
          address public operatorFilterRegistryAddress;
          // Address this contract verifies with the registryAddress for allowed operators.
          address public filterRegistrant;
          // Address used for the mintSignature method
          address public signer;
          // Used to quickly invalidate batches of signatures if needed.
          uint256 public signatureVersion;
          // Mapping that shows if a tier is active or not
          mapping(uint256 => mapping(string => bool)) public isTierActive;
          mapping(bytes32 => bool) public signatureUsed;
          
          // For tokens that are open to a general sale.
          mapping(uint256 => SaleData) public generalSaleData;
          // Mapping of owner-approved contracts that can burn the user's tokens during a transaction
          mapping(address => mapping(uint256 => bool)) public approvedBurners;
          // =============================================================
          //                            Events
          // =============================================================
          event MintOpen(
              uint256 indexed tokenId,
              uint256 startTimestamp,
              uint256 endTimestamp,
              uint256 price,
              uint256 txLimit
          );
          event MintClosed(uint256 indexed tokenId);
          // =============================================================
          //                          Constructor
          // =============================================================
          constructor () {
              _setName("ValhallaReserve");
              _setSymbol("RSRV");
          }
          // =============================================================
          //                            IERC165
          // =============================================================
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30000 gas.
           */
          function supportsInterface(
              bytes4 interfaceId
          ) public view virtual override(ERC1155, ERC2981) returns (bool) {
              // The interface IDs are constants representing the first 4 bytes
              // of the XOR of all function selectors in the interface.
              // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
              // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
              return
                  ERC1155.supportsInterface(interfaceId) ||
                  ERC2981.supportsInterface(interfaceId);
          }
          /**
           * @dev Allows the owner to set a new name for the collection.
           */
          function setName(string memory name) external onlyOwner {
              _setName(name);
          }
          /**
           * @dev Allows the owner to set a new symbol for the collection.
           */
          function setSymbol(string memory symbol) external onlyOwner {
              _setSymbol(symbol);
          }
          /**
           * @dev Allows the owner to add a new tokenId if it does not already exist.
           * 
           * @param tokenId TokenId that will get created
           * @param tokenMintLimit Token Supply for the tokenId. If 0, the supply is capped at uint64 max.
           * @param uri link pointing to the token metadata
           */
          function addTokenId(uint256 tokenId, uint64 tokenMintLimit, string calldata uri) external onlyOwner {
              _addTokenId(tokenId, tokenMintLimit, uri);
          }
          /**
           * @dev Allows the owner to set a new token URI for a single tokenId.
           * 
           * This tokenId must have already been added by `addTokenId`
           */
          function updateTokenURI(uint256 tokenId, string calldata uri) external onlyOwner {
              _updateMetadata(tokenId, uri);
          }
          /**
           * @dev Token supply can be set, but can ONLY BE LOWERED. It also cannot be lower than the current supply.
           *
           * This logic is gauranteed by the {_setTokenMintLimit} method
           */
          function setTokenMintLimit(uint256 tokenId, uint64 tokenMintLimit) external onlyOwner {
              _setTokenMintLimit(tokenId, tokenMintLimit);
          }
       
          // =============================================================
          //                           IERC2981
          // =============================================================
          /**
           * @notice Allows the owner to set default royalties following EIP-2981 royalty standard.
           */
          function setDefaultRoyalty(
              address receiver,
              uint96 feeNumerator
          ) external onlyOwner {
              _setDefaultRoyalty(receiver, feeNumerator);
          }
          // =============================================================
          //                 Operator Filter Registry
          // =============================================================
          /**
           * @dev Stops operators from being added as an approved address to transfer.
           * @param operator the address a wallet is trying to grant approval to.
           */
          function _beforeApproval(address operator) internal virtual override {
              if (operatorFilterRegistryAddress.code.length > 0) {
                  if (
                      !IOperatorFilterRegistry(operatorFilterRegistryAddress)
                          .isOperatorAllowed(filterRegistrant, operator)
                  ) {
                      revert OperatorNotAllowed();
                  }
              }
              super._beforeApproval(operator);
          }
          /**
           * @dev Stops operators that are not approved from doing transfers.
           */
          function _beforeTokenTransfer(
              address operator,
              address from,
              address to,
              uint256[] memory ids,
              uint256[] memory amounts,
              bytes memory data
          ) internal virtual override {
              if (operatorFilterRegistryAddress.code.length > 0) {
                  if (
                      !IOperatorFilterRegistry(operatorFilterRegistryAddress)
                          .isOperatorAllowed(filterRegistrant, msg.sender)
                  ) {
                      revert OperatorNotAllowed();
                  }
              }
              super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
          }
          /**
           * @notice Allows the owner to set a new registrant contract.
           */
          function setOperatorFilterRegistryAddress(
              address registryAddress
          ) external onlyOwner {
              operatorFilterRegistryAddress = registryAddress;
          }
          /**
           * @notice Allows the owner to set a new registrant address.
           */
          function setFilterRegistrant(address newRegistrant) external onlyOwner {
              filterRegistrant = newRegistrant;
          }
          // =============================================================
          //                        Token Minting
          // =============================================================
          /**
           * @dev This function does a best effort to Owner mint. If a given tokenId is
           * over the token supply amount, it will mint as many are available and stop at the limit.
           * This is necessary so that a given transaction does not fail if another public mint
           * transaction happens to take place just before this one that would cause the amount of
           * minted tokens to go over a token limit.
           */
          function mintDev(
              address[] calldata receivers,
              uint256[] calldata tokenIds,
              uint256[] calldata amounts
          ) external onlyOwner {
              if (
                  receivers.length != tokenIds.length ||
                  receivers.length != amounts.length
              ) {
                  revert ArrayLengthMismatch();
              }
              for (uint256 i = 0; i < receivers.length; ) {
                  uint256 buyLimit = _remainingSupply(tokenIds[i]);
                  if (buyLimit != 0) {
                      if (amounts[i] > buyLimit) {
                          _mint(receivers[i], tokenIds[i], buyLimit, "");
                      } else {
                          _mint(receivers[i], tokenIds[i], amounts[i], "");
                      }
                  }
                  unchecked {
                      ++i;
                  }
              }
          }
          /**
           * @notice Allows the owner to change the active version of their signatures, this also
           * allows a simple invalidation of all signatures they have created on old versions.
           */
          function setSigner(address signer_) external onlyOwner {
              signer = signer_;
          }
          /**
           * @notice Allows the owner to change the active version of their signatures, this also
           * allows a simple invalidation of all signatures they have created on old versions.
           */
          function setSignatureVersion(uint256 version) external onlyOwner {
              signatureVersion = version;
          }
          /**
           * @notice Allows owner to sets if a certain tier is active or not.
           */
          function setIsTierActive(
              uint256 tokenId,
              string memory tier,
              bool active
          ) external onlyOwner {
              isTierActive[tokenId][tier] = active;
          }
          
          /**
           * @dev With the correct hash signed by the owner, a wallet can mint at
           * a unit price up to the quantity specified.
           */
          function mintSignature(
              string memory tier,
              uint256 tokenId,
              uint256 unitPrice,
              uint256 version,
              uint256 nonce,
              uint256 amount,
              uint256 buyAmount,
              bytes memory sig
          ) external payable {
              _verifyTokenMintLimit(tokenId, buyAmount);
              if (!isTierActive[tokenId][tier]) revert TierNotActive();
              if (buyAmount > amount || buyAmount == 0) revert InvalidSignatureBuyAmount();
              if (version != signatureVersion) revert InvalidSignatureVersion();
              uint256 totalPrice = unitPrice * buyAmount;
              if (msg.value != totalPrice) revert IncorrectMsgValue();
              bytes32 hash = ECDSA.toEthSignedMessageHash(
                  keccak256(
                      abi.encode(
                          tier,
                          address(this),
                          tokenId,
                          unitPrice,
                          version,
                          nonce,
                          amount,
                          msg.sender
                      )
                  )
              );
              if (signatureUsed[hash]) revert SignatureAlreadyUsed();
              signatureUsed[hash] = true;
              if (hash.recover(sig) != signer) revert InvalidSignature();
              _mint(_msgSender(), tokenId, buyAmount, "");
          }
          /**
           * @dev Allows the owner to open the {mint} method for a certain tokenId
           * this method is to allow buyers to save gas on minting by not requiring a signature.
           */
          function openMint(
              uint256 tokenId,
              uint96 price,
              uint48 startTimestamp,
              uint48 endTimestamp,
              uint64 txLimit
          ) external onlyOwner {
              if(!exists(tokenId)) revert NonExistentToken();
              generalSaleData[tokenId].price = price;
              generalSaleData[tokenId].startTimestamp = startTimestamp;
              generalSaleData[tokenId].endTimestamp = endTimestamp;
              generalSaleData[tokenId].txLimit = txLimit;
              emit MintOpen(
                  tokenId,
                  startTimestamp,
                  endTimestamp,
                  price,
                  txLimit
              );
          }
          /**
           * @dev Allows the owner to close the {generalMint} method to the public for a certain tokenId.
           */
          function closeMint(uint256 tokenId) external onlyOwner {
              delete generalSaleData[tokenId];
              emit MintClosed(tokenId);
          }
          /**
           * @dev Allows any user to buy a certain tokenId. This buy transaction is still limited by the
           * wallet mint limit, token supply limit, and transaction limit set for the tokenId. These are
           * all considered primary sales and will be split according to the withdrawal splits defined in the contract.
           */
          function mint(uint256 tokenId, uint256 buyAmount) external payable {
              _verifyTokenMintLimit(tokenId, buyAmount);
              if (block.timestamp < generalSaleData[tokenId].startTimestamp) revert MintNotActive();
              if (block.timestamp > generalSaleData[tokenId].endTimestamp) revert MintNotActive();
              if (
                  generalSaleData[tokenId].txLimit != 0 &&
                  buyAmount > generalSaleData[tokenId].txLimit
              ) {
                  revert OverTransactionLimit();
              }
              if (msg.value != generalSaleData[tokenId].price * buyAmount) revert IncorrectMsgValue();
              _mint(_msgSender(), tokenId, buyAmount, "");
          }
          // =============================================================
          //                        Token Burning
          // =============================================================
          /**
           * @dev Owner can allow or pause holders from burning tokens of a certain
           * tokenId on without an intermediary contract.
           */
          function setBurnable(uint256 tokenId, bool burnable) external onlyOwner {
              _setBurnable(tokenId, burnable);
          }
          /**
           * @dev Allows token owners to burn tokens if self-burn is enabled for that token.
           */
          function burn(uint256 tokenId, uint256 amount) external {
              if(!_isSelfBurnable(tokenId)) revert NotSelfBurnable();
              _burn(msg.sender, tokenId, amount);
          }
          /**
           * @dev Owner can allow for certain contract addresses to burn tokens for users.
           * 
           * If this is an EOA, the approvedBurn transaction will revert.
           */
          function setApprovedBurner(
              address burner, 
              uint256 tokenId, 
              bool approved
          ) external onlyOwner {
              approvedBurners[burner][tokenId] = approved;
          }
          /**
           * @dev Allows token owners to burn their tokens through owner-approved burner contracts.
           */
          function approvedBurn(address spender, uint256 tokenId, uint256 amount) external {
              if (!approvedBurners[msg.sender][tokenId]) revert SenderNotApprovedBurner();
              if (tx.origin == msg.sender) revert NotContractAccount();
              _burn(spender, tokenId, amount);
          }
          // =============================================================
          //                        Miscellaneous
          // =============================================================
          /**
           * @notice Allows owner to withdraw a specified amount of ETH to a specified address.
           */
          function withdraw(
              address withdrawAddress,
              uint256 amount
          ) external onlyOwner {
              unchecked {
                  if (amount > address(this).balance) {
                      amount = address(this).balance;
                  }
              }
              if (!_transferETH(withdrawAddress, amount)) revert WithdrawFailed();
          }
          /**
           * @notice Internal function to transfer ETH to a specified address.
           */
          function _transferETH(address to, uint256 value) internal returns (bool) {
              (bool success, ) = to.call{ value: value, gas: 30000 }(new bytes(0));
              return success;
          }
          
          error IncorrectMsgValue();
          error InvalidSignature();
          error InvalidSignatureBuyAmount();
          error InvalidSignatureVersion();
          error MintNotActive();
          error NotContractAccount();
          error NotSelfBurnable();
          error OperatorNotAllowed();
          error OverTransactionLimit();
          error SenderNotApprovedBurner();
          error SignatureAlreadyUsed();
          error TierNotActive();
          error WithdrawFailed();
      }// SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
      pragma solidity ^0.8.0;
      import "./IERC1155.sol";
      import "./IERC1155Receiver.sol";
      import "./IERC1155MetadataURI.sol";
      import "../../utils/Address.sol";
      import "../../utils/Strings.sol";
      import "../../utils/ERC165.sol";
      /**
       * @dev Implementation of the basic standard multi-token.
       * See https://eips.ethereum.org/EIPS/eip-1155
       * Originally based on code by Enjin: https://github.com/enjin/erc-1155
       *
       * There are some modifications compared to the originial OpenZepplin implementation
       * that give the collection owner mint limits for their tokenIds. It also has been
       * adjusted to have a max supply of uint64 of any tokenId for gas optimization.
       *
       * _Available since v3.1._
       */
      contract ERC1155 is IERC1155 {
          using Address for address;
          using Strings for uint256;
          // =============================================================
          //                            STRUCTS
          // =============================================================
          // Compiler will pack this into a single 256bit word.
          struct TokenAddressData {
              // Limited to uint64 to save gas fees.
              uint64 balance;
              // Keeps track of mint count for a user of a tokenId.
              uint64 numMinted;
              // Keeps track of burn count for a user of a tokenId.
              uint64 numBurned;
              // For miscellaneous variable(s) pertaining to the address
              // (e.g. number of whitelist mint slots used).
              // If there are multiple variables, please pack them into a uint64.
              uint64 aux;
          }
          // Compiler will pack this into a single 256bit word.
          struct TokenSupplyData {
              // Keeps track of mint count of a tokenId.
              uint64 numMinted;
              // Keeps track of burn count of a tokenId.
              uint64 numBurned;
              // Keeps track of maximum supply of a tokenId.
              uint64 tokenMintLimit;
              // If the token is self-burnable or not
              bool burnable;
          }
          // =============================================================
          //                            Constants
          // =============================================================
          uint64 public MAX_TOKEN_SUPPLY = (1 << 64) - 1;
          // =============================================================
          //                            STORAGE
          // =============================================================
          // Used to enable the uri method
          mapping(uint256 => string) public tokenMetadata;
          // Saves all the token mint/burn data and mint limitations.
          mapping(uint256 => TokenSupplyData) private _tokenData;
          // Mapping from token ID to account balances, mints, and burns
          mapping(uint256 => mapping(address => TokenAddressData)) private _balances;
          // Mapping from account to operator approvals
          mapping(address => mapping(address => bool)) private _operatorApprovals;
          // Token name
          string private _name;
          // Token symbol
          string private _symbol;
          // =============================================================
          //                            EVENTS
          // =============================================================
          event NewTokenAdded(
              uint256 indexed tokenId,
              uint256 tokenMintLimit,
              string tokenURI
          );
          event TokenURIChanged(uint256 tokenId, string newTokenURI);
          event TokenMintLimitChanged(uint256 tokenId, uint64 newMintLimit);
          event NameChanged(string name);
          event SymbolChanged(string symbol);
          // =============================================================
          //                          CONSTRUCTOR
          // =============================================================
          constructor() {}
          // =============================================================
          //                            IERC165
          // =============================================================
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId)
              public
              view
              virtual
              override(IERC165)
              returns (bool)
          {
              return
                  interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
                  interfaceId == 0xd9b67a26 || // ERC165 interface ID for ERC1155.
                  interfaceId == 0x0e89341c; // ERC165 interface ID for ERC1155MetadatURI.
          }
          // =============================================================
          //                    IERC1155MetadataURI
          // =============================================================
          /**
           * @dev See {IERC721Metadata-symbol}.
           */
          function name() public view returns (string memory) {
              return _name;
          }
          /**
           * @dev See {IERC721Metadata-symbol}.
           */
          function symbol() public view returns (string memory) {
              return _symbol;
          }
          /**
           * @dev updates the name of the collection
           */
          function _setName(string memory _newName) internal {
              _name = _newName;
              emit NameChanged(_newName);
          }
          /**
           * @dev updates the symbol of the collection
           */
          function _setSymbol(string memory _newSymbol) internal {
              _symbol = _newSymbol;
              emit SymbolChanged(_newSymbol);
          }
          /**
           * @dev See {IERC1155MetadataURI-uri}.
           *
           * This implementation returns the same URI for *all* token types. It relies
           * on the token type ID substitution mechanism
           * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
           *
           * Clients calling this function must replace the `\\{id\\}` substring with the
           * actual token type ID.
           */
          function uri(uint256 tokenId) public view returns (string memory) {
              if (!exists(tokenId)) revert NonExistentToken();
              return tokenMetadata[tokenId];
          }
          /**
           * @dev Allows the owner to change the metadata for a tokenId but NOT the mint limits.
           *
           * Requirements:
           *
           * - `tokenId` must have already been added.
           * - `metadata` must not be length 0.
           */
          function _updateMetadata(uint256 tokenId, string calldata metadata)
              internal
          {
              if (!exists(tokenId)) revert NonExistentToken();
              if (bytes(metadata).length == 0) revert InvalidMetadata();
              tokenMetadata[tokenId] = metadata;
              emit TokenURIChanged(tokenId, metadata);
          }
          // =============================================================
          //                          IERC1155
          // =============================================================
          /**
           * @dev Returns if a tokenId has been added to the collection yet.
           */
          function exists(uint256 tokenId) public view returns (bool) {
              return bytes(tokenMetadata[tokenId]).length > 0;
          }
          /**
           * @dev Allows the owner to add a tokenId to the collection with the specificed
           * metadata and mint limits. MintLimit of 0 will be treated as uint64 max.
           * 
           * NOTE: MINT LIMITS CANNOT BE INCREASED
           *
           * Requirements:
           *
           * - `tokenId` must not have been added yet.
           * - `metadata` must not be length 0.
           *
           * @param tokenId of the new addition to the colleciton
           * @param tokenMintLimit the most amount of tokens that can ever be minted
           * @param metadata for the new collection when calling uri
           */
          function _addTokenId(
              uint256 tokenId,
              uint64 tokenMintLimit,
              string calldata metadata
          ) internal {
              if (exists(tokenId)) revert TokenAlreadyExists();
              if (bytes(metadata).length == 0) revert InvalidMetadata();
              tokenMetadata[tokenId] = metadata;
              _tokenData[tokenId].tokenMintLimit = tokenMintLimit;
              if (tokenMintLimit == 0) {
                  _tokenData[tokenId].tokenMintLimit = MAX_TOKEN_SUPPLY;
              }
              emit NewTokenAdded(tokenId, tokenMintLimit, metadata);
          }
          /**
           * @dev Token supply can be set, but can ONLY BE LOWERED. Cannot be lower than the current supply.
           */
          function _setTokenMintLimit(
              uint256 tokenId, 
              uint64 tokenMintLimit
          ) internal {
              if (_tokenData[tokenId].numMinted > tokenMintLimit) revert InvalidMintLimit();
              if (tokenMintLimit == 0) revert InvalidMintLimit();
              _tokenData[tokenId].tokenMintLimit = tokenMintLimit;
              emit TokenMintLimitChanged(tokenId, tokenMintLimit);
          }
          /**
           * @dev See {IERC1155-balanceOf}.
           *
           * Requirements:
           *
           * - `account` cannot be the zero address.
           */
          function balanceOf(address account, uint256 id)
              public
              view
              virtual
              override
              returns (uint256)
          {
              if (account == address(0)) revert BalanceQueryForZeroAddress();
              return _balances[id][account].balance;
          }
          /**
           * @dev returns the total amount of tokens of a certain tokenId are in circulation.
           */
          function totalSupply(uint256 tokenId)
              public
              view
              virtual
              returns (uint256)
          {
              if (!exists(tokenId)) revert NonExistentToken();
              return _tokenData[tokenId].numMinted - _tokenData[tokenId].numBurned;
          }
          /**
           * @dev returns the total amount of tokens of a certain tokenId that were ever minted.
           */
          function totalMinted(uint256 tokenId)
              public
              view
              virtual
              returns (uint256)
          {
              if (!exists(tokenId)) revert NonExistentToken();
              return _tokenData[tokenId].numMinted;
          }
          /**
           * @dev returns the total amount of tokens of a certain tokenId that have gotten burned.
           */
          function totalBurned(uint256 tokenId)
              public
              view
              virtual
              returns (uint256)
          {
              if (!exists(tokenId)) revert NonExistentToken();
              return _tokenData[tokenId].numBurned;
          }
          /**
           * @dev Returns how much an address has minted of a certain id
           *
           * Requirements:
           *
           * - `account` cannot be the zero address.
           */
          function totalMintedByAddress(address account, uint256 id)
              public
              view
              virtual
              returns (uint256)
          {
              if (account == address(0)) revert BalanceQueryForZeroAddress();
              return _balances[id][account].numMinted;
          }
          /**
           * @dev Returns how much an address has minted of a certain id
           *
           * Requirements:
           *
           * - `account` cannot be the zero address.
           */
          function totalBurnedByAddress(address account, uint256 id)
              public
              view
              virtual
              returns (uint256)
          {
              if (account == address(0)) revert BalanceQueryForZeroAddress();
              return _balances[id][account].numBurned;
          }
          /**
           * @dev Returns how many tokens are still available to mint
           *
           * Requirements:
           *
           * - `tokenId` must already exist.
           */
          function remainingSupply(uint256 tokenId)
              public
              view
              virtual
              returns (uint256)
          {
              if (!exists(tokenId)) revert NonExistentToken();
              return _remainingSupply(tokenId);
          }
          /**
           * @dev Returns how many tokens are still available to mint
           */
          function _remainingSupply(uint256 tokenId)
              internal
              view
              returns (uint256)
          {
              return
                  _tokenData[tokenId].tokenMintLimit - _tokenData[tokenId].numMinted;
          }
          /**
           * @dev See {IERC1155-balanceOfBatch}.
           *
           * Requirements:
           *
           * - `accounts` and `ids` must have the same length.
           */
          function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
              public
              view
              virtual
              override
              returns (uint256[] memory)
          {
              if (accounts.length != ids.length) revert ArrayLengthMismatch();
              uint256[] memory batchBalances = new uint256[](accounts.length);
              for (uint256 i = 0; i < accounts.length; ++i) {
                  batchBalances[i] = balanceOf(accounts[i], ids[i]);
              }
              return batchBalances;
          }
          /**
           * @dev See {IERC1155-setApprovalForAll}.
           */
          function setApprovalForAll(address operator, bool approved)
              public
              virtual
              override
          {
              _setApprovalForAll(_msgSenderERC1155(), operator, approved);
          }
          /**
           * @dev See {IERC1155-isApprovedForAll}.
           */
          function isApprovedForAll(address account, address operator)
              public
              view
              virtual
              override
              returns (bool)
          {
              return _operatorApprovals[account][operator];
          }
          /**
           * @dev Verifies if a certain tokenId can still mint `buyAmount` more tokens of a certain id.
           */
          function _verifyTokenMintLimit(uint256 tokenId, uint256 buyAmount)
              internal
              view
          {
              if (
                  _tokenData[tokenId].numMinted + buyAmount >
                  _tokenData[tokenId].tokenMintLimit
              ) {
                  revert OverTokenLimit();
              }
          }
          /**
           * @dev See {IERC1155-safeTransferFrom}.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 id,
              uint256 amount,
              bytes memory data
          ) public virtual override {
              if (from != _msgSenderERC1155() && !isApprovedForAll(from, _msgSenderERC1155())) {
                  revert NotOwnerOrApproved();
              }
              _safeTransferFrom(from, to, id, amount, data);
          }
          /**
           * @dev See {IERC1155-safeBatchTransferFrom}.
           */
          function safeBatchTransferFrom(
              address from,
              address to,
              uint256[] calldata ids,
              uint256[] calldata amounts,
              bytes memory data
          ) public virtual override {
              if (from != _msgSenderERC1155() && !isApprovedForAll(from, _msgSenderERC1155())) {
                  revert NotOwnerOrApproved();
              }
              _safeBatchTransferFrom(from, to, ids, amounts, data);
          }
          /**
           * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
           *
           * Emits a {TransferSingle} event.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - `from` must have a balance of tokens of type `id` of at least `amount`.
           * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
           * acceptance magic value.
           */
          function _safeTransferFrom(
              address from,
              address to,
              uint256 id,
              uint256 amount,
              bytes memory data
          ) internal virtual {
              if (to == address(0)) revert TransferToZeroAddress();
              address operator = _msgSenderERC1155();
              _beforeTokenTransfer(
                  operator,
                  from,
                  to,
                  _asSingletonArray(id),
                  _asSingletonArray(amount),
                  data
              );
              if (_balances[id][from].balance < amount) {
                  revert InsufficientTokenBalance();
              }
              // to balance can never overflow because there is a cap on minting
              unchecked {
                  _balances[id][from].balance -= uint64(amount);
                  _balances[id][to].balance += uint64(amount);
              }
              emit TransferSingle(operator, from, to, id, amount);
              _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
          }
          /**
           * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
           *
           * Emits a {TransferBatch} event.
           *
           * Requirements:
           *
           * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
           * acceptance magic value.
           */
          function _safeBatchTransferFrom(
              address from,
              address to,
              uint256[] calldata ids,
              uint256[] calldata amounts,
              bytes memory data
          ) internal virtual {
              if (ids.length != amounts.length) revert ArrayLengthMismatch();
              if (to == address(0)) revert TransferToZeroAddress();
              address operator = _msgSenderERC1155();
              _beforeTokenTransfer(operator, from, to, ids, amounts, data);
              for (uint256 i = 0; i < ids.length; ) {
                  uint256 id = ids[i];
                  uint256 amount = amounts[i];
                  if (_balances[id][from].balance < amount) {
                      revert InsufficientTokenBalance();
                  }
                  // to balance can never overflow because there is a cap on minting
                  unchecked {
                      _balances[id][from].balance -= uint64(amount);
                      _balances[id][to].balance += uint64(amount);
                      
                      ++i;
                  }
              }
              emit TransferBatch(operator, from, to, ids, amounts);
              _doSafeBatchTransferAcceptanceCheck(
                  operator,
                  from,
                  to,
                  ids,
                  amounts,
                  data
              );
          }
          /**
           * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
           *
           * NOTE: In order to save gas fees when there are many transactions nearing the mint limit of a tokenId,
           * we do NOT call `_verifyTokenMintLimit` and instead leave it to the external method to do this check.
           * This allows the queued transactions that were too late to mint the token to error as cheaply as possible.
           *
           * Emits a {TransferSingle} event.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
           * acceptance magic value.
           */
          function _mint(
              address to,
              uint256 id,
              uint256 amount,
              bytes memory data
          ) internal virtual {
              if (to == address(0)) revert MintToZeroAddress();
              if (!exists(id)) revert NonExistentToken();
              address operator = _msgSenderERC1155();
              _beforeTokenTransfer(
                  operator,
                  address(0),
                  to,
                  _asSingletonArray(id),
                  _asSingletonArray(amount),
                  data
              );
              unchecked {
                  _tokenData[id].numMinted += uint64(amount);
                  _balances[id][to].balance += uint64(amount);
                  _balances[id][to].numMinted += uint64(amount);
              }
              emit TransferSingle(operator, address(0), to, id, amount);
              _doSafeTransferAcceptanceCheck(
                  operator,
                  address(0),
                  to,
                  id,
                  amount,
                  data
              );
          }
          /**
           * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
           *
           * Requirements:
           *
           * - `ids` and `amounts` must have the same length.
           * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
           * acceptance magic value.
           */
          function _mintBatch(
              address to,
              uint256[] calldata ids,
              uint256[] calldata amounts,
              bytes calldata data
          ) internal virtual {
              if (to == address(0)) revert MintToZeroAddress();
              if (ids.length != amounts.length) revert ArrayLengthMismatch();
              address operator = _msgSenderERC1155();
              _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
              for (uint256 i = 0; i < ids.length; ) {
                  _verifyTokenMintLimit(ids[i], amounts[i]);
                  // The token mint limit verification prevents potential overflow/underflow
                  unchecked {
                      _tokenData[ids[i]].numMinted += uint64(amounts[i]);
                      _balances[ids[i]][to].balance += uint64(amounts[i]);
                      _balances[ids[i]][to].numMinted += uint64(amounts[i]);
                      
                      ++i;
                  }
              }
              emit TransferBatch(operator, address(0), to, ids, amounts);
              _doSafeBatchTransferAcceptanceCheck(
                  operator,
                  address(0),
                  to,
                  ids,
                  amounts,
                  data
              );
          }
          /**
           * @dev Allow or stop holders from self-burning tokens of a certain tokenId.
           */
          function _setBurnable(uint256 tokenId, bool burnable) internal {
              _tokenData[tokenId].burnable = burnable;
          }
          /**
           * @dev returns if a tokenId is self-burnable.
           */
          function _isSelfBurnable(uint256 tokenId) internal view returns (bool) {
              return _tokenData[tokenId].burnable;
          }
          /**
           * @dev Destroys `amount` tokens of token type `id` from `from` 
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `from` must have at least `amount` tokens of token type `id`.
           */
          function _burn(
              address from,
              uint256 id,
              uint256 amount
          ) internal virtual {
              if (from == address(0)) revert BurnFromZeroAddress();
              address operator = _msgSenderERC1155();
              _beforeTokenTransfer(
                  operator,
                  from,
                  address(0),
                  _asSingletonArray(id),
                  _asSingletonArray(amount),
                  ""
              );
              uint256 fromBalance = _balances[id][from].balance;
              if (fromBalance < amount) revert InsufficientTokenBalance();
              unchecked {
                  _balances[id][from].numBurned += uint64(amount);
                  _balances[id][from].balance = uint64(fromBalance - amount);
              }
              emit TransferSingle(operator, from, address(0), id, amount);
          }
          /**
           * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
           *
           * Requirements:
           *
           * - `ids` and `amounts` must have the same length.
           */
          function _burnBatch(
              address from,
              uint256[] calldata ids,
              uint256[] calldata amounts
          ) internal virtual {
              if (from == address(0)) revert BurnFromZeroAddress();
              if (ids.length != amounts.length) revert ArrayLengthMismatch();
              address operator = _msgSenderERC1155();
              _beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
              for (uint256 i = 0; i < ids.length; ) {
                  uint256 id = ids[i];
                  uint256 amount = amounts[i];
                  uint256 fromBalance = _balances[id][from].balance;
                  if (fromBalance < amount) revert InsufficientTokenBalance();
                  unchecked {
                      _balances[id][from].numBurned += uint64(amount);
                      _balances[id][from].balance = uint64(fromBalance - amount);
                      ++i;
                  }
              }
              emit TransferBatch(operator, from, address(0), ids, amounts);
          }
          /**
           * @dev Approve `operator` to operate on all of `owner` tokens
           *
           * Emits a {ApprovalForAll} event.
           */
          function _setApprovalForAll(
              address owner,
              address operator,
              bool approved
          ) internal virtual {
              _beforeApproval(operator);
              if (owner == operator) revert ApprovalToCurrentOwner();
              _operatorApprovals[owner][operator] = approved;
              emit ApprovalForAll(owner, operator, approved);
          }
          /**
           * @dev Hook that is called before any approval for a token or wallet
           *      
           * `approvedAddr` - the address a wallet is trying to grant approval to.
           */
          function _beforeApproval(address approvedAddr) internal virtual {}
          
          /**
           * @dev Hook that is called before any token transfer. This includes minting
           * and burning, as well as batched variants.
           *
           * The same hook is called on both single and batched variants. For single
           * transfers, the length of the `id` and `amount` arrays will be 1.
           *
           * Calling conditions (for each `id` and `amount` pair):
           *
           * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
           * of token type `id` will be  transferred to `to`.
           * - When `from` is zero, `amount` tokens of token type `id` will be minted
           * for `to`.
           * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
           * will be burned.
           * - `from` and `to` are never both zero.
           * - `ids` and `amounts` have the same, non-zero length.
           *
           * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
           */
          function _beforeTokenTransfer(
              address operator,
              address from,
              address to,
              uint256[] memory ids,
              uint256[] memory amounts,
              bytes memory data
          ) internal virtual {}
          function _doSafeTransferAcceptanceCheck(
              address operator,
              address from,
              address to,
              uint256 id,
              uint256 amount,
              bytes memory data
          ) private {
              if (to.isContract()) {
                  try
                      IERC1155Receiver(to).onERC1155Received(
                          operator,
                          from,
                          id,
                          amount,
                          data
                      )
                  returns (bytes4 response) {
                      if (response != IERC1155Receiver.onERC1155Received.selector) {
                          revert TransferToNonERC721ReceiverImplementer();
                      }
                  } catch Error(string memory reason) {
                      revert(reason);
                  } catch {
                      revert TransferToNonERC721ReceiverImplementer();
                  }
              }
          }
          function _doSafeBatchTransferAcceptanceCheck(
              address operator,
              address from,
              address to,
              uint256[] calldata ids,
              uint256[] calldata amounts,
              bytes memory data
          ) private {
              if (to.isContract()) {
                  try
                      IERC1155Receiver(to).onERC1155BatchReceived(
                          operator,
                          from,
                          ids,
                          amounts,
                          data
                      )
                  returns (bytes4 response) {
                      if (
                          response != IERC1155Receiver.onERC1155BatchReceived.selector
                      ) {
                          revert TransferToNonERC721ReceiverImplementer();
                      }
                  } catch Error(string memory reason) {
                      revert(reason);
                  } catch {
                      revert TransferToNonERC721ReceiverImplementer();
                  }
              }
          }
          /**
           * @dev helper method to turn a uint256 variable into a 1-length array we can pass into uint256[] variables
           */
          function _asSingletonArray(uint256 element)
              private
              pure
              returns (uint256[] memory)
          {
              uint256[] memory array = new uint256[](1);
              array[0] = element;
              return array;
          }
          /**
           * @dev Returns the message sender (defaults to `msg.sender`).
           *
           * If you are writing GSN compatible contracts, you need to override this function.
           */
          function _msgSenderERC1155() internal view virtual returns (address) {
              return msg.sender;
          }
          error ApprovalToCurrentOwner();
          error ArrayLengthMismatch();
          error BalanceQueryForZeroAddress();
          error BurnFromZeroAddress();
          error InsufficientTokenBalance();
          error InvalidMetadata();
          error InvalidMintLimit();
          error MintToZeroAddress();
          error NonExistentToken();
          error NotOwnerOrApproved();
          error OverTokenLimit();
          error TokenAlreadyExists();
          error TransferToNonERC721ReceiverImplementer();
          error TransferToZeroAddress();
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)
      pragma solidity ^0.8.0;
      import "../../utils/IERC165.sol";
      /**
       * @dev Required interface of an ERC1155 compliant contract, as defined in the
       * https://eips.ethereum.org/EIPS/eip-1155[EIP].
       *
       * _Available since v3.1._
       */
      interface IERC1155 is IERC165 {
          /**
           * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
           */
          event TransferSingle(
              address indexed operator,
              address indexed from,
              address indexed to,
              uint256 id,
              uint256 value
          );
          /**
           * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
           * transfers.
           */
          event TransferBatch(
              address indexed operator,
              address indexed from,
              address indexed to,
              uint256[] ids,
              uint256[] values
          );
          /**
           * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
           * `approved`.
           */
          event ApprovalForAll(
              address indexed account,
              address indexed operator,
              bool approved
          );
          /**
           * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
           *
           * If an {URI} event was emitted for `id`, the standard
           * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
           * returned by {IERC1155MetadataURI-uri}.
           */
          event URI(string value, uint256 indexed id);
          /**
           * @dev Returns the amount of tokens of token type `id` owned by `account`.
           *
           * Requirements:
           *
           * - `account` cannot be the zero address.
           */
          function balanceOf(address account, uint256 id)
              external
              view
              returns (uint256);
          /**
           * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
           *
           * Requirements:
           *
           * - `accounts` and `ids` must have the same length.
           */
          function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
              external
              view
              returns (uint256[] memory);
          /**
           * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
           *
           * Emits an {ApprovalForAll} event.
           *
           * Requirements:
           *
           * - `operator` cannot be the caller.
           */
          function setApprovalForAll(address operator, bool approved) external;
          /**
           * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
           *
           * See {setApprovalForAll}.
           */
          function isApprovedForAll(address account, address operator)
              external
              view
              returns (bool);
          /**
           * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
           *
           * Emits a {TransferSingle} event.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
           * - `from` must have a balance of tokens of type `id` of at least `amount`.
           * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
           * acceptance magic value.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 id,
              uint256 amount,
              bytes calldata data
          ) external;
          /**
           * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
           *
           * Emits a {TransferBatch} event.
           *
           * Requirements:
           *
           * - `ids` and `amounts` must have the same length.
           * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
           * acceptance magic value.
           */
          function safeBatchTransferFrom(
              address from,
              address to,
              uint256[] calldata ids,
              uint256[] calldata amounts,
              bytes calldata data
          ) external;
          // =============================================================
          //                        IERC721Metadata
          // =============================================================
          /**
           * @dev Returns the URI for token type `id`.
           *
           * If the `\\{id\\}` substring is present in the URI, it must be replaced by
           * clients with the actual token type ID.
           */
          function uri(uint256 id) external view returns (string memory);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
      pragma solidity ^0.8.0;
      import "./IERC1155.sol";
      /**
       * @dev Interface of the optional ERC1155MetadataExtension interface, as defined
       * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
       *
       * _Available since v3.1._
       */
      interface IERC1155MetadataURI is IERC1155 {
          /**
           * @dev Returns the URI for token type `id`.
           *
           * If the `\\{id\\}` substring is present in the URI, it must be replaced by
           * clients with the actual token type ID.
           */
          function uri(uint256 id) external view returns (string memory);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
      pragma solidity ^0.8.0;
      import "../../utils/IERC165.sol";
      /**
       * @dev _Available since v3.1._
       */
      interface IERC1155Receiver is IERC165 {
          /**
           * @dev Handles the receipt of a single ERC1155 token type. This function is
           * called at the end of a `safeTransferFrom` after the balance has been updated.
           *
           * NOTE: To accept the transfer, this must return
           * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
           * (i.e. 0xf23a6e61, or its own function selector).
           *
           * @param operator The address which initiated the transfer (i.e. msg.sender)
           * @param from The address which previously owned the token
           * @param id The ID of the token being transferred
           * @param value The amount of tokens being transferred
           * @param data Additional data with no specified format
           * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
           */
          function onERC1155Received(
              address operator,
              address from,
              uint256 id,
              uint256 value,
              bytes calldata data
          ) external returns (bytes4);
          /**
           * @dev Handles the receipt of a multiple ERC1155 token types. This function
           * is called at the end of a `safeBatchTransferFrom` after the balances have
           * been updated.
           *
           * NOTE: To accept the transfer(s), this must return
           * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
           * (i.e. 0xbc197c81, or its own function selector).
           *
           * @param operator The address which initiated the batch transfer (i.e. msg.sender)
           * @param from The address which previously owned the token
           * @param ids An array containing ids of each token being transferred (order and length must match values array)
           * @param values An array containing amounts of each token being transferred (order and length must match ids array)
           * @param data Additional data with no specified format
           * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
           */
          function onERC1155BatchReceived(
              address operator,
              address from,
              uint256[] calldata ids,
              uint256[] calldata values,
              bytes calldata data
          ) external returns (bytes4);
      }
      // 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 functionCallWithValue(target, data, 0, "Address: low-level call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
           * `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but also transferring `value` wei to `target`.
           *
           * Requirements:
           *
           * - the calling contract must have an ETH balance of at least `value`.
           * - the called Solidity function must be `payable`.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
          }
          /**
           * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
           * with `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value,
              string memory errorMessage
          ) internal returns (bytes memory) {
              require(address(this).balance >= value, "Address: insufficient balance for call");
              (bool success, bytes memory returndata) = target.call{value: value}(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
              return functionStaticCall(target, data, "Address: low-level static call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              (bool success, bytes memory returndata) = target.staticcall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionDelegateCall(target, data, "Address: low-level delegate call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              (bool success, bytes memory returndata) = target.delegatecall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
           * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
           *
           * _Available since v4.8._
           */
          function verifyCallResultFromTarget(
              address target,
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              if (success) {
                  if (returndata.length == 0) {
                      // only check isContract if the call was successful and the return data is empty
                      // otherwise we already know that it was a contract
                      require(isContract(target), "Address: call to non-contract");
                  }
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          /**
           * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
           * revert reason or using the provided one.
           *
           * _Available since v4.3._
           */
          function verifyCallResult(
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal pure returns (bytes memory) {
              if (success) {
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          function _revert(bytes memory returndata, string memory errorMessage) private pure {
              // Look for revert reason and bubble it up if present
              if (returndata.length > 0) {
                  // The easiest way to bubble the revert reason is using memory via assembly
                  /// @solidity memory-safe-assembly
                  assembly {
                      let returndata_size := mload(returndata)
                      revert(add(32, returndata), returndata_size)
                  }
              } else {
                  revert(errorMessage);
              }
          }
      }
      // 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;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)
      pragma solidity ^0.8.0;
      import "./Strings.sol";
      /**
       * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
       *
       * These functions can be used to verify that a message was signed by the holder
       * of the private keys of a given address.
       */
      library ECDSA {
          enum RecoverError {
              NoError,
              InvalidSignature,
              InvalidSignatureLength,
              InvalidSignatureS,
              InvalidSignatureV // Deprecated in v4.8
          }
          function _throwError(RecoverError error) private pure {
              if (error == RecoverError.NoError) {
                  return; // no error: do nothing
              } else if (error == RecoverError.InvalidSignature) {
                  revert("ECDSA: invalid signature");
              } else if (error == RecoverError.InvalidSignatureLength) {
                  revert("ECDSA: invalid signature length");
              } else if (error == RecoverError.InvalidSignatureS) {
                  revert("ECDSA: invalid signature 's' value");
              }
          }
          /**
           * @dev Returns the address that signed a hashed message (`hash`) with
           * `signature` or error string. This address can then be used for verification purposes.
           *
           * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
           * this function rejects them by requiring the `s` value to be in the lower
           * half order, and the `v` value to be either 27 or 28.
           *
           * IMPORTANT: `hash` _must_ be the result of a hash operation for the
           * verification to be secure: it is possible to craft signatures that
           * recover to arbitrary addresses for non-hashed data. A safe way to ensure
           * this is by receiving a hash of the original message (which may otherwise
           * be too long), and then calling {toEthSignedMessageHash} on it.
           *
           * Documentation for signature generation:
           * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
           * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
           *
           * _Available since v4.3._
           */
          function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
              if (signature.length == 65) {
                  bytes32 r;
                  bytes32 s;
                  uint8 v;
                  // ecrecover takes the signature parameters, and the only way to get them
                  // currently is to use assembly.
                  /// @solidity memory-safe-assembly
                  assembly {
                      r := mload(add(signature, 0x20))
                      s := mload(add(signature, 0x40))
                      v := byte(0, mload(add(signature, 0x60)))
                  }
                  return tryRecover(hash, v, r, s);
              } else {
                  return (address(0), RecoverError.InvalidSignatureLength);
              }
          }
          /**
           * @dev Returns the address that signed a hashed message (`hash`) with
           * `signature`. This address can then be used for verification purposes.
           *
           * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
           * this function rejects them by requiring the `s` value to be in the lower
           * half order, and the `v` value to be either 27 or 28.
           *
           * IMPORTANT: `hash` _must_ be the result of a hash operation for the
           * verification to be secure: it is possible to craft signatures that
           * recover to arbitrary addresses for non-hashed data. A safe way to ensure
           * this is by receiving a hash of the original message (which may otherwise
           * be too long), and then calling {toEthSignedMessageHash} on it.
           */
          function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, signature);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
           *
           * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
           *
           * _Available since v4.3._
           */
          function tryRecover(
              bytes32 hash,
              bytes32 r,
              bytes32 vs
          ) internal pure returns (address, RecoverError) {
              bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
              uint8 v = uint8((uint256(vs) >> 255) + 27);
              return tryRecover(hash, v, r, s);
          }
          /**
           * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
           *
           * _Available since v4.2._
           */
          function recover(
              bytes32 hash,
              bytes32 r,
              bytes32 vs
          ) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, r, vs);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
           * `r` and `s` signature fields separately.
           *
           * _Available since v4.3._
           */
          function tryRecover(
              bytes32 hash,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) internal pure returns (address, RecoverError) {
              // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
              // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
              // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
              // signatures from current libraries generate a unique signature with an s-value in the lower half order.
              //
              // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
              // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
              // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
              // these malleable signatures as well.
              if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                  return (address(0), RecoverError.InvalidSignatureS);
              }
              // If the signature is valid (and not malleable), return the signer address
              address signer = ecrecover(hash, v, r, s);
              if (signer == address(0)) {
                  return (address(0), RecoverError.InvalidSignature);
              }
              return (signer, RecoverError.NoError);
          }
          /**
           * @dev Overload of {ECDSA-recover} that receives the `v`,
           * `r` and `s` signature fields separately.
           */
          function recover(
              bytes32 hash,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Returns an Ethereum Signed Message, created from a `hash`. This
           * produces hash corresponding to the one signed with the
           * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
           * JSON-RPC method as part of EIP-191.
           *
           * See {recover}.
           */
          function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
              // 32 is the length in bytes of hash,
              // enforced by the type signature above
              return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
      32", hash));
          }
          /**
           * @dev Returns an Ethereum Signed Message, created from `s`. This
           * produces hash corresponding to the one signed with the
           * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
           * JSON-RPC method as part of EIP-191.
           *
           * See {recover}.
           */
          function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
              return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
      ", Strings.toString(s.length), s));
          }
          /**
           * @dev Returns an Ethereum Signed Typed Data, created from a
           * `domainSeparator` and a `structHash`. This produces hash corresponding
           * to the one signed with the
           * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
           * JSON-RPC method as part of EIP-712.
           *
           * See {recover}.
           */
          function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
              return keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash));
          }
      }// 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;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)
      pragma solidity ^0.8.0;
      import "./IERC2981.sol";
      import "./ERC165.sol";
      /**
       * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
       *
       * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
       * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
       *
       * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
       * fee is specified in basis points by default.
       *
       * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
       * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
       * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
       *
       * _Available since v4.5._
       */
      abstract contract ERC2981 is IERC2981, ERC165 {
          struct RoyaltyInfo {
              address receiver;
              uint96 royaltyFraction;
          }
          RoyaltyInfo private _defaultRoyaltyInfo;
          mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
              return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
          }
          /**
           * @inheritdoc IERC2981
           */
          function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) {
              RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
              if (royalty.receiver == address(0)) {
                  royalty = _defaultRoyaltyInfo;
              }
              uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
              return (royalty.receiver, royaltyAmount);
          }
          /**
           * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
           * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
           * override.
           */
          function _feeDenominator() internal pure virtual returns (uint96) {
              return 10000;
          }
          /**
           * @dev Sets the royalty information that all ids in this contract will default to.
           *
           * Requirements:
           *
           * - `receiver` cannot be the zero address.
           * - `feeNumerator` cannot be greater than the fee denominator.
           */
          function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
              require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
              require(receiver != address(0), "ERC2981: invalid receiver");
              _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
          }
          /**
           * @dev Removes default royalty information.
           */
          function _deleteDefaultRoyalty() internal virtual {
              delete _defaultRoyaltyInfo;
          }
          /**
           * @dev Sets the royalty information for a specific token id, overriding the global default.
           *
           * Requirements:
           *
           * - `receiver` cannot be the zero address.
           * - `feeNumerator` cannot be greater than the fee denominator.
           */
          function _setTokenRoyalty(
              uint256 tokenId,
              address receiver,
              uint96 feeNumerator
          ) internal virtual {
              require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
              require(receiver != address(0), "ERC2981: Invalid parameters");
              _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
          }
          /**
           * @dev Resets royalty information for the token id back to the global default.
           */
          function _resetTokenRoyalty(uint256 tokenId) internal virtual {
              delete _tokenRoyaltyInfo[tokenId];
          }
      }// 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);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.9;
      import "./IERC165.sol";
      /**
       * @dev Interface for the NFT Royalty Standard
       */
      interface IERC2981 is IERC165 {
          /**
           * ERC165 bytes to add to interface array - set in parent contract
           * implementing this standard
           *
           * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
           * bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
           * _registerInterface(_INTERFACE_ID_ERC2981);
           */
          /**
           * @notice Called with the sale price to determine how much royalty
           *          is owed and to whom.
           * @param _tokenId - the NFT asset queried for royalty information
           * @param _salePrice - the sale price of the NFT asset specified by _tokenId
           * @return receiver - address of who should be sent the royalty payment
           * @return royaltyAmount - the royalty payment amount for _salePrice
           */
          function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
              external
              view
              returns (address receiver, uint256 royaltyAmount);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
      pragma solidity ^0.8.0;
      import "./Context.sol";
      error CallerNotOwner();
      error OwnerNotZero();
      /**
       * @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 internal _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 {
              if (owner() != _msgSender()) revert CallerNotOwner();
          }
          /**
           * @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 {
              if (newOwner == address(0)) revert OwnerNotZero();
              _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);
          }
      }
      // 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 3 of 4: Valhalla
      // SPDX-License-Identifier: MIT
      // ERC721A Contracts v4.2.3
      // Creator: Chiru Labs
      pragma solidity ^0.8.4;
      import './IERC721A.sol';
      /**
       * @dev Interface of ERC721 token receiver.
       */
      interface ERC721A__IERC721Receiver {
          function onERC721Received(
              address operator,
              address from,
              uint256 tokenId,
              bytes calldata data
          ) external returns (bytes4);
      }
      /**
       * @title ERC721V is a slight improvement upon ERC721A for a few select purposes.
       * 
       * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
       * the Metadata extension. It is optimized for lower gas during batch mints through the ERC721A implementation 
       * by Chiru Labs (https://github.com/chiru-labs/ERC721A)
       *
       * ERC2309 was removed because it will not be used. 
       * Token burning was also removed, but left the reserved bit there.
       * 
       * Ownership's extraData field was modified to be writable without ownership initialized. This allows for multiple
       * mints with different extraData values. A token's extraData will be used as a transfer lockup period and will
       * therefore NOT need to be persisted during a token transfer.
       * 
       * Both token operator approval methods will call a beforeApproval hook that can be overwritten.
       * 
       * Assumptions:
       *
       * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
       * starting from `_startTokenId()`.
       * 
       * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
       * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
       */
      contract ERC721V is IERC721A {
          // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
          struct TokenApprovalRef {
              address value;
          }
          // =============================================================
          //                           CONSTANTS
          // =============================================================
          // Mask of an entry in packed address data.
          uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
          // The bit position of `numberMinted` in packed address data.
          uint256 private constant _BITPOS_NUMBER_MINTED = 64;
          // The bit position of `numberBurned` in packed address data.
          uint256 private constant _BITPOS_NUMBER_BURNED = 128;
          // The bit position of `aux` in packed address data.
          uint256 private constant _BITPOS_AUX = 192;
          // Mask of all 256 bits in packed address data except the 64 bits for `aux`.
          uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
          // The bit position of `startTimestamp` in packed ownership.
          uint256 private constant _BITPOS_START_TIMESTAMP = 160;
          // The bit mask of the `burned` bit in packed ownership.
          uint256 private constant _BITMASK_BURNED = 1 << 224;
          // The bit position of the `nextInitialized` bit in packed ownership.
          uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;
          // The bit mask of the `nextInitialized` bit in packed ownership.
          uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;
          // The bit position of `extraData` in packed ownership.
          uint256 private constant _BITPOS_EXTRA_DATA = 232;
          // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
          uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
          // The mask of the lower 160 bits for addresses.
          uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;
          // The `Transfer` event signature is given by:
          // `keccak256(bytes("Transfer(address,address,uint256)"))`.
          bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
              0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
          // =============================================================
          //                            STORAGE
          // =============================================================
          // The next token ID to be minted.
          uint256 private _currentIndex;
          // Burning disabled.
          // uint256 private _burnCounter;
          // Token name
          string private _name;
          // Token symbol
          string private _symbol;
          // Mapping from token ID to ownership details
          // An empty struct value does not necessarily mean the token is unowned.
          // See {_packedOwnershipOf} implementation for details.
          //
          // Bits Layout:
          // - [0..159]   `addr`
          // - [160..223] `startTimestamp`
          // - [224]      `burned`
          // - [225]      `nextInitialized`
          // - [232..255] `extraData`
          mapping(uint256 => uint256) private _packedOwnerships;
          // Mapping owner address to address data.
          //
          // Bits Layout:
          // - [0..63]    `balance`
          // - [64..127]  `numberMinted`
          // - [128..191] `numberBurned`
          // - [192..255] `aux`
          mapping(address => uint256) private _packedAddressData;
          // Mapping from token ID to approved address.
          mapping(uint256 => TokenApprovalRef) private _tokenApprovals;
          // Mapping from owner to operator approvals
          mapping(address => mapping(address => bool)) private _operatorApprovals;
          // =============================================================
          //                          CONSTRUCTOR
          // =============================================================
          constructor(string memory name_, string memory symbol_) {
              _name = name_;
              _symbol = symbol_;
              _currentIndex = _startTokenId();
          }
          // =============================================================
          //                   TOKEN COUNTING OPERATIONS
          // =============================================================
          /**
           * @dev Returns the starting token ID.
           * To change the starting token ID, please override this function.
           */
          function _startTokenId() internal view virtual returns (uint256) {
              return 0;
          }
          /**
           * @dev Returns the next token ID to be minted.
           */
          function _nextTokenId() internal view virtual returns (uint256) {
              return _currentIndex;
          }
          /**
           * @dev Returns the total number of tokens in existence.
           * Burned tokens will reduce the count.
           * To get the total number of tokens minted, please see {_totalMinted}.
           */
          function totalSupply() public view virtual override returns (uint256) {
              // Counter underflow is impossible as _burnCounter cannot be incremented
              // more than `_currentIndex - _startTokenId()` times.
              unchecked {
                  return _currentIndex - _startTokenId();
              }
          }
          /**
           * @dev Returns the total amount of tokens minted in the contract.
           */
          function _totalMinted() internal view virtual returns (uint256) {
              // Counter underflow is impossible as `_currentIndex` does not decrement,
              // and it is initialized to `_startTokenId()`.
              unchecked {
                  return _currentIndex - _startTokenId();
              }
          }
          /**
           * Burning disabled.
           * @dev Returns the total number of tokens burned.
           */
          // function _totalBurned() internal view virtual returns (uint256) {
          //     return _burnCounter;
          // }
          // =============================================================
          //                    ADDRESS DATA OPERATIONS
          // =============================================================
          /**
           * @dev Returns the number of tokens in `owner`'s account.
           */
          function balanceOf(address owner) public view virtual override returns (uint256) {
              if (owner == address(0)) revert BalanceQueryForZeroAddress();
              return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
          }
          /**
           * Returns the number of tokens minted by `owner`.
           */
          function _numberMinted(address owner) internal view returns (uint256) {
              return (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
          }
          /**
           * Returns the number of tokens burned by or on behalf of `owner`.
           */
          function _numberBurned(address owner) internal view returns (uint256) {
              return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
          }
          /**
           * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
           */
          function _getAux(address owner) internal view returns (uint64) {
              return uint64(_packedAddressData[owner] >> _BITPOS_AUX);
          }
          /**
           * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
           * If there are multiple variables, please pack them into a uint64.
           */
          function _setAux(address owner, uint64 aux) internal virtual {
              uint256 packed = _packedAddressData[owner];
              uint256 auxCasted;
              // Cast `aux` with assembly to avoid redundant masking.
              assembly {
                  auxCasted := aux
              }
              packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
              _packedAddressData[owner] = packed;
          }
          // =============================================================
          //                            IERC165
          // =============================================================
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30000 gas.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
              // The interface IDs are constants representing the first 4 bytes
              // of the XOR of all function selectors in the interface.
              // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
              // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
              return
                  interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
                  interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
                  interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
          }
          // =============================================================
          //                        IERC721Metadata
          // =============================================================
          /**
           * @dev Returns the token collection name.
           */
          function name() public view virtual override returns (string memory) {
              return _name;
          }
          /**
           * @dev Returns the token collection symbol.
           */
          function symbol() public view virtual override returns (string memory) {
              return _symbol;
          }
          /**
           * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
           */
          function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
              if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
              string memory baseURI = _baseURI();
              return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
          }
          /**
           * @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, it can be overridden in child contracts.
           */
          function _baseURI() internal view virtual returns (string memory) {
              return '';
          }
          // =============================================================
          //                     OWNERSHIPS OPERATIONS
          // =============================================================
          /**
           * @dev Returns the owner of the `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function ownerOf(uint256 tokenId) public view virtual override returns (address) {
              return address(uint160(_packedOwnershipOf(tokenId)));
          }
          /**
           * @dev Gas spent here starts off proportional to the maximum mint batch size.
           * It gradually moves to O(1) as tokens get transferred around over time.
           */
          function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
              return _unpackedOwnership(_packedOwnershipOf(tokenId));
          }
          /**
           * @dev Returns the unpacked `TokenOwnership` struct at `index`.
           */
          function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
              return _unpackedOwnership(_packedOwnerships[index]);
          }
          /**
           * @dev Verifies if the address has been set a given ownership value.
           */
          function _ownershipNotInitialized(uint256 ownership) internal pure returns (bool) {
              return ownership & _BITMASK_EXTRA_DATA_COMPLEMENT == 0;
          }
          /**
           * @dev Initializes the ownership slot minted at `index` for efficiency purposes.
           */
          function _initializeOwnershipAt(uint256 index) internal virtual {
              if (_ownershipNotInitialized(_packedOwnerships[index])) {
                  _packedOwnerships[index] = _packedOwnershipOf(index);
              }
          }
          /**
           * Returns the packed ownership data of `tokenId`.
           */
          function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) {
              uint256 curr = tokenId;
              unchecked {
                  if (_startTokenId() <= curr)
                      if (curr < _currentIndex) {
                          uint256 packed = _packedOwnerships[curr];
                          // Burning disabled so we can remove the burned check.
                          // if (packed & _BITMASK_BURNED == 0) {
                          
                          // Invariant:
                          // There will always be an initialized ownership slot
                          // (i.e. `ownership.addr != address(0))
                          // before an unintialized ownership slot
                          // (i.e. `ownership.addr == address(0))
                          // Hence, `curr` will not underflow.
                          //
                          // We can directly compare the packed value.
                          // If the address is zero, packed will be zero.
                          while (_ownershipNotInitialized(packed)) {
                              packed = _packedOwnerships[--curr];
                          }
                          return packed;
                      }
              }
              revert OwnerQueryForNonexistentToken();
          }
          /**
           * @dev Returns the unpacked `TokenOwnership` struct from `packed`.
           */
          function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
              ownership.addr = address(uint160(packed));
              ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
              // Burning disabled
              // ownership.burned = packed & _BITMASK_BURNED != 0;
              ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
          }
          /**
           * @dev Packs ownership data into a single uint256.
           */
          function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
              assembly {
                  // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                  owner := and(owner, _BITMASK_ADDRESS)
                  // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
                  result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
              }
          }
          /**
           * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
           */
          function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
              // For branchless setting of the `nextInitialized` flag.
              assembly {
                  // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
                  result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
              }
          }
          // =============================================================
          //                      APPROVAL OPERATIONS
          // =============================================================
          /**
           * @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) public payable virtual override {
              _beforeApproval(to);
              address owner = ownerOf(tokenId);
              if (_msgSenderERC721A() != owner)
                  if (!isApprovedForAll(owner, _msgSenderERC721A())) {
                      revert ApprovalCallerNotOwnerNorApproved();
                  }
              _tokenApprovals[tokenId].value = to;
              emit Approval(owner, to, tokenId);
          }
          /**
           * @dev Returns the account approved for `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function getApproved(uint256 tokenId) public view virtual override returns (address) {
              if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
              return _tokenApprovals[tokenId].value;
          }
          /**
           * @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) public virtual override {
              _beforeApproval(operator);
              _operatorApprovals[_msgSenderERC721A()][operator] = approved;
              emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
          }
          /**
           * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
           *
           * See {setApprovalForAll}.
           */
          function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
              return _operatorApprovals[owner][operator];
          }
          /**
           * @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. See {_mint}.
           */
          function _exists(uint256 tokenId) internal view virtual returns (bool) {
              return
                  _startTokenId() <= tokenId &&
                  tokenId < _currentIndex; // If within bounds,
                  // Burning disabled so we can remove the burned check.
                  // _packedOwnerships[tokenId] & _BITMASK_BURNED == 0; 
          }
          /**
           * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
           */
          function _isSenderApprovedOrOwner(
              address approvedAddress,
              address owner,
              address msgSender
          ) private pure returns (bool result) {
              assembly {
                  // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
                  owner := and(owner, _BITMASK_ADDRESS)
                  // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
                  msgSender := and(msgSender, _BITMASK_ADDRESS)
                  // `msgSender == owner || msgSender == approvedAddress`.
                  result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
              }
          }
          /**
           * @dev Returns the storage slot and value for the approved address of `tokenId`.
           */
          function _getApprovedSlotAndAddress(uint256 tokenId)
              private
              view
              returns (uint256 approvedAddressSlot, address approvedAddress)
          {
              TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
              // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
              assembly {
                  approvedAddressSlot := tokenApproval.slot
                  approvedAddress := sload(approvedAddressSlot)
              }
          }
          // =============================================================
          //                      TRANSFER OPERATIONS
          // =============================================================
          /**
           * @dev Transfers `tokenId` from `from` to `to`.
           *
           * 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
          ) public payable virtual override {
              uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
              if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
              (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
              // The nested ifs save around 20+ gas over a compound boolean condition.
              if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
                  if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
              if (to == address(0)) revert TransferToZeroAddress();
              _beforeTokenTransfers(from, to, tokenId, 1);
              // Clear approvals from the previous owner.
              assembly {
                  if approvedAddress {
                      // This is equivalent to `delete _tokenApprovals[tokenId]`.
                      sstore(approvedAddressSlot, 0)
                  }
              }
              // Underflow of the sender's balance is impossible because we check for
              // ownership above and the recipient's balance can't realistically overflow.
              // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
              unchecked {
                  // We can directly increment and decrement the balances.
                  --_packedAddressData[from]; // Updates: `balance -= 1`.
                  ++_packedAddressData[to]; // Updates: `balance += 1`.
                  // Updates:
                  // - `address` to the next owner.
                  // - `startTimestamp` to the timestamp of transfering.
                  // - `burned` to `false`.
                  // - `nextInitialized` to `true`.
                  // - `extraData` to `0` because we use it for token lockup timestamp.
                  _packedOwnerships[tokenId] = _packOwnershipData(
                      to,
                      _BITMASK_NEXT_INITIALIZED
                  );
                  // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
                  if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                      uint256 nextTokenId = tokenId + 1;
                      // If the next slot's address is zero and not burned (i.e. packed value is zero).
                      if (_ownershipNotInitialized(_packedOwnerships[nextTokenId])) {
                          // If the next slot is within bounds.
                          if (nextTokenId != _currentIndex) {
                              // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                              _packedOwnerships[nextTokenId] = 
                                  (prevOwnershipPacked & _BITMASK_EXTRA_DATA_COMPLEMENT) | 
                                  (_packedOwnerships[nextTokenId] & ~_BITMASK_EXTRA_DATA_COMPLEMENT);
                          }
                      }
                  }
              }
              emit Transfer(from, to, tokenId);
              _afterTokenTransfers(from, to, tokenId, 1);
          }
          /**
           * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId
          ) public payable virtual override {
              safeTransferFrom(from, to, tokenId, '');
          }
          /**
           * @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 memory _data
          ) public payable virtual override {
              transferFrom(from, to, tokenId);
              if (to.code.length != 0)
                  if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
                      revert TransferToNonERC721ReceiverImplementer();
                  }
          }
          /**
           * @dev Hook that is called before any approval for a token or wallet
           *      
           * `approvedAddr` - the address a wallet is trying to grant approval to.
           */
          function _beforeApproval(address approvedAddr) internal virtual {}
          /**
           * @dev Hook that is called before a set of serially-ordered token IDs
           * are about to be transferred. This includes minting.
           * And also called before burning one token.
           *
           * `startTokenId` - the first token ID to be transferred.
           * `quantity` - the amount to be transferred.
           *
           * 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, `tokenId` will be burned by `from`.
           * - `from` and `to` are never both zero.
           */
          function _beforeTokenTransfers(
              address from,
              address to,
              uint256 startTokenId,
              uint256 quantity
          ) internal virtual {}
          /**
           * @dev Hook that is called after a set of serially-ordered token IDs
           * have been transferred. This includes minting.
           * And also called after one token has been burned.
           *
           * `startTokenId` - the first token ID to be transferred.
           * `quantity` - the amount to be transferred.
           *
           * Calling conditions:
           *
           * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
           * transferred to `to`.
           * - When `from` is zero, `tokenId` has been minted for `to`.
           * - When `to` is zero, `tokenId` has been burned by `from`.
           * - `from` and `to` are never both zero.
           */
          function _afterTokenTransfers(
              address from,
              address to,
              uint256 startTokenId,
              uint256 quantity
          ) internal virtual {}
          /**
           * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
           *
           * `from` - Previous owner of the given token ID.
           * `to` - Target address that will receive the token.
           * `tokenId` - Token ID to be transferred.
           * `_data` - Optional data to send along with the call.
           *
           * Returns whether the call correctly returned the expected magic value.
           */
          function _checkContractOnERC721Received(
              address from,
              address to,
              uint256 tokenId,
              bytes memory _data
          ) private returns (bool) {
              try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
                  bytes4 retval
              ) {
                  return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
              } catch (bytes memory reason) {
                  if (reason.length == 0) {
                      revert TransferToNonERC721ReceiverImplementer();
                  } else {
                      assembly {
                          revert(add(32, reason), mload(reason))
                      }
                  }
              }
          }
          // =============================================================
          //                        MINT OPERATIONS
          // =============================================================
          /**
           * @dev Mints `quantity` tokens and transfers them to `to`.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - `quantity` must be greater than 0.
           *
           * Emits a {Transfer} event for each mint.
           */
          function _mint(address to, uint256 quantity) internal virtual {
              uint256 startTokenId = _currentIndex;
              if (quantity == 0) revert MintZeroQuantity();
              _beforeTokenTransfers(address(0), to, startTokenId, quantity);
              // Overflows are incredibly unrealistic.
              // `balance` and `numberMinted` have a maximum limit of 2**64.
              // `tokenId` has a maximum limit of 2**256.
              unchecked {
                  // Updates:
                  // - `balance += quantity`.
                  // - `numberMinted += quantity`.
                  //
                  // We can directly add to the `balance` and `numberMinted`.
                  _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
                  // Updates:
                  // - `address` to the owner.
                  // - `startTimestamp` to the timestamp of minting.
                  // - `burned` to `false`.
                  // - `nextInitialized` to `quantity == 1`.
                  _packedOwnerships[startTokenId] = _packOwnershipData(
                      to,
                      _nextInitializedFlag(quantity)
                  );
                  uint256 toMasked;
                  uint256 end = startTokenId + quantity;
                  // Use assembly to loop and emit the `Transfer` event for gas savings.
                  // The duplicated `log4` removes an extra check and reduces stack juggling.
                  // The assembly, together with the surrounding Solidity code, have been
                  // delicately arranged to nudge the compiler into producing optimized opcodes.
                  assembly {
                      // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
                      toMasked := and(to, _BITMASK_ADDRESS)
                      // Emit the `Transfer` event.
                      log4(
                          0, // Start of data (0, since no data).
                          0, // End of data (0, since no data).
                          _TRANSFER_EVENT_SIGNATURE, // Signature.
                          0, // `address(0)`.
                          toMasked, // `to`.
                          startTokenId // `tokenId`.
                      )
                      // The `iszero(eq(,))` check ensures that large values of `quantity`
                      // that overflows uint256 will make the loop run out of gas.
                      // The compiler will optimize the `iszero` away for performance.
                      for {
                          let tokenId := add(startTokenId, 1)
                      } iszero(eq(tokenId, end)) {
                          tokenId := add(tokenId, 1)
                      } {
                          // Emit the `Transfer` event. Similar to above.
                          log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
                      }
                  }
                  if (toMasked == 0) revert MintToZeroAddress();
                  _currentIndex = end;
              }
              _afterTokenTransfers(address(0), to, startTokenId, quantity);
          }
          /**
           * @dev Safely mints `quantity` tokens and transfers them to `to`.
           *
           * Requirements:
           *
           * - If `to` refers to a smart contract, it must implement
           * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
           * - `quantity` must be greater than 0.
           *
           * See {_mint}.
           *
           * Emits a {Transfer} event for each mint.
           */
          function _safeMint(
              address to,
              uint256 quantity,
              bytes memory _data
          ) internal virtual {
              _mint(to, quantity);
              unchecked {
                  if (to.code.length != 0) {
                      uint256 end = _currentIndex;
                      uint256 index = end - quantity;
                      do {
                          if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
                              revert TransferToNonERC721ReceiverImplementer();
                          }
                      } while (index < end);
                      // Reentrancy protection.
                      if (_currentIndex != end) revert();
                  }
              }
          }
          /**
           * @dev Equivalent to `_safeMint(to, quantity, '')`.
           */
          function _safeMint(address to, uint256 quantity) internal virtual {
              _safeMint(to, quantity, '');
          }
          // =============================================================
          //                        BURN OPERATIONS
          // =============================================================
          // /**
          //  * @dev Equivalent to `_burn(tokenId, false)`.
          //  */
          // function _burn(uint256 tokenId) internal virtual {
          //     _burn(tokenId, false);
          // }
          // /**
          //  * @dev Destroys `tokenId`.
          //  * The approval is cleared when the token is burned.
          //  *
          //  * Requirements:
          //  *
          //  * - `tokenId` must exist.
          //  *
          //  * Emits a {Transfer} event.
          //  */
          // function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
          //     uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
          //     address from = address(uint160(prevOwnershipPacked));
          //     (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
          //     if (approvalCheck) {
          //         // The nested ifs save around 20+ gas over a compound boolean condition.
          //         if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
          //             if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
          //     }
          //     _beforeTokenTransfers(from, address(0), tokenId, 1);
          //     // Clear approvals from the previous owner.
          //     assembly {
          //         if approvedAddress {
          //             // This is equivalent to `delete _tokenApprovals[tokenId]`.
          //             sstore(approvedAddressSlot, 0)
          //         }
          //     }
          //     // Underflow of the sender's balance is impossible because we check for
          //     // ownership above and the recipient's balance can't realistically overflow.
          //     // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
          //     unchecked {
          //         // Updates:
          //         // - `balance -= 1`.
          //         // - `numberBurned += 1`.
          //         //
          //         // We can directly decrement the balance, and increment the number burned.
          //         // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
          //         _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
          //         // Updates:
          //         // - `address` to the last owner.
          //         // - `startTimestamp` to the timestamp of burning.
          //         // - `burned` to `true`.
          //         // - `nextInitialized` to `true`.
          //         _packedOwnerships[tokenId] = _packOwnershipData(
          //             from,
          //             (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED)
          //         );
          //         // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
          //         if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
          //             uint256 nextTokenId = tokenId + 1;
          //             // If the next slot's address is zero and not burned (i.e. packed value is zero).
          //             if (_ownershipNotInitialized(_packedOwnerships[nextTokenId])) {
          //                 // If the next slot is within bounds.
          //                 if (nextTokenId != _currentIndex) {
          //                     // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
          //                     _packedOwnerships[nextTokenId] = prevOwnershipPacked;
          //                 }
          //             }
          //         }
          //     }
          //     emit Transfer(from, address(0), tokenId);
          //     _afterTokenTransfers(from, address(0), tokenId, 1);
          //     // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
          //     unchecked {
          //         _burnCounter++;
          //     }
          // }
          // =============================================================
          //                     EXTRA DATA OPERATIONS
          // =============================================================
          /**
           * @dev Directly sets the extra data for the ownership data `index`.
           */
          function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
              uint256 packed = _packedOwnerships[index];
              uint256 extraDataCasted;
              // Cast `extraData` with assembly to avoid redundant masking.
              assembly {
                  extraDataCasted := extraData
              }
              packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
              _packedOwnerships[index] = packed;
          }
          /**
           * @dev gets the extra data for the ownership data `index`. This can differ from the
           * _packedOwnershipOf(index).extraData because if the address is not initialized it will return
           * the extraData of a different index.
           */
          function _getExtraDataAt(uint256 index) internal virtual returns (uint256) {
            return _packedOwnerships[index] >> _BITPOS_EXTRA_DATA;
          }
          // =============================================================
          //                       OTHER OPERATIONS
          // =============================================================
          /**
           * @dev Returns the message sender (defaults to `msg.sender`).
           *
           * If you are writing GSN compatible contracts, you need to override this function.
           */
          function _msgSenderERC721A() internal view virtual returns (address) {
              return msg.sender;
          }
          /**
           * @dev Converts a uint256 to its ASCII string decimal representation.
           */
          function _toString(uint256 value) internal pure virtual returns (string memory str) {
              assembly {
                  // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
                  // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
                  // We will need 1 word for the trailing zeros padding, 1 word for the length,
                  // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
                  let m := add(mload(0x40), 0xa0)
                  // Update the free memory pointer to allocate.
                  mstore(0x40, m)
                  // Assign the `str` to the end.
                  str := sub(m, 0x20)
                  // Zeroize the slot after the string.
                  mstore(str, 0)
                  // Cache the end of the memory to calculate the length later.
                  let end := str
                  // We write the string from rightmost digit to leftmost digit.
                  // The following is essentially a do-while loop that also handles the zero case.
                  // prettier-ignore
                  for { let temp := value } 1 {} {
                      str := sub(str, 1)
                      // Write the character to the pointer.
                      // The ASCII index of the '0' character is 48.
                      mstore8(str, add(48, mod(temp, 10)))
                      // Keep dividing `temp` until zero.
                      temp := div(temp, 10)
                      // prettier-ignore
                      if iszero(temp) { break }
                  }
                  let length := sub(end, str)
                  // Move the pointer 32 bytes leftwards to make room for the length.
                  str := sub(str, 0x20)
                  // Store the length.
                  mstore(str, length)
              }
          }
      }// SPDX-License-Identifier: MIT
      // ERC721A Contracts v4.2.3
      // Creator: Chiru Labs
      pragma solidity ^0.8.4;
      /**
       * @dev Interface of ERC721A.
       */
      interface IERC721A {
          /**
           * The caller must own the token or be an approved operator.
           */
          error ApprovalCallerNotOwnerNorApproved();
          /**
           * The token does not exist.
           */
          error ApprovalQueryForNonexistentToken();
          /**
           * Cannot query the balance for the zero address.
           */
          error BalanceQueryForZeroAddress();
          /**
           * Cannot mint to the zero address.
           */
          error MintToZeroAddress();
          /**
           * The quantity of tokens minted must be more than zero.
           */
          error MintZeroQuantity();
          /**
           * The token does not exist.
           */
          error OwnerQueryForNonexistentToken();
          /**
           * The caller must own the token or be an approved operator.
           */
          error TransferCallerNotOwnerNorApproved();
          /**
           * The token must be owned by `from`.
           */
          error TransferFromIncorrectOwner();
          /**
           * Cannot safely transfer to a contract that does not implement the
           * ERC721Receiver interface.
           */
          error TransferToNonERC721ReceiverImplementer();
          /**
           * Cannot transfer to the zero address.
           */
          error TransferToZeroAddress();
          /**
           * The token does not exist.
           */
          error URIQueryForNonexistentToken();
          /**
           * The `quantity` minted with ERC2309 exceeds the safety limit.
           */
          error MintERC2309QuantityExceedsLimit();
          /**
           * The `extraData` cannot be set on an unintialized ownership slot.
           */
          error OwnershipNotInitializedForExtraData();
          // =============================================================
          //                            STRUCTS
          // =============================================================
          struct TokenOwnership {
              // The address of the owner.
              address addr;
              // Stores the start time of ownership with minimal overhead for tokenomics.
              uint64 startTimestamp;
              // Whether the token has been burned.
              bool burned;
              // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
              uint24 extraData;
          }
          // =============================================================
          //                         TOKEN COUNTERS
          // =============================================================
          /**
           * @dev Returns the total number of tokens in existence.
           * Burned tokens will reduce the count.
           * To get the total number of tokens minted, please see {_totalMinted}.
           */
          function totalSupply() external view returns (uint256);
          // =============================================================
          //                            IERC165
          // =============================================================
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30000 gas.
           */
          function supportsInterface(bytes4 interfaceId) external view returns (bool);
          // =============================================================
          //                            IERC721
          // =============================================================
          /**
           * @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`,
           * 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,
              bytes calldata data
          ) external payable;
          /**
           * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId
          ) external payable;
          /**
           * @dev Transfers `tokenId` 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 payable;
          /**
           * @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 payable;
          /**
           * @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);
          // =============================================================
          //                        IERC721Metadata
          // =============================================================
          /**
           * @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);
      }// 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;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)
      pragma solidity ^0.8.0;
      import "./Strings.sol";
      /**
       * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
       *
       * These functions can be used to verify that a message was signed by the holder
       * of the private keys of a given address.
       */
      library ECDSA {
          enum RecoverError {
              NoError,
              InvalidSignature,
              InvalidSignatureLength,
              InvalidSignatureS,
              InvalidSignatureV // Deprecated in v4.8
          }
          function _throwError(RecoverError error) private pure {
              if (error == RecoverError.NoError) {
                  return; // no error: do nothing
              } else if (error == RecoverError.InvalidSignature) {
                  revert("ECDSA: invalid signature");
              } else if (error == RecoverError.InvalidSignatureLength) {
                  revert("ECDSA: invalid signature length");
              } else if (error == RecoverError.InvalidSignatureS) {
                  revert("ECDSA: invalid signature 's' value");
              }
          }
          /**
           * @dev Returns the address that signed a hashed message (`hash`) with
           * `signature` or error string. This address can then be used for verification purposes.
           *
           * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
           * this function rejects them by requiring the `s` value to be in the lower
           * half order, and the `v` value to be either 27 or 28.
           *
           * IMPORTANT: `hash` _must_ be the result of a hash operation for the
           * verification to be secure: it is possible to craft signatures that
           * recover to arbitrary addresses for non-hashed data. A safe way to ensure
           * this is by receiving a hash of the original message (which may otherwise
           * be too long), and then calling {toEthSignedMessageHash} on it.
           *
           * Documentation for signature generation:
           * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
           * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
           *
           * _Available since v4.3._
           */
          function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
              if (signature.length == 65) {
                  bytes32 r;
                  bytes32 s;
                  uint8 v;
                  // ecrecover takes the signature parameters, and the only way to get them
                  // currently is to use assembly.
                  /// @solidity memory-safe-assembly
                  assembly {
                      r := mload(add(signature, 0x20))
                      s := mload(add(signature, 0x40))
                      v := byte(0, mload(add(signature, 0x60)))
                  }
                  return tryRecover(hash, v, r, s);
              } else {
                  return (address(0), RecoverError.InvalidSignatureLength);
              }
          }
          /**
           * @dev Returns the address that signed a hashed message (`hash`) with
           * `signature`. This address can then be used for verification purposes.
           *
           * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
           * this function rejects them by requiring the `s` value to be in the lower
           * half order, and the `v` value to be either 27 or 28.
           *
           * IMPORTANT: `hash` _must_ be the result of a hash operation for the
           * verification to be secure: it is possible to craft signatures that
           * recover to arbitrary addresses for non-hashed data. A safe way to ensure
           * this is by receiving a hash of the original message (which may otherwise
           * be too long), and then calling {toEthSignedMessageHash} on it.
           */
          function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, signature);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
           *
           * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
           *
           * _Available since v4.3._
           */
          function tryRecover(
              bytes32 hash,
              bytes32 r,
              bytes32 vs
          ) internal pure returns (address, RecoverError) {
              bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
              uint8 v = uint8((uint256(vs) >> 255) + 27);
              return tryRecover(hash, v, r, s);
          }
          /**
           * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
           *
           * _Available since v4.2._
           */
          function recover(
              bytes32 hash,
              bytes32 r,
              bytes32 vs
          ) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, r, vs);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
           * `r` and `s` signature fields separately.
           *
           * _Available since v4.3._
           */
          function tryRecover(
              bytes32 hash,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) internal pure returns (address, RecoverError) {
              // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
              // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
              // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
              // signatures from current libraries generate a unique signature with an s-value in the lower half order.
              //
              // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
              // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
              // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
              // these malleable signatures as well.
              if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                  return (address(0), RecoverError.InvalidSignatureS);
              }
              // If the signature is valid (and not malleable), return the signer address
              address signer = ecrecover(hash, v, r, s);
              if (signer == address(0)) {
                  return (address(0), RecoverError.InvalidSignature);
              }
              return (signer, RecoverError.NoError);
          }
          /**
           * @dev Overload of {ECDSA-recover} that receives the `v`,
           * `r` and `s` signature fields separately.
           */
          function recover(
              bytes32 hash,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) internal pure returns (address) {
              (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
              _throwError(error);
              return recovered;
          }
          /**
           * @dev Returns an Ethereum Signed Message, created from a `hash`. This
           * produces hash corresponding to the one signed with the
           * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
           * JSON-RPC method as part of EIP-191.
           *
           * See {recover}.
           */
          function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
              // 32 is the length in bytes of hash,
              // enforced by the type signature above
              return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
      32", hash));
          }
          /**
           * @dev Returns an Ethereum Signed Message, created from `s`. This
           * produces hash corresponding to the one signed with the
           * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
           * JSON-RPC method as part of EIP-191.
           *
           * See {recover}.
           */
          function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
              return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
      ", Strings.toString(s.length), s));
          }
          /**
           * @dev Returns an Ethereum Signed Typed Data, created from a
           * `domainSeparator` and a `structHash`. This produces hash corresponding
           * to the one signed with the
           * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
           * JSON-RPC method as part of EIP-712.
           *
           * See {recover}.
           */
          function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
              return keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash));
          }
      }// 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;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)
      pragma solidity ^0.8.0;
      import "./IERC2981.sol";
      import "./ERC165.sol";
      /**
       * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
       *
       * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
       * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
       *
       * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
       * fee is specified in basis points by default.
       *
       * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
       * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
       * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
       *
       * _Available since v4.5._
       */
      abstract contract ERC2981 is IERC2981, ERC165 {
          struct RoyaltyInfo {
              address receiver;
              uint96 royaltyFraction;
          }
          RoyaltyInfo private _defaultRoyaltyInfo;
          mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
              return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
          }
          /**
           * @inheritdoc IERC2981
           */
          function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) {
              RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
              if (royalty.receiver == address(0)) {
                  royalty = _defaultRoyaltyInfo;
              }
              uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
              return (royalty.receiver, royaltyAmount);
          }
          /**
           * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
           * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
           * override.
           */
          function _feeDenominator() internal pure virtual returns (uint96) {
              return 10000;
          }
          /**
           * @dev Sets the royalty information that all ids in this contract will default to.
           *
           * Requirements:
           *
           * - `receiver` cannot be the zero address.
           * - `feeNumerator` cannot be greater than the fee denominator.
           */
          function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
              require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
              require(receiver != address(0), "ERC2981: invalid receiver");
              _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
          }
          /**
           * @dev Removes default royalty information.
           */
          function _deleteDefaultRoyalty() internal virtual {
              delete _defaultRoyaltyInfo;
          }
          /**
           * @dev Sets the royalty information for a specific token id, overriding the global default.
           *
           * Requirements:
           *
           * - `receiver` cannot be the zero address.
           * - `feeNumerator` cannot be greater than the fee denominator.
           */
          function _setTokenRoyalty(
              uint256 tokenId,
              address receiver,
              uint96 feeNumerator
          ) internal virtual {
              require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
              require(receiver != address(0), "ERC2981: Invalid parameters");
              _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
          }
          /**
           * @dev Resets royalty information for the token id back to the global default.
           */
          function _resetTokenRoyalty(uint256 tokenId) internal virtual {
              delete _tokenRoyaltyInfo[tokenId];
          }
      }// 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);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.9;
      import "./IERC165.sol";
      /**
       * @dev Interface for the NFT Royalty Standard
       */
      interface IERC2981 is IERC165 {
          /**
           * ERC165 bytes to add to interface array - set in parent contract
           * implementing this standard
           *
           * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
           * bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
           * _registerInterface(_INTERFACE_ID_ERC2981);
           */
          /**
           * @notice Called with the sale price to determine how much royalty
           *          is owed and to whom.
           * @param _tokenId - the NFT asset queried for royalty information
           * @param _salePrice - the sale price of the NFT asset specified by _tokenId
           * @return receiver - address of who should be sent the royalty payment
           * @return royaltyAmount - the royalty payment amount for _salePrice
           */
          function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
              external
              view
              returns (address receiver, uint256 royaltyAmount);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
      pragma solidity ^0.8.0;
      import "./Context.sol";
      error CallerNotOwner();
      error OwnerNotZero();
      /**
       * @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 internal _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 {
              if (owner() != _msgSender()) revert CallerNotOwner();
          }
          /**
           * @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 {
              if (newOwner == address(0)) revert OwnerNotZero();
              _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);
          }
      }
      // 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);
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.9;
      import "./token/ERC721V.sol";
      import "./utils/ERC2981.sol";
      import "./utils/IERC165.sol";
      import "./utils/Ownable.sol";
      import "./utils/ECDSA.sol";
      /////////////////////////////////////////////////////////////////////////////
      //                                                                         //
      //                                                                         //
      //    ██╗░░░██╗░█████╗░██╗░░░░░██╗░░██╗░█████╗░██╗░░░░░██╗░░░░░░█████╗░    //
      //    ██║░░░██║██╔══██╗██║░░░░░██║░░██║██╔══██╗██║░░░░░██║░░░░░██╔══██╗    //
      //    ╚██╗░██╔╝███████║██║░░░░░███████║███████║██║░░░░░██║░░░░░███████║    //
      //    ░╚████╔╝░██╔══██║██║░░░░░██╔══██║██╔══██║██║░░░░░██║░░░░░██╔══██║    //
      //    ░░╚██╔╝░░██║░░██║███████╗██║░░██║██║░░██║███████╗███████╗██║░░██║    //
      //    ░░░╚═╝░░░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝╚══════╝╚══════╝╚═╝░░╚═╝    //
      //                                                                         //
      //                                                                         //
      /////////////////////////////////////////////////////////////////////////////
      /**
       * Subset of a Presale with only the methods that the main minting contract will call.
       */
      interface Presale {
          function selectedBids(address presaleAddr) external view returns (uint256);
      }
      /**
       * Subset of the IOperatorFilterRegistry with only the methods that the main minting contract will call.
       * The owner of the collection is able to manage the registry subscription on the contract's behalf
       */
      interface IOperatorFilterRegistry {
          function isOperatorAllowed(
              address registrant,
              address operator
          ) external returns (bool);
      }
      contract Valhalla is ERC721V, Ownable, ERC2981 {
          using ECDSA for bytes32;
          // =============================================================
          //                            Structs
          // =============================================================
          // Compiler will pack this into one 256-bit word
          struct AuctionParams {
              // auctionNumber; also tracks which bidIndexes are currently live
              uint16 index;
              // Following 2 values will be multiplied by 1 GWEI or 0.000000001 ETH
              // Bid values with GWEI lower than this denomination do NOT add to a bid.
              uint56 startPrice;
              uint56 minStackedBidIncrement;
              // new bids must beat the lowest bid by this percentage. This is a whole
              // percentage number, a value of 10 means new bids must beat old ones by 10%
              uint8 minBidIncrementPercentage;
              // Optional parameter for if a bid was submitted within seconds of ending,
              // endTimestamp will extend to block.timestamp+timeBuffer if that value is greater.
              uint16 timeBuffer;
              // When the auction can start getting bidded on
              uint48 startTimestamp;
              // When the auction can no longer get bidded on
              uint48 endTimestamp;
              // How many tokens are up for auction. If 0, there is NO auction live.
              uint8 numTokens;
          }
          struct Bid {
              address bidder;
              uint192 amount;
              uint64 bidTime;
          }
          struct BidIndex {
              uint8 index;
              bool isSet;
          }
          // =============================================================
          //                            Constants
          // =============================================================
          // Set on contract initialization
          address public immutable PRESALE_ADDRESS;
          // Proof of hash will be given after reveal.
          string public MINT_PROVENANCE_HASH = "037226b21636376001dbfd22f52d1dd72845efa9613baf51a6a011ac731b2327";
          // Owner will be minting this amount to the treasury which happens before
          // any presale or regular sale. Once totalSupply() is over this amount,
          // no more can get minted by {mintDev}
          uint256 public constant TREASURY_SUPPLY = 300;
          // Maximum tokens that can be minted from {mintTier} and {mintPublic}
          uint256 public constant MINT_CAP = 9000;
          // Public mint is unlikely to be enabled as it will get botted, but if
          // is needed this will make it a tiny bit harder to bot the entire remaining.
          uint256 public constant MAX_PUBLIC_MINT_TXN_SIZE = 5;
          // Proof of hash will be given after all tokens are auctioned.
          string public AUCTION_PROVENANCE_HASH = "eb8c88969a4b776d757de962a194f5b4ffaaadb991ecfbb24d806c7bc6397d30";
          // Multiplier for minBidPrice and minBidIncrement to verify bids are large enough
          // Is used so that we can save storage space and fit the auctionParams into one uint256
          uint256 public constant AUCTION_PRICE_MULTIPLIER = 1 gwei;
          uint256 public constant AUCTION_SUPPLY = 1000;
          // At most 5 tokens can be bid on at once
          uint256 public constant MAX_NUM_BIDS = 5;
          // Cheaper gaswise to set this as 10000 instead of MINT_CAP + AUCTION_SUPPLY
          uint256 public constant TOTAL_SUPPLY = 10000;
          // =============================================================
          //                            STORAGE
          // =============================================================
          // Address that houses the implemention to check if operators are allowed or not
          address public operatorFilterRegistryAddress;
          // Address this contract verifies with the registryAddress for allowed operators.
          address public filterRegistrant;
          // Address that will link to the tokenDNA which the metadata relies on.
          address public dnaContractAddress;
          /**
           * Lockup timestamps are saved in uint24 to fit into the _extraData for the _packedOwnerships
           * mapping of ERC721A tokens. In order to still represent a large range of times, we will
           * be saving the hour the token gets unlocked.
           *
           * In {_beforeTokenTransfers}, _extraData * 3600 will be compared with the current block.timestamp.
           */
          uint24 public firstUnlockTime;
          uint24 public secondUnlockTime;
          uint24 public thirdUnlockTime;
          // Determines whether a presale address has already gotten its presale tokens
          mapping(address => bool) public presaleMinted;
          // If a presale address wants their tokens to land in a different wallet
          mapping(address => address) public presaleDelegation;
          string public tokenUriBase;
          // Address used for {mintTier} which will be a majority of the transactions
          address public signer;
          // Used to quickly invalidate batches of signatures if needed.
          uint256 public signatureVersion;
          // Mapping that shows if a tier is active or not
          mapping(string => bool) public isTierActive;
          mapping(bytes32 => bool) public signatureUsed;
          // Price of a single public mint, {mintPublic} is NOT enabled while this value is 0.
          uint256 public publicMintPrice;
          // Address that is permitted to start and stop auctions
          address public auctioneer;
          // The current highest bids made in the auction
          Bid[MAX_NUM_BIDS] public activeBids;
          // The mapping between an address and its active bid. The isSet flag differentiates the default
          // uint value 0 from an actual 0 value.
          mapping(uint256 => mapping(address => BidIndex)) public bidIndexes;
          // All parameters needed to run an auction
          AuctionParams public auctionParams;
          // ETH reserved due to a live auction, cannot be withdrawn by the owner until the
          // owner calls {endAuction} which also mints out the tokens.
          uint256 public reserveAuctionETH;
          // =============================================================
          //                            Events
          // =============================================================
          event TokenLocked(uint256 indexed tokenId, uint256 unlockTimeHr);
          event TokenUnlocked(uint256 indexed tokenId);
          event AuctionStarted(uint256 indexed index);
          event NewBid(
              uint256 indexed auctionIndex,
              address indexed bidder,
              uint256 value
          );
          event BidIncreased(
              uint256 indexed auctionIndex,
              address indexed bidder,
              uint256 oldValue,
              uint256 increment
          );
          event AuctionExtended(uint256 indexed index);
          // =============================================================
          //                          Constructor
          // =============================================================
          constructor(address initialPresale) ERC721V("Valhalla", "VAL") {
              PRESALE_ADDRESS = initialPresale;
          }
          /**
           * @dev Returns the starting token ID.
           * To change the starting token ID, please override this function.
           */
          function _startTokenId() internal view virtual override returns (uint256) {
              return 1;
          }
          // =============================================================
          //                            IERC165
          // =============================================================
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30000 gas.
           */
          function supportsInterface(
              bytes4 interfaceId
          ) public view virtual override(ERC721V, ERC2981) returns (bool) {
              // The interface IDs are constants representing the first 4 bytes
              // of the XOR of all function selectors in the interface.
              // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
              // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
              return
                  ERC721V.supportsInterface(interfaceId) ||
                  ERC2981.supportsInterface(interfaceId);
          }
          // =============================================================
          //                           IERC2981
          // =============================================================
          /**
           * @notice Allows the owner to set default royalties following EIP-2981 royalty standard.
           */
          function setDefaultRoyalty(
              address receiver,
              uint96 feeNumerator
          ) external onlyOwner {
              _setDefaultRoyalty(receiver, feeNumerator);
          }
          // =============================================================
          //                        Token Metadata
          // =============================================================
          function tokenURI(
              uint256 tokenId
          ) public view override returns (string memory) {
              return string(abi.encodePacked(tokenUriBase, _toString(tokenId)));
          }
          /**
           * @notice Allows the owner to set the base token URI.
           */
          function setTokenURI(string memory newUriBase) external onlyOwner {
              tokenUriBase = newUriBase;
          }
          /**
           * @notice Allows the owner to set the dna contract address.
           */
          function setDnaContract(address dnaAddress) external onlyOwner {
              dnaContractAddress = dnaAddress;
          }
          // =============================================================
          //                 Operator Filter Registry
          // =============================================================
          /**
           * @dev Stops operators from being added as an approved address to transfer.
           * @param operator the address a wallet is trying to grant approval to.
           */
          function _beforeApproval(address operator) internal virtual override {
              if (operatorFilterRegistryAddress.code.length > 0) {
                  if (
                      !IOperatorFilterRegistry(operatorFilterRegistryAddress)
                          .isOperatorAllowed(filterRegistrant, operator)
                  ) {
                      revert OperatorNotAllowed();
                  }
              }
              super._beforeApproval(operator);
          }
          /**
           * @dev Stops operators that are not approved from doing transfers.
           */
          function _beforeTokenTransfers(
              address from,
              address to,
              uint256 tokenId,
              uint256 quantity
          ) internal virtual override {
              if (operatorFilterRegistryAddress.code.length > 0) {
                  if (
                      !IOperatorFilterRegistry(operatorFilterRegistryAddress)
                          .isOperatorAllowed(filterRegistrant, msg.sender)
                  ) {
                      revert OperatorNotAllowed();
                  }
              }
              // expiration time represented in hours. multiply by 60 * 60, or 3600.
              if (_getExtraDataAt(tokenId) * 3600 > block.timestamp)
                  revert TokenTransferLocked();
              super._beforeTokenTransfers(from, to, tokenId, quantity);
          }
          /**
           * @notice Allows the owner to set a new registrant contract.
           */
          function setOperatorFilterRegistryAddress(
              address registryAddress
          ) external onlyOwner {
              operatorFilterRegistryAddress = registryAddress;
          }
          /**
           * @notice Allows the owner to set a new registrant address.
           */
          function setFilterRegistrant(address newRegistrant) external onlyOwner {
              filterRegistrant = newRegistrant;
          }
          // =============================================================
          //                          Presale
          // =============================================================
          /**
           * @notice Allows the owner to mint from treasury supply.
           */
          function mintDev(
              address[] memory mintAddresses,
              uint256[] memory mintQuantities
          ) external onlyOwner {
              for (uint256 i = 0; i < mintAddresses.length; ++i) {
                  _mint(mintAddresses[i], mintQuantities[i]);
                  if (totalSupply() > TREASURY_SUPPLY) revert OverDevSupplyLimit();
              }
          }
          /**
           * @notice Allows the owner to set the presale unlock times.
           */
          function setUnlockTimes(
              uint24 first,
              uint24 second,
              uint24 third
          ) external onlyOwner {
              firstUnlockTime = first;
              secondUnlockTime = second;
              thirdUnlockTime = third;
          }
          /**
           * @notice Allows selected presale addresses to assign wallet address to receive presale mints.
           * @dev This does not do anything for addresses that were not selected on the presale contract.
           */
          function setPresaleMintAddress(address addr) external {
              presaleDelegation[msg.sender] = addr;
          }
          /**
           * @notice Allows owner to mint presale tokens. The ordering is randomzied on-chain so
           * that the owner does not have control over which users get which tokens when uploading
           * an array of presaleUsers
           * @dev Presale contract already guarantees a cap on the # of presale tokens, so
           * we will not check supply against the MINT_CAP in order to save gas.
           */
          function mintPresale(address[] memory presaleUsers) external onlyOwner {
              uint256 nextId = _nextTokenId();
              uint256 supplyLeft = presaleUsers.length;
              while (supplyLeft > 0) {
                  // generate a random index less than the supply left
                  uint256 randomIndex = uint256(
                      keccak256(abi.encodePacked(block.timestamp, supplyLeft))
                  ) % supplyLeft;
                  address presaleUser = presaleUsers[randomIndex];
                  if (presaleMinted[presaleUser])
                      revert PresaleAddressAlreadyMinted();
                  presaleMinted[presaleUser] = true;
                  uint256 tokensOwed = Presale(PRESALE_ADDRESS).selectedBids(
                      presaleUser
                  );
                  _mintPresaleAddress(presaleUser, nextId, tokensOwed);
                  unchecked {
                      --supplyLeft;
                      // Replace the chosen address with the last address not chosen
                      presaleUsers[randomIndex] = presaleUsers[supplyLeft];
                      nextId += tokensOwed;
                  }
              }
          }
          /**
           * @dev mints a certain amount of tokens to the presale address or its delegation
           * if it has delegated another wallet. These tokens will be locked up and released
           * 1/3rd of the amounts at a time.
           */
          function _mintPresaleAddress(
              address presale,
              uint256 nextId,
              uint256 amount
          ) internal {
              if (presaleDelegation[presale] != address(0)) {
                  _mint(presaleDelegation[presale], amount);
              } else {
                  _mint(presale, amount);
              }
              unchecked {
                  // Cheaper gas wise to do every 3 tokens and deal with the remainder afterwards
                  // than to do if statements within the loop.
                  for (uint256 j = 0; j < amount / 3; ) {
                      uint256 start = nextId + j * 3;
                      _setExtraDataAt(start, thirdUnlockTime);
                      _setExtraDataAt(start + 1, secondUnlockTime);
                      _setExtraDataAt(start + 2, firstUnlockTime);
                      emit TokenLocked(start, thirdUnlockTime);
                      emit TokenLocked(start + 1, secondUnlockTime);
                      emit TokenLocked(start + 2, firstUnlockTime);
                      ++j;
                  }
                  // temporarily adjust nextId to do minimal subtractions
                  // when setting `extraData` field
                  nextId += amount - 1;
                  if (amount % 3 == 2) {
                      _setExtraDataAt(nextId - 1, thirdUnlockTime);
                      emit TokenLocked(nextId - 1, thirdUnlockTime);
                      _setExtraDataAt(nextId, secondUnlockTime);
                      emit TokenLocked(nextId, secondUnlockTime);
                  } else if (amount % 3 == 1) {
                      _setExtraDataAt(nextId, thirdUnlockTime);
                      emit TokenLocked(nextId, thirdUnlockTime);
                  }
              }
          }
          // =============================================================
          //                   External Mint Methods
          // =============================================================
          /**
           * @notice Allows the owner to change the active version of their signatures, this also
           * allows a simple invalidation of all signatures they have created on old versions.
           */
          function setSigner(address signer_) external onlyOwner {
              signer = signer_;
          }
          /**
           * @notice Allows the owner to change the active version of their signatures, this also
           * allows a simple invalidation of all signatures they have created on old versions.
           */
          function setSignatureVersion(uint256 version) external onlyOwner {
              signatureVersion = version;
          }
          /**
           * @notice Allows owner to sets if a certain tier is active or not.
           */
          function setIsTierActive(
              string memory tier,
              bool active
          ) external onlyOwner {
              isTierActive[tier] = active;
          }
          /**
           * @notice Tiered mint for allegiants, immortals, and presale bidders.
           * @dev After a tier is activated by the owner, users with the proper signature for that
           * tier are able to mint based on what the owner has approved for their wallet.
           */
          function mintTier(
              string memory tier,
              uint256 price,
              uint256 version,
              uint256 allowedAmount,
              uint256 buyAmount,
              bytes memory sig
          ) external payable {
              if (totalSupply() + buyAmount > MINT_CAP) revert OverMintLimit();
              if (!isTierActive[tier]) revert TierNotActive();
              if (version != signatureVersion) revert InvalidSignatureVersion();
              if (buyAmount > allowedAmount) revert InvalidSignatureBuyAmount();
              if (msg.value != price * buyAmount) revert IncorrectMsgValue();
              bytes32 hash = ECDSA.toEthSignedMessageHash(
                  keccak256(
                      abi.encode(
                          tier,
                          address(this),
                          price,
                          version,
                          allowedAmount,
                          msg.sender
                      )
                  )
              );
              if (signatureUsed[hash]) revert SignatureAlreadyUsed();
              signatureUsed[hash] = true;
              if (hash.recover(sig) != signer) revert InvalidSignature();
              _mint(msg.sender, buyAmount);
          }
          /**
           * @notice Allows the owner to set the public mint price.
           * @dev If this is 0, it is assumed that the public mint is not active.
           */
          function setPublicMintPrice(uint256 price) external onlyOwner {
              publicMintPrice = price;
          }
          /**
           * @notice Public mint method. Will not work while {publicMintPrice} is 0.
           * Unlikely to be enabled because it can be easily botted.
           */
          function mintPublic(uint256 amount) external payable {
              if (tx.origin != msg.sender) revert NotEOA();
              if (totalSupply() + amount > MINT_CAP) revert OverMintLimit();
              if (publicMintPrice == 0) revert PublicMintNotLive();
              if (amount > MAX_PUBLIC_MINT_TXN_SIZE) revert OverMintLimit();
              if (msg.value != amount * publicMintPrice) revert IncorrectMsgValue();
              _mint(msg.sender, amount);
          }
          // =============================================================
          //                       Auction Methods
          // =============================================================
          /**
           * @notice Allows the owner to set the auction parameters
           */
          function setOverallAuctionParams(
              uint40 startPrice_,
              uint40 minStackedBidIncrement_,
              uint8 minBidIncrementPercentage_,
              uint16 timeBuffer_
          ) external onlyOwner {
              auctionParams.startPrice = startPrice_;
              auctionParams.minStackedBidIncrement = minStackedBidIncrement_;
              auctionParams.minBidIncrementPercentage = minBidIncrementPercentage_;
              auctionParams.timeBuffer = timeBuffer_;
          }
          /**
           * @notice Allows the owner to set the auctioneer address.
           */
          function setAuctioneer(address auctioneer_) external onlyOwner {
              auctioneer = auctioneer_;
          }
          /**
           * @notice Allows the autioneer to start the auction of `numTokens` from `startTime` to `endTime`.
           * @dev Auctions can only start after all minting has terminated. We cannot auction more than
           * MAX_NUM_BIDS at a time. Only one auction can be live at a time.
           */
          function startAuction(
              uint8 numTokens,
              uint48 startTime,
              uint48 endTime
          ) external {
              if (auctioneer != msg.sender) revert CallerNotAuctioneer();
              if (totalSupply() < MINT_CAP) revert MintingNotFinished();
              if (totalSupply() + numTokens > TOTAL_SUPPLY) revert OverTokenLimit();
              if (numTokens > MAX_NUM_BIDS) revert OverMaxBids();
              if (auctionParams.numTokens != 0) revert AuctionStillLive();
              if (auctionParams.startPrice == 0) revert AuctionParamsNotInitialized();
              auctionParams.numTokens = numTokens;
              auctionParams.startTimestamp = startTime;
              auctionParams.endTimestamp = endTime;
              emit AuctionStarted(auctionParams.index);
          }
          /**
           * @notice Allows the auctioneer to end the auction.
           * @dev Auctions can end at any time by the owner's discretion and when it ends all
           * current bids are accepted. The owner is also now able to withdraw the funds
           * that were reserved for the auction, and active bids data id reset.
           */
          function endAuction() external {
              if (auctioneer != msg.sender) revert CallerNotAuctioneer();
              if (auctionParams.numTokens == 0) revert AuctionNotLive();
              uint256 lowestPrice = activeBids[getBidIndexToUpdate()].amount;
              for (uint256 i = 0; i < auctionParams.numTokens; ) {
                  if (activeBids[i].bidder == address(0)) {
                      break;
                  }
                  _mint(activeBids[i].bidder, 1);
                  // getBidIndex to update gaurantees no activeBids[i] is less than lowestPrice.
                  unchecked {
                      _transferETH(
                          activeBids[i].bidder,
                          activeBids[i].amount - lowestPrice
                      );
                      ++i;
                  }
              }
              unchecked {
                  ++auctionParams.index;
              }
              auctionParams.numTokens = 0;
              delete activeBids;
              reserveAuctionETH = 0;
          }
          /**
           * @notice Gets the index of the entry in activeBids to update
           * @dev The index to return will be decided by the following rules:
           * If there are less than auctionTokens bids, the index of the first empty slot is returned.
           * If there are auctionTokens or more bids, the index of the lowest value bid is returned. If
           * there is a tie, the most recent bid with the low amount will be returned. If there is a tie
           * among bidTimes, the highest index is chosen.
           */
          function getBidIndexToUpdate() public view returns (uint8) {
              uint256 minAmount = activeBids[0].amount;
              // If the first value is 0 then we can assume that no bids have been submitted
              if (minAmount == 0) {
                  return 0;
              }
              uint8 minIndex = 0;
              uint64 minBidTime = activeBids[0].bidTime;
              for (uint8 i = 1; i < auctionParams.numTokens; ) {
                  uint256 bidAmount = activeBids[i].amount;
                  uint64 bidTime = activeBids[i].bidTime;
                  // A zero bidAmount means the slot is empty because we enforce non-zero bid amounts
                  if (bidAmount == 0) {
                      return i;
                  } else if (
                      bidAmount < minAmount ||
                      (bidAmount == minAmount && bidTime >= minBidTime)
                  ) {
                      minAmount = bidAmount;
                      minIndex = i;
                      minBidTime = bidTime;
                  }
                  unchecked {
                      ++i;
                  }
              }
              return minIndex;
          }
          /**
           * @notice Handle users' bids
           * @dev Bids must be made while the auction is live. Bids must meet a minimum reserve price.
           *
           * The first {auctionParams.numTokens} bids made will be accepted as valid. Subsequent bids must be a percentage
           * higher than the lowest of the active bids. When a low bid is replaced, the ETH will
           * be refunded back to the original bidder.
           *
           * If a valid bid comes in within the last `timeBuffer` seconds, the auction will be extended
           * for another `timeBuffer` seconds. This will continue until no new active bids come in.
           *
           * If a wallet makes a bid while it still has an active bid, the second bid will
           * stack on top of the first bid. If the second bid doesn't meet the `minStackedBidIncrement`
           * threshold, an error will be thrown. A wallet will only have one active bid at at time.
           */
          function bid() external payable {
              if (msg.sender != tx.origin) revert NotEOA();
              if (auctionParams.numTokens == 0) {
                  revert AuctionNotInitialized();
              }
              if (
                  block.timestamp < auctionParams.startTimestamp ||
                  block.timestamp > auctionParams.endTimestamp
              ) {
                  revert AuctionNotLive();
              }
              BidIndex memory existingIndex = bidIndexes[auctionParams.index][
                  msg.sender
              ];
              if (existingIndex.isSet) {
                  // Case when the user already has an active bid
                  if (
                      msg.value <
                      auctionParams.minStackedBidIncrement * AUCTION_PRICE_MULTIPLIER
                  ) {
                      revert BidIncrementTooLow();
                  }
                  uint192 oldValue = activeBids[existingIndex.index].amount;
                  unchecked {
                      reserveAuctionETH += msg.value;
                      activeBids[existingIndex.index].amount =
                          oldValue +
                          uint192(msg.value);
                  }
                  activeBids[existingIndex.index].bidTime = uint64(block.timestamp);
                  emit BidIncreased(
                      auctionParams.index,
                      msg.sender,
                      oldValue,
                      msg.value
                  );
              } else {
                  if (
                      msg.value < auctionParams.startPrice * AUCTION_PRICE_MULTIPLIER
                  ) {
                      revert ReservePriceNotMet();
                  }
                  uint8 lowestBidIndex = getBidIndexToUpdate();
                  uint256 lowestBidAmount = activeBids[lowestBidIndex].amount;
                  address lowestBidder = activeBids[lowestBidIndex].bidder;
                  unchecked {
                      if (
                          msg.value <
                          lowestBidAmount +
                              (lowestBidAmount *
                                  auctionParams.minBidIncrementPercentage) /
                              100
                      ) {
                          revert IncrementalPriceNotMet();
                      }
                      reserveAuctionETH += msg.value - lowestBidAmount;
                  }
                  // Refund lowest bidder and remove bidIndexes entry
                  if (lowestBidder != address(0)) {
                      delete bidIndexes[auctionParams.index][lowestBidder];
                      _transferETH(lowestBidder, lowestBidAmount);
                  }
                  activeBids[lowestBidIndex] = Bid({
                      bidder: msg.sender,
                      amount: uint192(msg.value),
                      bidTime: uint64(block.timestamp)
                  });
                  bidIndexes[auctionParams.index][msg.sender] = BidIndex({
                      index: lowestBidIndex,
                      isSet: true
                  });
                  emit NewBid(auctionParams.index, msg.sender, msg.value);
              }
              // Extend the auction if the bid was received within `timeBuffer` of the auction end time
              if (
                  auctionParams.endTimestamp - block.timestamp <
                  auctionParams.timeBuffer
              ) {
                  unchecked {
                      auctionParams.endTimestamp = uint48(
                          block.timestamp + auctionParams.timeBuffer
                      );
                  }
                  emit AuctionExtended(auctionParams.index);
              }
          }
          // =============================================================
          //                        Miscellaneous
          // =============================================================
          /**
           * @notice Allows owner to emit TokenUnlocked events
           * @dev This method does NOT need to be called for locked tokens to be unlocked.
           * It is here to emit unlock events for marketplaces to know when tokens are
           * eligible for trade. The burden to call this method on the right tokens at the
           * correct timestamp is on the owner of the contract.
           */
          function emitTokensUnlocked(uint256[] memory tokens) external onlyOwner {
              for (uint256 i = 0; i < tokens.length; ) {
                  emit TokenUnlocked(tokens[i]);
                  unchecked {
                      ++i;
                  }
              }
          }
          /**
           * @notice Allows owner to withdraw a specified amount of ETH to a specified address.
           */
          function withdraw(
              address withdrawAddress,
              uint256 amount
          ) external onlyOwner {
              unchecked {
                  if (amount > address(this).balance - reserveAuctionETH) {
                      amount = address(this).balance - reserveAuctionETH;
                  }
              }
              if (!_transferETH(withdrawAddress, amount)) revert WithdrawFailed();
          }
          /**
           * @notice Internal function to transfer ETH to a specified address.
           */
          function _transferETH(address to, uint256 value) internal returns (bool) {
              (bool success, ) = to.call{ value: value, gas: 30000 }(new bytes(0));
              return success;
          }
          error AuctionNotInitialized();
          error AuctionNotLive();
          error AuctionParamsNotInitialized();
          error AuctionStillLive();
          error BidIncrementTooLow();
          error CallerNotAuctioneer();
          error IncorrectMsgValue();
          error IncrementalPriceNotMet();
          error InvalidSignatureBuyAmount();
          error InvalidSignature();
          error InvalidSignatureVersion();
          error MintingNotFinished();
          error NotEOA();
          error OverDevSupplyLimit();
          error OverMintLimit();
          error OverTokenLimit();
          error OverMaxBids();
          error OperatorNotAllowed();
          error PublicMintNotLive();
          error PresaleAddressAlreadyMinted();
          error ReservePriceNotMet();
          error SignatureAlreadyUsed();
          error TierNotActive();
          error TokenTransferLocked();
          error WithdrawFailed();
      }
      

      File 4 of 4: OperatorFilterRegistry
      // 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);
          }
      }
      // 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;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)
      // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
      pragma solidity ^0.8.0;
      /**
       * @dev Library for managing
       * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
       * types.
       *
       * Sets have the following properties:
       *
       * - Elements are added, removed, and checked for existence in constant time
       * (O(1)).
       * - Elements are enumerated in O(n). No guarantees are made on the ordering.
       *
       * ```
       * contract Example {
       *     // Add the library methods
       *     using EnumerableSet for EnumerableSet.AddressSet;
       *
       *     // Declare a set state variable
       *     EnumerableSet.AddressSet private mySet;
       * }
       * ```
       *
       * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
       * and `uint256` (`UintSet`) are supported.
       *
       * [WARNING]
       * ====
       * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
       * unusable.
       * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
       *
       * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
       * array of EnumerableSet.
       * ====
       */
      library EnumerableSet {
          // To implement this library for multiple types with as little code
          // repetition as possible, we write it in terms of a generic Set type with
          // bytes32 values.
          // The Set implementation uses private functions, and user-facing
          // implementations (such as AddressSet) are just wrappers around the
          // underlying Set.
          // This means that we can only create new EnumerableSets for types that fit
          // in bytes32.
          struct Set {
              // Storage of set values
              bytes32[] _values;
              // Position of the value in the `values` array, plus 1 because index 0
              // means a value is not in the set.
              mapping(bytes32 => uint256) _indexes;
          }
          /**
           * @dev Add a value to a set. O(1).
           *
           * Returns true if the value was added to the set, that is if it was not
           * already present.
           */
          function _add(Set storage set, bytes32 value) private returns (bool) {
              if (!_contains(set, value)) {
                  set._values.push(value);
                  // The value is stored at length-1, but we add 1 to all indexes
                  // and use 0 as a sentinel value
                  set._indexes[value] = set._values.length;
                  return true;
              } else {
                  return false;
              }
          }
          /**
           * @dev Removes a value from a set. O(1).
           *
           * Returns true if the value was removed from the set, that is if it was
           * present.
           */
          function _remove(Set storage set, bytes32 value) private returns (bool) {
              // We read and store the value's index to prevent multiple reads from the same storage slot
              uint256 valueIndex = set._indexes[value];
              if (valueIndex != 0) {
                  // Equivalent to contains(set, value)
                  // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                  // the array, and then remove the last element (sometimes called as 'swap and pop').
                  // This modifies the order of the array, as noted in {at}.
                  uint256 toDeleteIndex = valueIndex - 1;
                  uint256 lastIndex = set._values.length - 1;
                  if (lastIndex != toDeleteIndex) {
                      bytes32 lastValue = set._values[lastIndex];
                      // Move the last value to the index where the value to delete is
                      set._values[toDeleteIndex] = lastValue;
                      // Update the index for the moved value
                      set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                  }
                  // Delete the slot where the moved value was stored
                  set._values.pop();
                  // Delete the index for the deleted slot
                  delete set._indexes[value];
                  return true;
              } else {
                  return false;
              }
          }
          /**
           * @dev Returns true if the value is in the set. O(1).
           */
          function _contains(Set storage set, bytes32 value) private view returns (bool) {
              return set._indexes[value] != 0;
          }
          /**
           * @dev Returns the number of values on the set. O(1).
           */
          function _length(Set storage set) private view returns (uint256) {
              return set._values.length;
          }
          /**
           * @dev Returns the value stored at position `index` in the set. O(1).
           *
           * Note that there are no guarantees on the ordering of values inside the
           * array, and it may change when more values are added or removed.
           *
           * Requirements:
           *
           * - `index` must be strictly less than {length}.
           */
          function _at(Set storage set, uint256 index) private view returns (bytes32) {
              return set._values[index];
          }
          /**
           * @dev Return the entire set in an array
           *
           * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
           * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
           * this function has an unbounded cost, and using it as part of a state-changing function may render the function
           * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
           */
          function _values(Set storage set) private view returns (bytes32[] memory) {
              return set._values;
          }
          // Bytes32Set
          struct Bytes32Set {
              Set _inner;
          }
          /**
           * @dev Add a value to a set. O(1).
           *
           * Returns true if the value was added to the set, that is if it was not
           * already present.
           */
          function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
              return _add(set._inner, value);
          }
          /**
           * @dev Removes a value from a set. O(1).
           *
           * Returns true if the value was removed from the set, that is if it was
           * present.
           */
          function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
              return _remove(set._inner, value);
          }
          /**
           * @dev Returns true if the value is in the set. O(1).
           */
          function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
              return _contains(set._inner, value);
          }
          /**
           * @dev Returns the number of values in the set. O(1).
           */
          function length(Bytes32Set storage set) internal view returns (uint256) {
              return _length(set._inner);
          }
          /**
           * @dev Returns the value stored at position `index` in the set. O(1).
           *
           * Note that there are no guarantees on the ordering of values inside the
           * array, and it may change when more values are added or removed.
           *
           * Requirements:
           *
           * - `index` must be strictly less than {length}.
           */
          function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
              return _at(set._inner, index);
          }
          /**
           * @dev Return the entire set in an array
           *
           * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
           * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
           * this function has an unbounded cost, and using it as part of a state-changing function may render the function
           * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
           */
          function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
              bytes32[] memory store = _values(set._inner);
              bytes32[] memory result;
              /// @solidity memory-safe-assembly
              assembly {
                  result := store
              }
              return result;
          }
          // AddressSet
          struct AddressSet {
              Set _inner;
          }
          /**
           * @dev Add a value to a set. O(1).
           *
           * Returns true if the value was added to the set, that is if it was not
           * already present.
           */
          function add(AddressSet storage set, address value) internal returns (bool) {
              return _add(set._inner, bytes32(uint256(uint160(value))));
          }
          /**
           * @dev Removes a value from a set. O(1).
           *
           * Returns true if the value was removed from the set, that is if it was
           * present.
           */
          function remove(AddressSet storage set, address value) internal returns (bool) {
              return _remove(set._inner, bytes32(uint256(uint160(value))));
          }
          /**
           * @dev Returns true if the value is in the set. O(1).
           */
          function contains(AddressSet storage set, address value) internal view returns (bool) {
              return _contains(set._inner, bytes32(uint256(uint160(value))));
          }
          /**
           * @dev Returns the number of values in the set. O(1).
           */
          function length(AddressSet storage set) internal view returns (uint256) {
              return _length(set._inner);
          }
          /**
           * @dev Returns the value stored at position `index` in the set. O(1).
           *
           * Note that there are no guarantees on the ordering of values inside the
           * array, and it may change when more values are added or removed.
           *
           * Requirements:
           *
           * - `index` must be strictly less than {length}.
           */
          function at(AddressSet storage set, uint256 index) internal view returns (address) {
              return address(uint160(uint256(_at(set._inner, index))));
          }
          /**
           * @dev Return the entire set in an array
           *
           * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
           * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
           * this function has an unbounded cost, and using it as part of a state-changing function may render the function
           * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
           */
          function values(AddressSet storage set) internal view returns (address[] memory) {
              bytes32[] memory store = _values(set._inner);
              address[] memory result;
              /// @solidity memory-safe-assembly
              assembly {
                  result := store
              }
              return result;
          }
          // UintSet
          struct UintSet {
              Set _inner;
          }
          /**
           * @dev Add a value to a set. O(1).
           *
           * Returns true if the value was added to the set, that is if it was not
           * already present.
           */
          function add(UintSet storage set, uint256 value) internal returns (bool) {
              return _add(set._inner, bytes32(value));
          }
          /**
           * @dev Removes a value from a set. O(1).
           *
           * Returns true if the value was removed from the set, that is if it was
           * present.
           */
          function remove(UintSet storage set, uint256 value) internal returns (bool) {
              return _remove(set._inner, bytes32(value));
          }
          /**
           * @dev Returns true if the value is in the set. O(1).
           */
          function contains(UintSet storage set, uint256 value) internal view returns (bool) {
              return _contains(set._inner, bytes32(value));
          }
          /**
           * @dev Returns the number of values in the set. O(1).
           */
          function length(UintSet storage set) internal view returns (uint256) {
              return _length(set._inner);
          }
          /**
           * @dev Returns the value stored at position `index` in the set. O(1).
           *
           * Note that there are no guarantees on the ordering of values inside the
           * array, and it may change when more values are added or removed.
           *
           * Requirements:
           *
           * - `index` must be strictly less than {length}.
           */
          function at(UintSet storage set, uint256 index) internal view returns (uint256) {
              return uint256(_at(set._inner, index));
          }
          /**
           * @dev Return the entire set in an array
           *
           * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
           * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
           * this function has an unbounded cost, and using it as part of a state-changing function may render the function
           * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
           */
          function values(UintSet storage set) internal view returns (uint256[] memory) {
              bytes32[] memory store = _values(set._inner);
              uint256[] memory result;
              /// @solidity memory-safe-assembly
              assembly {
                  result := store
              }
              return result;
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.13;
      import {EnumerableSet} from "openzeppelin-contracts/utils/structs/EnumerableSet.sol";
      interface IOperatorFilterRegistry {
          function isOperatorAllowed(address registrant, address operator) external returns (bool);
          function register(address registrant) external;
          function registerAndSubscribe(address registrant, address subscription) external;
          function registerAndCopyEntries(address registrant, address registrantToCopy) external;
          function updateOperator(address registrant, address operator, bool filtered) external;
          function updateOperators(address registrant, address[] calldata operators, bool filtered) external;
          function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;
          function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;
          function subscribe(address registrant, address registrantToSubscribe) external;
          function unsubscribe(address registrant, bool copyExistingEntries) external;
          function subscriptionOf(address addr) external returns (address registrant);
          function subscribers(address registrant) external returns (address[] memory);
          function subscriberAt(address registrant, uint256 index) external returns (address);
          function copyEntriesOf(address registrant, address registrantToCopy) external;
          function isOperatorFiltered(address registrant, address operator) external returns (bool);
          function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);
          function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);
          function filteredOperators(address addr) external returns (address[] memory);
          function filteredCodeHashes(address addr) external returns (bytes32[] memory);
          function filteredOperatorAt(address registrant, uint256 index) external returns (address);
          function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);
          function isRegistered(address addr) external returns (bool);
          function codeHashOf(address addr) external returns (bytes32);
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.13;
      import {IOperatorFilterRegistry} from "./IOperatorFilterRegistry.sol";
      import {Ownable} from "openzeppelin-contracts/access/Ownable.sol";
      import {EnumerableSet} from "openzeppelin-contracts/utils/structs/EnumerableSet.sol";
      import {OperatorFilterRegistryErrorsAndEvents} from "./OperatorFilterRegistryErrorsAndEvents.sol";
      /**
       * @title  OperatorFilterRegistry
       * @notice Borrows heavily from the QQL BlacklistOperatorFilter contract:
       *         https://github.com/qql-art/contracts/blob/main/contracts/BlacklistOperatorFilter.sol
       * @notice This contracts allows tokens or token owners to register specific addresses or codeHashes that may be
       * *       restricted according to the isOperatorAllowed function.
       */
      contract OperatorFilterRegistry is IOperatorFilterRegistry, OperatorFilterRegistryErrorsAndEvents {
          using EnumerableSet for EnumerableSet.AddressSet;
          using EnumerableSet for EnumerableSet.Bytes32Set;
          /// @dev initialized accounts have a nonzero codehash (see https://eips.ethereum.org/EIPS/eip-1052)
          /// Note that this will also be a smart contract's codehash when making calls from its constructor.
          bytes32 constant EOA_CODEHASH = keccak256("");
          mapping(address => EnumerableSet.AddressSet) private _filteredOperators;
          mapping(address => EnumerableSet.Bytes32Set) private _filteredCodeHashes;
          mapping(address => address) private _registrations;
          mapping(address => EnumerableSet.AddressSet) private _subscribers;
          /**
           * @notice restricts method caller to the address or EIP-173 "owner()"
           */
          modifier onlyAddressOrOwner(address addr) {
              if (msg.sender != addr) {
                  try Ownable(addr).owner() returns (address owner) {
                      if (msg.sender != owner) {
                          revert OnlyAddressOrOwner();
                      }
                  } catch (bytes memory reason) {
                      if (reason.length == 0) {
                          revert NotOwnable();
                      } else {
                          /// @solidity memory-safe-assembly
                          assembly {
                              revert(add(32, reason), mload(reason))
                          }
                      }
                  }
              }
              _;
          }
          /**
           * @notice Returns true if operator is not filtered for a given token, either by address or codeHash. Also returns
           *         true if supplied registrant address is not registered.
           */
          function isOperatorAllowed(address registrant, address operator) external view returns (bool) {
              address registration = _registrations[registrant];
              if (registration != address(0)) {
                  EnumerableSet.AddressSet storage filteredOperatorsRef;
                  EnumerableSet.Bytes32Set storage filteredCodeHashesRef;
                  filteredOperatorsRef = _filteredOperators[registration];
                  filteredCodeHashesRef = _filteredCodeHashes[registration];
                  if (filteredOperatorsRef.contains(operator)) {
                      revert AddressFiltered(operator);
                  }
                  if (operator.code.length > 0) {
                      bytes32 codeHash = operator.codehash;
                      if (filteredCodeHashesRef.contains(codeHash)) {
                          revert CodeHashFiltered(operator, codeHash);
                      }
                  }
              }
              return true;
          }
          //////////////////
          // AUTH METHODS //
          //////////////////
          /**
           * @notice Registers an address with the registry. May be called by address itself or by EIP-173 owner.
           */
          function register(address registrant) external onlyAddressOrOwner(registrant) {
              if (_registrations[registrant] != address(0)) {
                  revert AlreadyRegistered();
              }
              _registrations[registrant] = registrant;
              emit RegistrationUpdated(registrant, true);
          }
          /**
           * @notice Unregisters an address with the registry and removes its subscription. May be called by address itself or by EIP-173 owner.
           *         Note that this does not remove any filtered addresses or codeHashes.
           *         Also note that any subscriptions to this registrant will still be active and follow the existing filtered addresses and codehashes.
           */
          function unregister(address registrant) external onlyAddressOrOwner(registrant) {
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  _subscribers[registration].remove(registrant);
                  emit SubscriptionUpdated(registrant, registration, false);
              }
              _registrations[registrant] = address(0);
              emit RegistrationUpdated(registrant, false);
          }
          /**
           * @notice Registers an address with the registry and "subscribes" to another address's filtered operators and codeHashes.
           */
          function registerAndSubscribe(address registrant, address subscription) external onlyAddressOrOwner(registrant) {
              address registration = _registrations[registrant];
              if (registration != address(0)) {
                  revert AlreadyRegistered();
              }
              if (registrant == subscription) {
                  revert CannotSubscribeToSelf();
              }
              address subscriptionRegistration = _registrations[subscription];
              if (subscriptionRegistration == address(0)) {
                  revert NotRegistered(subscription);
              }
              if (subscriptionRegistration != subscription) {
                  revert CannotSubscribeToRegistrantWithSubscription(subscription);
              }
              _registrations[registrant] = subscription;
              _subscribers[subscription].add(registrant);
              emit RegistrationUpdated(registrant, true);
              emit SubscriptionUpdated(registrant, subscription, true);
          }
          /**
           * @notice Registers an address with the registry and copies the filtered operators and codeHashes from another
           *         address without subscribing.
           */
          function registerAndCopyEntries(address registrant, address registrantToCopy)
              external
              onlyAddressOrOwner(registrant)
          {
              if (registrantToCopy == registrant) {
                  revert CannotCopyFromSelf();
              }
              address registration = _registrations[registrant];
              if (registration != address(0)) {
                  revert AlreadyRegistered();
              }
              address registrantRegistration = _registrations[registrantToCopy];
              if (registrantRegistration == address(0)) {
                  revert NotRegistered(registrantToCopy);
              }
              _registrations[registrant] = registrant;
              emit RegistrationUpdated(registrant, true);
              _copyEntries(registrant, registrantToCopy);
          }
          /**
           * @notice Update an operator address for a registered address - when filtered is true, the operator is filtered.
           */
          function updateOperator(address registrant, address operator, bool filtered)
              external
              onlyAddressOrOwner(registrant)
          {
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  revert CannotUpdateWhileSubscribed(registration);
              }
              EnumerableSet.AddressSet storage filteredOperatorsRef = _filteredOperators[registrant];
              if (!filtered) {
                  bool removed = filteredOperatorsRef.remove(operator);
                  if (!removed) {
                      revert AddressNotFiltered(operator);
                  }
              } else {
                  bool added = filteredOperatorsRef.add(operator);
                  if (!added) {
                      revert AddressAlreadyFiltered(operator);
                  }
              }
              emit OperatorUpdated(registrant, operator, filtered);
          }
          /**
           * @notice Update a codeHash for a registered address - when filtered is true, the codeHash is filtered.
           */
          function updateCodeHash(address registrant, bytes32 codeHash, bool filtered)
              external
              onlyAddressOrOwner(registrant)
          {
              if (codeHash == EOA_CODEHASH) {
                  revert CannotFilterEOAs();
              }
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  revert CannotUpdateWhileSubscribed(registration);
              }
              EnumerableSet.Bytes32Set storage filteredCodeHashesRef = _filteredCodeHashes[registrant];
              if (!filtered) {
                  bool removed = filteredCodeHashesRef.remove(codeHash);
                  if (!removed) {
                      revert CodeHashNotFiltered(codeHash);
                  }
              } else {
                  bool added = filteredCodeHashesRef.add(codeHash);
                  if (!added) {
                      revert CodeHashAlreadyFiltered(codeHash);
                  }
              }
              emit CodeHashUpdated(registrant, codeHash, filtered);
          }
          /**
           * @notice Update multiple operators for a registered address - when filtered is true, the operators will be filtered. Reverts on duplicates.
           */
          function updateOperators(address registrant, address[] calldata operators, bool filtered)
              external
              onlyAddressOrOwner(registrant)
          {
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  revert CannotUpdateWhileSubscribed(registration);
              }
              EnumerableSet.AddressSet storage filteredOperatorsRef = _filteredOperators[registrant];
              uint256 operatorsLength = operators.length;
              unchecked {
                  if (!filtered) {
                      for (uint256 i = 0; i < operatorsLength; ++i) {
                          address operator = operators[i];
                          bool removed = filteredOperatorsRef.remove(operator);
                          if (!removed) {
                              revert AddressNotFiltered(operator);
                          }
                      }
                  } else {
                      for (uint256 i = 0; i < operatorsLength; ++i) {
                          address operator = operators[i];
                          bool added = filteredOperatorsRef.add(operator);
                          if (!added) {
                              revert AddressAlreadyFiltered(operator);
                          }
                      }
                  }
              }
              emit OperatorsUpdated(registrant, operators, filtered);
          }
          /**
           * @notice Update multiple codeHashes for a registered address - when filtered is true, the codeHashes will be filtered. Reverts on duplicates.
           */
          function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered)
              external
              onlyAddressOrOwner(registrant)
          {
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  revert CannotUpdateWhileSubscribed(registration);
              }
              EnumerableSet.Bytes32Set storage filteredCodeHashesRef = _filteredCodeHashes[registrant];
              uint256 codeHashesLength = codeHashes.length;
              unchecked {
                  if (!filtered) {
                      for (uint256 i = 0; i < codeHashesLength; ++i) {
                          bytes32 codeHash = codeHashes[i];
                          bool removed = filteredCodeHashesRef.remove(codeHash);
                          if (!removed) {
                              revert CodeHashNotFiltered(codeHash);
                          }
                      }
                  } else {
                      for (uint256 i = 0; i < codeHashesLength; ++i) {
                          bytes32 codeHash = codeHashes[i];
                          if (codeHash == EOA_CODEHASH) {
                              revert CannotFilterEOAs();
                          }
                          bool added = filteredCodeHashesRef.add(codeHash);
                          if (!added) {
                              revert CodeHashAlreadyFiltered(codeHash);
                          }
                      }
                  }
              }
              emit CodeHashesUpdated(registrant, codeHashes, filtered);
          }
          /**
           * @notice Subscribe an address to another registrant's filtered operators and codeHashes. Will remove previous
           *         subscription if present.
           *         Note that accounts with subscriptions may go on to subscribe to other accounts - in this case,
           *         subscriptions will not be forwarded. Instead the former subscription's existing entries will still be
           *         used.
           */
          function subscribe(address registrant, address newSubscription) external onlyAddressOrOwner(registrant) {
              if (registrant == newSubscription) {
                  revert CannotSubscribeToSelf();
              }
              if (newSubscription == address(0)) {
                  revert CannotSubscribeToZeroAddress();
              }
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration == newSubscription) {
                  revert AlreadySubscribed(newSubscription);
              }
              address newSubscriptionRegistration = _registrations[newSubscription];
              if (newSubscriptionRegistration == address(0)) {
                  revert NotRegistered(newSubscription);
              }
              if (newSubscriptionRegistration != newSubscription) {
                  revert CannotSubscribeToRegistrantWithSubscription(newSubscription);
              }
              if (registration != registrant) {
                  _subscribers[registration].remove(registrant);
                  emit SubscriptionUpdated(registrant, registration, false);
              }
              _registrations[registrant] = newSubscription;
              _subscribers[newSubscription].add(registrant);
              emit SubscriptionUpdated(registrant, newSubscription, true);
          }
          /**
           * @notice Unsubscribe an address from its current subscribed registrant, and optionally copy its filtered operators and codeHashes.
           */
          function unsubscribe(address registrant, bool copyExistingEntries) external onlyAddressOrOwner(registrant) {
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration == registrant) {
                  revert NotSubscribed();
              }
              _subscribers[registration].remove(registrant);
              _registrations[registrant] = registrant;
              emit SubscriptionUpdated(registrant, registration, false);
              if (copyExistingEntries) {
                  _copyEntries(registrant, registration);
              }
          }
          /**
           * @notice Copy filtered operators and codeHashes from a different registrantToCopy to addr.
           */
          function copyEntriesOf(address registrant, address registrantToCopy) external onlyAddressOrOwner(registrant) {
              if (registrant == registrantToCopy) {
                  revert CannotCopyFromSelf();
              }
              address registration = _registrations[registrant];
              if (registration == address(0)) {
                  revert NotRegistered(registrant);
              }
              if (registration != registrant) {
                  revert CannotUpdateWhileSubscribed(registration);
              }
              address registrantRegistration = _registrations[registrantToCopy];
              if (registrantRegistration == address(0)) {
                  revert NotRegistered(registrantToCopy);
              }
              _copyEntries(registrant, registrantToCopy);
          }
          /// @dev helper to copy entries from registrantToCopy to registrant and emit events
          function _copyEntries(address registrant, address registrantToCopy) private {
              EnumerableSet.AddressSet storage filteredOperatorsRef = _filteredOperators[registrantToCopy];
              EnumerableSet.Bytes32Set storage filteredCodeHashesRef = _filteredCodeHashes[registrantToCopy];
              uint256 filteredOperatorsLength = filteredOperatorsRef.length();
              uint256 filteredCodeHashesLength = filteredCodeHashesRef.length();
              unchecked {
                  for (uint256 i = 0; i < filteredOperatorsLength; ++i) {
                      address operator = filteredOperatorsRef.at(i);
                      bool added = _filteredOperators[registrant].add(operator);
                      if (added) {
                          emit OperatorUpdated(registrant, operator, true);
                      }
                  }
                  for (uint256 i = 0; i < filteredCodeHashesLength; ++i) {
                      bytes32 codehash = filteredCodeHashesRef.at(i);
                      bool added = _filteredCodeHashes[registrant].add(codehash);
                      if (added) {
                          emit CodeHashUpdated(registrant, codehash, true);
                      }
                  }
              }
          }
          //////////////////
          // VIEW METHODS //
          //////////////////
          /**
           * @notice Get the subscription address of a given registrant, if any.
           */
          function subscriptionOf(address registrant) external view returns (address subscription) {
              subscription = _registrations[registrant];
              if (subscription == address(0)) {
                  revert NotRegistered(registrant);
              } else if (subscription == registrant) {
                  subscription = address(0);
              }
          }
          /**
           * @notice Get the set of addresses subscribed to a given registrant.
           *         Note that order is not guaranteed as updates are made.
           */
          function subscribers(address registrant) external view returns (address[] memory) {
              return _subscribers[registrant].values();
          }
          /**
           * @notice Get the subscriber at a given index in the set of addresses subscribed to a given registrant.
           *         Note that order is not guaranteed as updates are made.
           */
          function subscriberAt(address registrant, uint256 index) external view returns (address) {
              return _subscribers[registrant].at(index);
          }
          /**
           * @notice Returns true if operator is filtered by a given address or its subscription.
           */
          function isOperatorFiltered(address registrant, address operator) external view returns (bool) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredOperators[registration].contains(operator);
              }
              return _filteredOperators[registrant].contains(operator);
          }
          /**
           * @notice Returns true if a codeHash is filtered by a given address or its subscription.
           */
          function isCodeHashFiltered(address registrant, bytes32 codeHash) external view returns (bool) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredCodeHashes[registration].contains(codeHash);
              }
              return _filteredCodeHashes[registrant].contains(codeHash);
          }
          /**
           * @notice Returns true if the hash of an address's code is filtered by a given address or its subscription.
           */
          function isCodeHashOfFiltered(address registrant, address operatorWithCode) external view returns (bool) {
              bytes32 codeHash = operatorWithCode.codehash;
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredCodeHashes[registration].contains(codeHash);
              }
              return _filteredCodeHashes[registrant].contains(codeHash);
          }
          /**
           * @notice Returns true if an address has registered
           */
          function isRegistered(address registrant) external view returns (bool) {
              return _registrations[registrant] != address(0);
          }
          /**
           * @notice Returns a list of filtered operators for a given address or its subscription.
           */
          function filteredOperators(address registrant) external view returns (address[] memory) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredOperators[registration].values();
              }
              return _filteredOperators[registrant].values();
          }
          /**
           * @notice Returns the set of filtered codeHashes for a given address or its subscription.
           *         Note that order is not guaranteed as updates are made.
           */
          function filteredCodeHashes(address registrant) external view returns (bytes32[] memory) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredCodeHashes[registration].values();
              }
              return _filteredCodeHashes[registrant].values();
          }
          /**
           * @notice Returns the filtered operator at the given index of the set of filtered operators for a given address or
           *         its subscription.
           *         Note that order is not guaranteed as updates are made.
           */
          function filteredOperatorAt(address registrant, uint256 index) external view returns (address) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredOperators[registration].at(index);
              }
              return _filteredOperators[registrant].at(index);
          }
          /**
           * @notice Returns the filtered codeHash at the given index of the list of filtered codeHashes for a given address or
           *         its subscription.
           *         Note that order is not guaranteed as updates are made.
           */
          function filteredCodeHashAt(address registrant, uint256 index) external view returns (bytes32) {
              address registration = _registrations[registrant];
              if (registration != registrant) {
                  return _filteredCodeHashes[registration].at(index);
              }
              return _filteredCodeHashes[registrant].at(index);
          }
          /// @dev Convenience method to compute the code hash of an arbitrary contract
          function codeHashOf(address a) external view returns (bytes32) {
              return a.codehash;
          }
      }
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.13;
      contract OperatorFilterRegistryErrorsAndEvents {
          error CannotFilterEOAs();
          error AddressAlreadyFiltered(address operator);
          error AddressNotFiltered(address operator);
          error CodeHashAlreadyFiltered(bytes32 codeHash);
          error CodeHashNotFiltered(bytes32 codeHash);
          error OnlyAddressOrOwner();
          error NotRegistered(address registrant);
          error AlreadyRegistered();
          error AlreadySubscribed(address subscription);
          error NotSubscribed();
          error CannotUpdateWhileSubscribed(address subscription);
          error CannotSubscribeToSelf();
          error CannotSubscribeToZeroAddress();
          error NotOwnable();
          error AddressFiltered(address filtered);
          error CodeHashFiltered(address account, bytes32 codeHash);
          error CannotSubscribeToRegistrantWithSubscription(address registrant);
          error CannotCopyFromSelf();
          event RegistrationUpdated(address indexed registrant, bool indexed registered);
          event OperatorUpdated(address indexed registrant, address indexed operator, bool indexed filtered);
          event OperatorsUpdated(address indexed registrant, address[] operators, bool indexed filtered);
          event CodeHashUpdated(address indexed registrant, bytes32 indexed codeHash, bool indexed filtered);
          event CodeHashesUpdated(address indexed registrant, bytes32[] codeHashes, bool indexed filtered);
          event SubscriptionUpdated(address indexed registrant, address indexed subscription, bool indexed subscribed);
      }