ETH Price: $2,265.27 (-6.53%)

Transaction Decoder

Block:
20079852 at Jun-13-2024 02:14:23 AM +UTC
Transaction Fee:
0.00117132484995134 ETH $2.65
Gas Used:
68,180 Gas / 17.179889263 Gwei

Emitted Events:

277 Sale.Credit( destination=[Sender] 0xb43d184ec7d4d2acb4ebc8db53f4031bca9319a4, amount=340007 )

Account State Difference:

  Address   Before After State Difference Code
0x0ac850A3...8e680E7B3 1,607.683685300132635236 Eth1,607.683685300132635237 Eth0.000000000000000001
(beaverbuild)
22.037463081536404693 Eth22.037531261536404693 Eth0.00006818
0xb43D184E...bcA9319A4
1.564652706940075799 Eth
Nonce: 1038
1.563481382090124458 Eth
Nonce: 1039
0.001171324849951341

Execution Trace

ETH 1.25 Sale.buyPleb( _amount=340007, _destination=0xb43D184Ec7d4D2AcB4eBc8Db53f4031bcA9319A4 )
  • BoredApeYachtClub.balanceOf( owner=0xb43D184Ec7d4D2AcB4eBc8Db53f4031bcA9319A4 ) => ( 0 )
  • MutantApeYachtClub.balanceOf( owner=0xb43D184Ec7d4D2AcB4eBc8Db53f4031bcA9319A4 ) => ( 0 )
  • ETH 1.249999999999999999 0xb43d184ec7d4d2acb4ebc8db53f4031bca9319a4.CALL( )
    buyPleb[Sale (ln:384)]
    File 1 of 3: Sale
    // SPDX-License-Identifier: LicenseRef-VPL WITH AGPL-3.0-only
    pragma solidity ^0.8.25;
    import {
      Ownable
    } from "solady/auth/Ownable.sol";
    import {
      MerkleProofLib
    } from "solady/utils/MerkleProofLib.sol";
    import {
      SafeTransferLib
    } from "solady/utils/SafeTransferLib.sol";
    import {
      ReentrancyGuard
    } from "soledge/utils/ReentrancyGuard.sol";
    /**
      This is the interface for determining particular ERC-721 or ERC-20 ownership.
    */
    interface IBalanceOf {
      /**
        Retrieve the balance that a particular `_owner` has of this token.
        @param _owner The owner to query the balance for.
        @return _ The token balance of `_owner`.
      */
      function balanceOf (
        address _owner
      ) external view returns (uint256);
    }
    /**
      @custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVM MEVM
      @title A contract to sell the future Remilia ERC-20 token.
      @author Tim Clancy <tim-clancy.eth>
      @custom:terry "God is just. Work is rewarded with blessing if not money. Luck
        is the most important thing, but really it's God."
      A contract to sell the future Remilia ERC-20 token.
      No seed raise, no investors,
      no burdens, no promises,
      just conviction.
      I love you.
      @custom:date May 22nd, 2024.
    */
    contract Sale is Ownable, ReentrancyGuard {
      /// An error emitted if the Sale is paused.
      error Paused ();
      /// An error emitted if a caller underpays.
      error InsufficientPayment ();
      /// An error emitted if a caller is not eligible per a snapshot.
      error Ineligible ();
      /// An error emitted if a round has sold out.
      error SoldOut ();
      /// An error emitted if a caller is over their allocation.
      error OverAllocated ();
      /// An error emitted if a caller is over the maximum size per call.
      error OverMax ();
      /// An error emitted if the caller is a loser.
      error Loser ();
      /**
        This struct represents the configuration options for this sale.
        @param owner The address of the initial contract owner.
        @param steps The number of discrete steps to apply for holder sales.
        @param maxSpend The maximum spend in Ether able to be purchased in one call.
        @param anyFill Total slots available to purchase in the any round of the
          community sale.
        @param miladyFill Total slots available to purchase in the Milady round of
          the community sale.
        @param remilioFill Total slots available to purchase in the Remilio round of
          the community sale.
        @param plebPremium The premium paid by plebs, in basis points.
        @param loserPremium The premium paid by losers, in basis points.
        @param basePrice The base price of the public round, in nanoether.
        @param endPrice The end price of the public round, in nanoether.
        @param available The total amount of `token` intended to be sold, 1e18.
        @param milady The address of the Milady NFT.
        @param communityPrice The nanoether price per token of the community round.
        @param remilio The address of the Remilio NFT.
        @param communityAllo The amount of `token` sold in each community slot.
        @param anyRoot The hash tree root of the any community snapshot.
        @param miladyRoot The hash tree root of the Milady community snapshot.
        @param remilioRoot The hash tree root of the Remilio community snapshot.
        @param losers An array of token collection addresses whose holders are
          losers.
      */
      struct Configuration {
        address owner;
        uint8 steps;
        uint8 maxSpend;
        uint16 anyFill;
        uint16 miladyFill;
        uint16 remilioFill;
        uint16 plebPremium;
        uint16 loserPremium;
        uint32 basePrice;
        uint32 endPrice;
        uint32 available;
        address milady;
        uint32 communityPrice;
        address remilio;
        uint96 communityAllo;
        bytes32 anyRoot;
        bytes32 miladyRoot;
        bytes32 remilioRoot;
        address[] losers;
      }
      /// The configuration of this sale.
      Configuration public config;
      /// Precalculate and cache a community round spend amount.
      uint256 private communitySpend;
      /// Track the total number of future token sold.
      uint256 public totalSold;
      /// Track the receipt balance of each address sold to.
      mapping ( address => uint256 ) public receiptBalance;
      /// A mapping to record community sale fill progress.
      mapping ( bytes32 => uint16 ) public communityFill;
      /// A mapping to record caller participation in the community sales.
      mapping ( address => mapping ( bytes32 => bool ) ) public participation;
      /// Whether or not interacting with the sale is paused.
      bool public paused = true;
      /**
        This struct represents the current prices to be paid by either Remilia
        community members or the general non-holding public for sale participation.
        @param remilia The nanoether price paid by Remilia holders.
        @param pleb The nanoether price paid by the general public.
        @param loser The nanoether premium price paid by losers.
      */
      struct CurrentPrices {
        uint256 remilia;
        uint256 pleb;
        uint256 loser;
      }
      /**
        This event is emitted whenever an address is credited with tokens.
        @param destination The address credited with tokens.
        @param amount The amount of tokens credited.
      */
      event Credit (
        address indexed destination,
        uint256 amount
      );
      /**
        A modifier to revert an operation if the owner has paused.
      */
      modifier notPaused () {
        if (paused) {
          revert Paused();
        }
        _;
      }
      /**
        Construct a new instance of the sale contract.
        @param _config A `Configuration` to prepare this sale.
      */
      constructor (
        Configuration memory _config
      ) {
        _initializeOwner(_config.owner);
        config = _config;
        communitySpend = _config.communityPrice * _config.communityAllo / 1e9;
        communityFill[_config.anyRoot] = _config.anyFill;
        communityFill[_config.miladyRoot] = _config.miladyFill;
        communityFill[_config.remilioRoot] = _config.remilioFill;
      }
      /**
        Return the amount of future tokens credited to an address.
        @param _holder The address to retrieve future token credits for.
        @return _ The amount of future token credited to `_holder`.
      */
      function balanceOf (
        address _holder
      ) external view returns (uint256) {
        return receiptBalance[_holder];
      }
      /**
        Allow the owner to pause or unpause the sale.
        @param _status The pause status to set.
      */
      function setPaused (
        bool _status
      ) external onlyOwner {
        paused = _status;
      }
      /**
        A utility function to help transfer Ether out of this contract.
        @param _to The address to transfer Ether to.
        @param _amount The amount of Ether to transfer.
      */
      function _transferEther (
        address _to,
        uint256 _amount
      ) private {
        bool success = SafeTransferLib.trySafeTransferETH(
          _to,
          _amount,
          SafeTransferLib.GAS_STIPEND_NO_STORAGE_WRITES
        );
        if (!success) {
          SafeTransferLib.forceSafeTransferETH(_to, _amount);
        }
      }
      /**
        This is a private helper function to handle the different possible
        community buy options. It exists to be wrapped in normie-digestible names.
        @param _destination An address to receive the purchased tokens.
        @param _root The hash tree root.
        @param _proof A hash tree proof of snapshot eligibility.
      */
      function _processCommunityBuy (
        address _destination,
        bytes32 _root,
        bytes32[] memory _proof
      ) private {
        // Determine payment required.
        if (communitySpend > msg.value) {
          revert InsufficientPayment();
        }
        // Determine snapshot eligibility.
        if (!MerkleProofLib.verify(
          _proof,
          _root,
          keccak256(abi.encodePacked(msg.sender))
        )) {
          revert Ineligible();
        }
        // Prevent overallocating to a single caller.
        if (participation[msg.sender][_root]) {
          revert OverAllocated();
        }
        // Prevent overselling this round.
        if (
          communityFill[_root] == 0 || 
          totalSold + config.communityAllo > uint256(config.available) * 1e18
        ) {
          revert SoldOut();
        }
        // Update state.
        totalSold += config.communityAllo;
        communityFill[_root] = communityFill[_root] - 1;
        participation[msg.sender][_root] = true;
        // Credit the `_destination` the purchased tokens.
        receiptBalance[_destination] =
          receiptBalance[_destination] + config.communityAllo;
        emit Credit(_destination, config.communityAllo);
        // Prevent infiltration by losers.
        for (uint256 i = 0; i < config.losers.length; i++) {
          if (IBalanceOf(config.losers[i]).balanceOf(msg.sender) > 0) {
            revert Loser();
          }
        }
        // Refund the caller any excess payment.
        if (msg.value > communitySpend) {
          uint256 excess = msg.value - communitySpend;
          _transferEther(msg.sender, excess);
        }
      }
      /**
        The Sale has a special, limited portion set aside at the lowest rate for
        any Remilia holder to purchase based on a snapshot. The quanitity available
        for each wallet to purchase is limited.
        @param _destination An address to receive the purchased tokens.
        @param _proof A hash tree proof of snapshot eligibility.
      */
      function buyCommunityAny (
        address _destination,
        bytes32[] memory _proof
      ) external payable nonReentrant notPaused {
        _processCommunityBuy(
          _destination,
          config.anyRoot,
          _proof
        );
      }
      /**
        The Sale has a special, limited portion set aside at the lowest rate for
        Milady holders to purchase based on a snapshot. The quanitity available
        for each wallet to purchase is limited.
        @param _destination An address to receive the purchased tokens.
        @param _proof A hash tree proof of snapshot eligibility.
      */
      function buyCommunityMilady (
        address _destination,
        bytes32[] memory _proof
      ) external payable nonReentrant notPaused {
        _processCommunityBuy(
          _destination,
          config.miladyRoot,
          _proof
        );
      }
      /**
        The Sale has a special, limited portion set aside at the lowest rate for
        Remilio holders to purchase based on a snapshot. The quanitity available
        for each wallet to purchase is limited.
        @param _destination An address to receive the purchased tokens.
        @param _proof A hash tree proof of snapshot eligibility.
      */
      function buyCommunityRemilio (
        address _destination,
        bytes32[] memory _proof
      ) external payable nonReentrant notPaused {
        _processCommunityBuy(
          _destination,
          config.remilioRoot,
          _proof
        );
      }
      /**
        Returns the current prices of the esteemed Remilia token. The price of the
        token depends on the elapsed progress of the sale.
        @return _ The current prices paid by different classes of buyers, refer to
          the `CurrentPrices` struct.
      */
      function currentPrices () public view returns (CurrentPrices memory) {
        uint256 currentBalance = (uint256(config.available) * 1e18) - totalSold;
        uint256 range = uint256(config.endPrice - config.basePrice) * 1e9;
        uint256 sold = (uint256(config.available) * 1e18) - currentBalance;
        uint256 progress = sold * 1e30 / (uint256(config.available) * 1e18);
        uint256 currentPrice = uint256(config.basePrice) * 1e9 + (range * progress) / 1e30; 
        // Progress is stepwise for holders.
        uint256 stepSize = (uint256(config.available) * 1e18) / config.steps;
        uint256 currentStep = sold / stepSize;
        uint256 stepIncrease = range / config.steps;
        uint256 holderPrice = uint256(config.basePrice) * 1e9 + (currentStep * stepIncrease);
        return CurrentPrices({
          remilia: holderPrice,
          pleb: currentPrice * (100_00 + config.plebPremium) / 100_00,
          loser: currentPrice * (100_00 + config.loserPremium) / 100_00
      });
      }
      /**
        Allow the caller to purchase some of the esteemed Remilia token as an
        esteemed Remilia holder.
        @param _amount The amount of token the caller is trying to buy.
        @param _destination An address to receive the purchased tokens.
        @param _proof A hash tree proof of snapshot eligibility.
      */
      function buyHolder (
        uint256 _amount,
        address _destination,
        bytes32[] memory _proof
      ) external payable nonReentrant notPaused {
        uint256 currentPrice = currentPrices().remilia;
        // Determine payment required.
        uint256 spent = currentPrice * _amount / 1e18;
        uint256 value = msg.value;
        if (spent > value) {
          revert InsufficientPayment();
        }
        // Determine snapshot eligibility.
        if (!MerkleProofLib.verify(
          _proof,
          config.anyRoot,
          keccak256(abi.encodePacked(msg.sender))
        ) && IBalanceOf(config.milady).balanceOf(msg.sender) == 0
          && IBalanceOf(config.remilio).balanceOf(msg.sender) == 0) {
          revert Ineligible();
        }
        // Prevent infiltration by losers.
        for (uint256 i = 0; i < config.losers.length; i++) {
          if (IBalanceOf(config.losers[i]).balanceOf(msg.sender) > 0) {
            revert Loser();
          }
        }
        // Prevent overpurchasing in one call.
        if (value > uint256(config.maxSpend) * 1e18) {
          revert OverMax();
        }
        // Prevent overselling this round.
        if (totalSold + _amount > uint256(config.available) * 1e18) {
          revert SoldOut();
        }
        // Credit the `_destination` the purchased tokens.
        totalSold += _amount;
        receiptBalance[_destination] = receiptBalance[_destination] + _amount;
        emit Credit(_destination, _amount);
        // Refund the caller any excess payment.
        if (value > spent) {
          uint256 excess = value - spent;
          _transferEther(msg.sender, excess);
        }
      }
      /**
        Allow the caller to purchase some of the esteemed Remilia token.
        @param _amount The amount of token the caller is trying to buy.
        @param _destination An address to receive the purchased tokens.
      */
      function buyPleb (
        uint256 _amount,
        address _destination
      ) external payable nonReentrant notPaused {
        uint256 currentPrice = currentPrices().pleb;
        // Determine payment required.
        uint256 spent = currentPrice * _amount / 1e18;
        uint256 value = msg.value;
        if (spent > value) {
          revert InsufficientPayment();
        }
        // Prevent infiltration by losers.
        for (uint256 i = 0; i < config.losers.length; i++) {
          if (IBalanceOf(config.losers[i]).balanceOf(msg.sender) > 0) {
            revert Loser();
          }
        }
        // Prevent overpurchasing in one call.
        if (value > uint256(config.maxSpend) * 1e18) {
          revert OverMax();
        }
        // Prevent overselling this round.
        if (totalSold + _amount > uint256(config.available) * 1e18) {
          revert SoldOut();
        }
        // Credit the `_destination` the purchased tokens.
        totalSold += _amount;
        receiptBalance[_destination] = receiptBalance[_destination] + _amount;
        emit Credit(_destination, _amount);
        // Refund the caller any excess payment.
        if (value > spent) {
          uint256 excess = value - spent;
          _transferEther(msg.sender, excess);
        }
      }
      /**
        Allow the caller to purchase some of the esteemed Remilia token.
        Even if they are a loser.
        @param _amount The amount of token the caller is trying to buy.
        @param _destination An address to receive the purchased tokens.
      */
      function buyLoser (
        uint256 _amount,
        address _destination
      ) external payable nonReentrant notPaused {
        uint256 currentPrice = currentPrices().loser;
        // Determine payment required.
        uint256 spent = currentPrice * _amount / 1e18;
        uint256 value = msg.value;
        if (spent > value) {
          revert InsufficientPayment();
        }
        // Prevent overpurchasing in one call.
        if (value > uint256(config.maxSpend) * 1e18) {
          revert OverMax();
        }
        // Prevent overselling this round.
        if (totalSold + _amount > uint256(config.available) * 1e18) {
          revert SoldOut();
        }
        // Credit the `_destination` the purchased tokens.
        totalSold += _amount;
        receiptBalance[_destination] = receiptBalance[_destination] + _amount;
        emit Credit(_destination, _amount);
        // Refund the caller any excess payment.
        if (value > spent) {
          uint256 excess = value - spent;
          _transferEther(msg.sender, excess);
        }
      }
      /**
        Allow the owner to reconfigure this instance of the sale contract.
        @param _config A `Configuration` to prepare this sale.
      */
      function reconfigure (
        Configuration memory _config
      ) external payable onlyOwner {
        config = _config;
        communitySpend = _config.communityPrice * _config.communityAllo / 1e9;
        communityFill[_config.anyRoot] = _config.anyFill;
        communityFill[_config.miladyRoot] = _config.miladyFill;
        communityFill[_config.remilioRoot] = _config.remilioFill;
      }
      /**
        Allow the owner to transfer Ether out of this contract.
        @param _to The address to transfer Ether to.
        @param _amount The amount of Ether to transfer.
      */
      function transferEther (
        address _to,
        uint256 _amount
      ) external payable onlyOwner {
        _transferEther(_to, _amount);
      }
      /**
        Allow the owner of the Sale to transfer ERC-20 tokens out of this contract.
        This is only needed in case we need to save someone very very stupid.
        @param _token The address of the ERC-20 token to transfer.
        @param _to The address to transfer the ERC-20 `_token` to.
        @param _amount The amount of `_token` to transfer.
      */
      function transferToken (
        address _token,
        address _to,
        uint256 _amount
      ) external payable onlyOwner {
        SafeTransferLib.safeTransfer(_token, _to, _amount);
      }
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.4;
    /// @notice Simple single owner authorization mixin.
    /// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
    ///
    /// @dev Note:
    /// This implementation does NOT auto-initialize the owner to `msg.sender`.
    /// You MUST call the `_initializeOwner` in the constructor / initializer.
    ///
    /// While the ownable portion follows
    /// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
    /// the nomenclature for the 2-step ownership handover may be unique to this codebase.
    abstract contract Ownable {
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                       CUSTOM ERRORS                        */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev The caller is not authorized to call the function.
        error Unauthorized();
        /// @dev The `newOwner` cannot be the zero address.
        error NewOwnerIsZeroAddress();
        /// @dev The `pendingOwner` does not have a valid handover request.
        error NoHandoverRequest();
        /// @dev Cannot double-initialize.
        error AlreadyInitialized();
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                           EVENTS                           */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev The ownership is transferred from `oldOwner` to `newOwner`.
        /// This event is intentionally kept the same as OpenZeppelin's Ownable to be
        /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
        /// despite it not being as lightweight as a single argument event.
        event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
        /// @dev An ownership handover to `pendingOwner` has been requested.
        event OwnershipHandoverRequested(address indexed pendingOwner);
        /// @dev The ownership handover to `pendingOwner` has been canceled.
        event OwnershipHandoverCanceled(address indexed pendingOwner);
        /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
        uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
            0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
        /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
        uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
            0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
        /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
        uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
            0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                          STORAGE                           */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev The owner slot is given by:
        /// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
        /// It is intentionally chosen to be a high value
        /// to avoid collision with lower slots.
        /// The choice of manual storage layout is to enable compatibility
        /// with both regular and upgradeable contracts.
        bytes32 internal constant _OWNER_SLOT =
            0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
        /// The ownership handover slot of `newOwner` is given by:
        /// ```
        ///     mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
        ///     let handoverSlot := keccak256(0x00, 0x20)
        /// ```
        /// It stores the expiry timestamp of the two-step ownership handover.
        uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                     INTERNAL FUNCTIONS                     */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
        function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
        /// @dev Initializes the owner directly without authorization guard.
        /// This function must be called upon initialization,
        /// regardless of whether the contract is upgradeable or not.
        /// This is to enable generalization to both regular and upgradeable contracts,
        /// and to save gas in case the initial owner is not the caller.
        /// For performance reasons, this function will not check if there
        /// is an existing owner.
        function _initializeOwner(address newOwner) internal virtual {
            if (_guardInitializeOwner()) {
                /// @solidity memory-safe-assembly
                assembly {
                    let ownerSlot := _OWNER_SLOT
                    if sload(ownerSlot) {
                        mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
                        revert(0x1c, 0x04)
                    }
                    // Clean the upper 96 bits.
                    newOwner := shr(96, shl(96, newOwner))
                    // Store the new value.
                    sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
                    // Emit the {OwnershipTransferred} event.
                    log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
                }
            } else {
                /// @solidity memory-safe-assembly
                assembly {
                    // Clean the upper 96 bits.
                    newOwner := shr(96, shl(96, newOwner))
                    // Store the new value.
                    sstore(_OWNER_SLOT, newOwner)
                    // Emit the {OwnershipTransferred} event.
                    log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
                }
            }
        }
        /// @dev Sets the owner directly without authorization guard.
        function _setOwner(address newOwner) internal virtual {
            if (_guardInitializeOwner()) {
                /// @solidity memory-safe-assembly
                assembly {
                    let ownerSlot := _OWNER_SLOT
                    // Clean the upper 96 bits.
                    newOwner := shr(96, shl(96, newOwner))
                    // Emit the {OwnershipTransferred} event.
                    log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                    // Store the new value.
                    sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
                }
            } else {
                /// @solidity memory-safe-assembly
                assembly {
                    let ownerSlot := _OWNER_SLOT
                    // Clean the upper 96 bits.
                    newOwner := shr(96, shl(96, newOwner))
                    // Emit the {OwnershipTransferred} event.
                    log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                    // Store the new value.
                    sstore(ownerSlot, newOwner)
                }
            }
        }
        /// @dev Throws if the sender is not the owner.
        function _checkOwner() internal view virtual {
            /// @solidity memory-safe-assembly
            assembly {
                // If the caller is not the stored owner, revert.
                if iszero(eq(caller(), sload(_OWNER_SLOT))) {
                    mstore(0x00, 0x82b42900) // `Unauthorized()`.
                    revert(0x1c, 0x04)
                }
            }
        }
        /// @dev Returns how long a two-step ownership handover is valid for in seconds.
        /// Override to return a different value if needed.
        /// Made internal to conserve bytecode. Wrap it in a public function if needed.
        function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
            return 48 * 3600;
        }
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                  PUBLIC UPDATE FUNCTIONS                   */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev Allows the owner to transfer the ownership to `newOwner`.
        function transferOwnership(address newOwner) public payable virtual onlyOwner {
            /// @solidity memory-safe-assembly
            assembly {
                if iszero(shl(96, newOwner)) {
                    mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
                    revert(0x1c, 0x04)
                }
            }
            _setOwner(newOwner);
        }
        /// @dev Allows the owner to renounce their ownership.
        function renounceOwnership() public payable virtual onlyOwner {
            _setOwner(address(0));
        }
        /// @dev Request a two-step ownership handover to the caller.
        /// The request will automatically expire in 48 hours (172800 seconds) by default.
        function requestOwnershipHandover() public payable virtual {
            unchecked {
                uint256 expires = block.timestamp + _ownershipHandoverValidFor();
                /// @solidity memory-safe-assembly
                assembly {
                    // Compute and set the handover slot to `expires`.
                    mstore(0x0c, _HANDOVER_SLOT_SEED)
                    mstore(0x00, caller())
                    sstore(keccak256(0x0c, 0x20), expires)
                    // Emit the {OwnershipHandoverRequested} event.
                    log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
                }
            }
        }
        /// @dev Cancels the two-step ownership handover to the caller, if any.
        function cancelOwnershipHandover() public payable virtual {
            /// @solidity memory-safe-assembly
            assembly {
                // Compute and set the handover slot to 0.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, caller())
                sstore(keccak256(0x0c, 0x20), 0)
                // Emit the {OwnershipHandoverCanceled} event.
                log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
            }
        }
        /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
        /// Reverts if there is no existing ownership handover requested by `pendingOwner`.
        function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
            /// @solidity memory-safe-assembly
            assembly {
                // Compute and set the handover slot to 0.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, pendingOwner)
                let handoverSlot := keccak256(0x0c, 0x20)
                // If the handover does not exist, or has expired.
                if gt(timestamp(), sload(handoverSlot)) {
                    mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
                    revert(0x1c, 0x04)
                }
                // Set the handover slot to 0.
                sstore(handoverSlot, 0)
            }
            _setOwner(pendingOwner);
        }
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                   PUBLIC READ FUNCTIONS                    */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev Returns the owner of the contract.
        function owner() public view virtual returns (address result) {
            /// @solidity memory-safe-assembly
            assembly {
                result := sload(_OWNER_SLOT)
            }
        }
        /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
        function ownershipHandoverExpiresAt(address pendingOwner)
            public
            view
            virtual
            returns (uint256 result)
        {
            /// @solidity memory-safe-assembly
            assembly {
                // Compute the handover slot.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, pendingOwner)
                // Load the handover slot.
                result := sload(keccak256(0x0c, 0x20))
            }
        }
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                         MODIFIERS                          */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev Marks a function as only callable by the owner.
        modifier onlyOwner() virtual {
            _checkOwner();
            _;
        }
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.4;
    /// @notice Gas optimized verification of proof of inclusion for a leaf in a Merkle tree.
    /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MerkleProofLib.sol)
    /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/MerkleProofLib.sol)
    /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol)
    library MerkleProofLib {
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*            MERKLE PROOF VERIFICATION OPERATIONS            */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev Returns whether `leaf` exists in the Merkle tree with `root`, given `proof`.
        function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf)
            internal
            pure
            returns (bool isValid)
        {
            /// @solidity memory-safe-assembly
            assembly {
                if mload(proof) {
                    // Initialize `offset` to the offset of `proof` elements in memory.
                    let offset := add(proof, 0x20)
                    // Left shift by 5 is equivalent to multiplying by 0x20.
                    let end := add(offset, shl(5, mload(proof)))
                    // Iterate over proof elements to compute root hash.
                    for {} 1 {} {
                        // Slot of `leaf` in scratch space.
                        // If the condition is true: 0x20, otherwise: 0x00.
                        let scratch := shl(5, gt(leaf, mload(offset)))
                        // Store elements to hash contiguously in scratch space.
                        // Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.
                        mstore(scratch, leaf)
                        mstore(xor(scratch, 0x20), mload(offset))
                        // Reuse `leaf` to store the hash to reduce stack operations.
                        leaf := keccak256(0x00, 0x40)
                        offset := add(offset, 0x20)
                        if iszero(lt(offset, end)) { break }
                    }
                }
                isValid := eq(leaf, root)
            }
        }
        /// @dev Returns whether `leaf` exists in the Merkle tree with `root`, given `proof`.
        function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf)
            internal
            pure
            returns (bool isValid)
        {
            /// @solidity memory-safe-assembly
            assembly {
                if proof.length {
                    // Left shift by 5 is equivalent to multiplying by 0x20.
                    let end := add(proof.offset, shl(5, proof.length))
                    // Initialize `offset` to the offset of `proof` in the calldata.
                    let offset := proof.offset
                    // Iterate over proof elements to compute root hash.
                    for {} 1 {} {
                        // Slot of `leaf` in scratch space.
                        // If the condition is true: 0x20, otherwise: 0x00.
                        let scratch := shl(5, gt(leaf, calldataload(offset)))
                        // Store elements to hash contiguously in scratch space.
                        // Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes.
                        mstore(scratch, leaf)
                        mstore(xor(scratch, 0x20), calldataload(offset))
                        // Reuse `leaf` to store the hash to reduce stack operations.
                        leaf := keccak256(0x00, 0x40)
                        offset := add(offset, 0x20)
                        if iszero(lt(offset, end)) { break }
                    }
                }
                isValid := eq(leaf, root)
            }
        }
        /// @dev Returns whether all `leaves` exist in the Merkle tree with `root`,
        /// given `proof` and `flags`.
        ///
        /// Note:
        /// - Breaking the invariant `flags.length == (leaves.length - 1) + proof.length`
        ///   will always return false.
        /// - The sum of the lengths of `proof` and `leaves` must never overflow.
        /// - Any non-zero word in the `flags` array is treated as true.
        /// - The memory offset of `proof` must be non-zero
        ///   (i.e. `proof` is not pointing to the scratch space).
        function verifyMultiProof(
            bytes32[] memory proof,
            bytes32 root,
            bytes32[] memory leaves,
            bool[] memory flags
        ) internal pure returns (bool isValid) {
            // Rebuilds the root by consuming and producing values on a queue.
            // The queue starts with the `leaves` array, and goes into a `hashes` array.
            // After the process, the last element on the queue is verified
            // to be equal to the `root`.
            //
            // The `flags` array denotes whether the sibling
            // should be popped from the queue (`flag == true`), or
            // should be popped from the `proof` (`flag == false`).
            /// @solidity memory-safe-assembly
            assembly {
                // Cache the lengths of the arrays.
                let leavesLength := mload(leaves)
                let proofLength := mload(proof)
                let flagsLength := mload(flags)
                // Advance the pointers of the arrays to point to the data.
                leaves := add(0x20, leaves)
                proof := add(0x20, proof)
                flags := add(0x20, flags)
                // If the number of flags is correct.
                for {} eq(add(leavesLength, proofLength), add(flagsLength, 1)) {} {
                    // For the case where `proof.length + leaves.length == 1`.
                    if iszero(flagsLength) {
                        // `isValid = (proof.length == 1 ? proof[0] : leaves[0]) == root`.
                        isValid := eq(mload(xor(leaves, mul(xor(proof, leaves), proofLength))), root)
                        break
                    }
                    // The required final proof offset if `flagsLength` is not zero, otherwise zero.
                    let proofEnd := add(proof, shl(5, proofLength))
                    // We can use the free memory space for the queue.
                    // We don't need to allocate, since the queue is temporary.
                    let hashesFront := mload(0x40)
                    // Copy the leaves into the hashes.
                    // Sometimes, a little memory expansion costs less than branching.
                    // Should cost less, even with a high free memory offset of 0x7d00.
                    leavesLength := shl(5, leavesLength)
                    for { let i := 0 } iszero(eq(i, leavesLength)) { i := add(i, 0x20) } {
                        mstore(add(hashesFront, i), mload(add(leaves, i)))
                    }
                    // Compute the back of the hashes.
                    let hashesBack := add(hashesFront, leavesLength)
                    // This is the end of the memory for the queue.
                    // We recycle `flagsLength` to save on stack variables (sometimes save gas).
                    flagsLength := add(hashesBack, shl(5, flagsLength))
                    for {} 1 {} {
                        // Pop from `hashes`.
                        let a := mload(hashesFront)
                        // Pop from `hashes`.
                        let b := mload(add(hashesFront, 0x20))
                        hashesFront := add(hashesFront, 0x40)
                        // If the flag is false, load the next proof,
                        // else, pops from the queue.
                        if iszero(mload(flags)) {
                            // Loads the next proof.
                            b := mload(proof)
                            proof := add(proof, 0x20)
                            // Unpop from `hashes`.
                            hashesFront := sub(hashesFront, 0x20)
                        }
                        // Advance to the next flag.
                        flags := add(flags, 0x20)
                        // Slot of `a` in scratch space.
                        // If the condition is true: 0x20, otherwise: 0x00.
                        let scratch := shl(5, gt(a, b))
                        // Hash the scratch space and push the result onto the queue.
                        mstore(scratch, a)
                        mstore(xor(scratch, 0x20), b)
                        mstore(hashesBack, keccak256(0x00, 0x40))
                        hashesBack := add(hashesBack, 0x20)
                        if iszero(lt(hashesBack, flagsLength)) { break }
                    }
                    isValid :=
                        and(
                            // Checks if the last value in the queue is same as the root.
                            eq(mload(sub(hashesBack, 0x20)), root),
                            // And whether all the proofs are used, if required.
                            eq(proofEnd, proof)
                        )
                    break
                }
            }
        }
        /// @dev Returns whether all `leaves` exist in the Merkle tree with `root`,
        /// given `proof` and `flags`.
        ///
        /// Note:
        /// - Breaking the invariant `flags.length == (leaves.length - 1) + proof.length`
        ///   will always return false.
        /// - Any non-zero word in the `flags` array is treated as true.
        /// - The calldata offset of `proof` must be non-zero
        ///   (i.e. `proof` is from a regular Solidity function with a 4-byte selector).
        function verifyMultiProofCalldata(
            bytes32[] calldata proof,
            bytes32 root,
            bytes32[] calldata leaves,
            bool[] calldata flags
        ) internal pure returns (bool isValid) {
            // Rebuilds the root by consuming and producing values on a queue.
            // The queue starts with the `leaves` array, and goes into a `hashes` array.
            // After the process, the last element on the queue is verified
            // to be equal to the `root`.
            //
            // The `flags` array denotes whether the sibling
            // should be popped from the queue (`flag == true`), or
            // should be popped from the `proof` (`flag == false`).
            /// @solidity memory-safe-assembly
            assembly {
                // If the number of flags is correct.
                for {} eq(add(leaves.length, proof.length), add(flags.length, 1)) {} {
                    // For the case where `proof.length + leaves.length == 1`.
                    if iszero(flags.length) {
                        // `isValid = (proof.length == 1 ? proof[0] : leaves[0]) == root`.
                        // forgefmt: disable-next-item
                        isValid := eq(
                            calldataload(
                                xor(leaves.offset, mul(xor(proof.offset, leaves.offset), proof.length))
                            ),
                            root
                        )
                        break
                    }
                    // The required final proof offset if `flagsLength` is not zero, otherwise zero.
                    let proofEnd := add(proof.offset, shl(5, proof.length))
                    // We can use the free memory space for the queue.
                    // We don't need to allocate, since the queue is temporary.
                    let hashesFront := mload(0x40)
                    // Copy the leaves into the hashes.
                    // Sometimes, a little memory expansion costs less than branching.
                    // Should cost less, even with a high free memory offset of 0x7d00.
                    calldatacopy(hashesFront, leaves.offset, shl(5, leaves.length))
                    // Compute the back of the hashes.
                    let hashesBack := add(hashesFront, shl(5, leaves.length))
                    // This is the end of the memory for the queue.
                    // We recycle `flagsLength` to save on stack variables (sometimes save gas).
                    flags.length := add(hashesBack, shl(5, flags.length))
                    // We don't need to make a copy of `proof.offset` or `flags.offset`,
                    // as they are pass-by-value (this trick may not always save gas).
                    for {} 1 {} {
                        // Pop from `hashes`.
                        let a := mload(hashesFront)
                        // Pop from `hashes`.
                        let b := mload(add(hashesFront, 0x20))
                        hashesFront := add(hashesFront, 0x40)
                        // If the flag is false, load the next proof,
                        // else, pops from the queue.
                        if iszero(calldataload(flags.offset)) {
                            // Loads the next proof.
                            b := calldataload(proof.offset)
                            proof.offset := add(proof.offset, 0x20)
                            // Unpop from `hashes`.
                            hashesFront := sub(hashesFront, 0x20)
                        }
                        // Advance to the next flag offset.
                        flags.offset := add(flags.offset, 0x20)
                        // Slot of `a` in scratch space.
                        // If the condition is true: 0x20, otherwise: 0x00.
                        let scratch := shl(5, gt(a, b))
                        // Hash the scratch space and push the result onto the queue.
                        mstore(scratch, a)
                        mstore(xor(scratch, 0x20), b)
                        mstore(hashesBack, keccak256(0x00, 0x40))
                        hashesBack := add(hashesBack, 0x20)
                        if iszero(lt(hashesBack, flags.length)) { break }
                    }
                    isValid :=
                        and(
                            // Checks if the last value in the queue is same as the root.
                            eq(mload(sub(hashesBack, 0x20)), root),
                            // And whether all the proofs are used, if required.
                            eq(proofEnd, proof.offset)
                        )
                    break
                }
            }
        }
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                   EMPTY CALLDATA HELPERS                   */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev Returns an empty calldata bytes32 array.
        function emptyProof() internal pure returns (bytes32[] calldata proof) {
            /// @solidity memory-safe-assembly
            assembly {
                proof.length := 0
            }
        }
        /// @dev Returns an empty calldata bytes32 array.
        function emptyLeaves() internal pure returns (bytes32[] calldata leaves) {
            /// @solidity memory-safe-assembly
            assembly {
                leaves.length := 0
            }
        }
        /// @dev Returns an empty calldata bool array.
        function emptyFlags() internal pure returns (bool[] calldata flags) {
            /// @solidity memory-safe-assembly
            assembly {
                flags.length := 0
            }
        }
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.4;
    /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
    /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
    /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
    /// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
    ///
    /// @dev Note:
    /// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
    /// - For ERC20s, this implementation won't check that a token has code,
    ///   responsibility is delegated to the caller.
    library SafeTransferLib {
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                       CUSTOM ERRORS                        */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev The ETH transfer has failed.
        error ETHTransferFailed();
        /// @dev The ERC20 `transferFrom` has failed.
        error TransferFromFailed();
        /// @dev The ERC20 `transfer` has failed.
        error TransferFailed();
        /// @dev The ERC20 `approve` has failed.
        error ApproveFailed();
        /// @dev The Permit2 operation has failed.
        error Permit2Failed();
        /// @dev The Permit2 amount must be less than `2**160 - 1`.
        error Permit2AmountOverflow();
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                         CONSTANTS                          */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
        uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
        /// @dev Suggested gas stipend for contract receiving ETH to perform a few
        /// storage reads and writes, but low enough to prevent griefing.
        uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
        /// @dev The unique EIP-712 domain domain separator for the DAI token contract.
        bytes32 internal constant DAI_DOMAIN_SEPARATOR =
            0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
        /// @dev The address for the WETH9 contract on Ethereum mainnet.
        address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
        /// @dev The canonical Permit2 address.
        /// [Github](https://github.com/Uniswap/permit2)
        /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
        address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                       ETH OPERATIONS                       */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
        //
        // The regular variants:
        // - Forwards all remaining gas to the target.
        // - Reverts if the target reverts.
        // - Reverts if the current contract has insufficient balance.
        //
        // The force variants:
        // - Forwards with an optional gas stipend
        //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
        // - If the target reverts, or if the gas stipend is exhausted,
        //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
        //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
        // - Reverts if the current contract has insufficient balance.
        //
        // The try variants:
        // - Forwards with a mandatory gas stipend.
        // - Instead of reverting, returns whether the transfer succeeded.
        /// @dev Sends `amount` (in wei) ETH to `to`.
        function safeTransferETH(address to, uint256 amount) internal {
            /// @solidity memory-safe-assembly
            assembly {
                if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
        }
        /// @dev Sends all the ETH in the current contract to `to`.
        function safeTransferAllETH(address to) internal {
            /// @solidity memory-safe-assembly
            assembly {
                // Transfer all the ETH and check if it succeeded or not.
                if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
        }
        /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
        function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
            /// @solidity memory-safe-assembly
            assembly {
                if lt(selfbalance(), amount) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, to) // Store the address in scratch space.
                    mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                    mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                    if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                }
            }
        }
        /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
        function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
            /// @solidity memory-safe-assembly
            assembly {
                if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, to) // Store the address in scratch space.
                    mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                    mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                    if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                }
            }
        }
        /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
        function forceSafeTransferETH(address to, uint256 amount) internal {
            /// @solidity memory-safe-assembly
            assembly {
                if lt(selfbalance(), amount) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, to) // Store the address in scratch space.
                    mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                    mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                    if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                }
            }
        }
        /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
        function forceSafeTransferAllETH(address to) internal {
            /// @solidity memory-safe-assembly
            assembly {
                // forgefmt: disable-next-item
                if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, to) // Store the address in scratch space.
                    mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                    mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                    if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                }
            }
        }
        /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
        function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
            internal
            returns (bool success)
        {
            /// @solidity memory-safe-assembly
            assembly {
                success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
            }
        }
        /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
        function trySafeTransferAllETH(address to, uint256 gasStipend)
            internal
            returns (bool success)
        {
            /// @solidity memory-safe-assembly
            assembly {
                success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
            }
        }
        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
        /*                      ERC20 OPERATIONS                      */
        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
        /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
        /// Reverts upon failure.
        ///
        /// The `from` account must have at least `amount` approved for
        /// the current contract to manage.
        function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
            /// @solidity memory-safe-assembly
            assembly {
                let m := mload(0x40) // Cache the free memory pointer.
                mstore(0x60, amount) // Store the `amount` argument.
                mstore(0x40, to) // Store the `to` argument.
                mstore(0x2c, shl(96, from)) // Store the `from` argument.
                mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                // Perform the transfer, reverting upon failure.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                        call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                    )
                ) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
                mstore(0x60, 0) // Restore the zero slot to zero.
                mstore(0x40, m) // Restore the free memory pointer.
            }
        }
        /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
        ///
        /// The `from` account must have at least `amount` approved for the current contract to manage.
        function trySafeTransferFrom(address token, address from, address to, uint256 amount)
            internal
            returns (bool success)
        {
            /// @solidity memory-safe-assembly
            assembly {
                let m := mload(0x40) // Cache the free memory pointer.
                mstore(0x60, amount) // Store the `amount` argument.
                mstore(0x40, to) // Store the `to` argument.
                mstore(0x2c, shl(96, from)) // Store the `from` argument.
                mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                success :=
                    and( // The arguments of `and` are evaluated from right to left.
                        or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                        call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                    )
                mstore(0x60, 0) // Restore the zero slot to zero.
                mstore(0x40, m) // Restore the free memory pointer.
            }
        }
        /// @dev Sends all of ERC20 `token` from `from` to `to`.
        /// Reverts upon failure.
        ///
        /// The `from` account must have their entire balance approved for the current contract to manage.
        function safeTransferAllFrom(address token, address from, address to)
            internal
            returns (uint256 amount)
        {
            /// @solidity memory-safe-assembly
            assembly {
                let m := mload(0x40) // Cache the free memory pointer.
                mstore(0x40, to) // Store the `to` argument.
                mstore(0x2c, shl(96, from)) // Store the `from` argument.
                mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                // Read the balance, reverting upon failure.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                        staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                    )
                ) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
                mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
                amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
                // Perform the transfer, reverting upon failure.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                        call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                    )
                ) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
                mstore(0x60, 0) // Restore the zero slot to zero.
                mstore(0x40, m) // Restore the free memory pointer.
            }
        }
        /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
        /// Reverts upon failure.
        function safeTransfer(address token, address to, uint256 amount) internal {
            /// @solidity memory-safe-assembly
            assembly {
                mstore(0x14, to) // Store the `to` argument.
                mstore(0x34, amount) // Store the `amount` argument.
                mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                // Perform the transfer, reverting upon failure.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                        call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    )
                ) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
                mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
            }
        }
        /// @dev Sends all of ERC20 `token` from the current contract to `to`.
        /// Reverts upon failure.
        function safeTransferAll(address token, address to) internal returns (uint256 amount) {
            /// @solidity memory-safe-assembly
            assembly {
                mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
                mstore(0x20, address()) // Store the address of the current contract.
                // Read the balance, reverting upon failure.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                        staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                    )
                ) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
                mstore(0x14, to) // Store the `to` argument.
                amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
                mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                // Perform the transfer, reverting upon failure.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                        call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    )
                ) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
                mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
            }
        }
        /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
        /// Reverts upon failure.
        function safeApprove(address token, address to, uint256 amount) internal {
            /// @solidity memory-safe-assembly
            assembly {
                mstore(0x14, to) // Store the `to` argument.
                mstore(0x34, amount) // Store the `amount` argument.
                mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                // Perform the approval, reverting upon failure.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                        call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    )
                ) {
                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                    revert(0x1c, 0x04)
                }
                mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
            }
        }
        /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
        /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
        /// then retries the approval again (some tokens, e.g. USDT, requires this).
        /// Reverts upon failure.
        function safeApproveWithRetry(address token, address to, uint256 amount) internal {
            /// @solidity memory-safe-assembly
            assembly {
                mstore(0x14, to) // Store the `to` argument.
                mstore(0x34, amount) // Store the `amount` argument.
                mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                // Perform the approval, retrying upon failure.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                        call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    )
                ) {
                    mstore(0x34, 0) // Store 0 for the `amount`.
                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                    pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                    mstore(0x34, amount) // Store back the original `amount`.
                    // Retry the approval, reverting upon failure.
                    if iszero(
                        and(
                            or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
                            call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                        )
                    ) {
                        mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                        revert(0x1c, 0x04)
                    }
                }
                mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
            }
        }
        /// @dev Returns the amount of ERC20 `token` owned by `account`.
        /// Returns zero if the `token` does not exist.
        function balanceOf(address token, address account) internal view returns (uint256 amount) {
            /// @solidity memory-safe-assembly
            assembly {
                mstore(0x14, account) // Store the `account` argument.
                mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                amount :=
                    mul( // The arguments of `mul` are evaluated from right to left.
                        mload(0x20),
                        and( // The arguments of `and` are evaluated from right to left.
                            gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                            staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                        )
                    )
            }
        }
        /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
        /// If the initial attempt fails, try to use Permit2 to transfer the token.
        /// Reverts upon failure.
        ///
        /// The `from` account must have at least `amount` approved for the current contract to manage.
        function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
            if (!trySafeTransferFrom(token, from, to, amount)) {
                permit2TransferFrom(token, from, to, amount);
            }
        }
        /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
        /// Reverts upon failure.
        function permit2TransferFrom(address token, address from, address to, uint256 amount)
            internal
        {
            /// @solidity memory-safe-assembly
            assembly {
                let m := mload(0x40)
                mstore(add(m, 0x74), shr(96, shl(96, token)))
                mstore(add(m, 0x54), amount)
                mstore(add(m, 0x34), to)
                mstore(add(m, 0x20), shl(96, from))
                // `transferFrom(address,address,uint160,address)`.
                mstore(m, 0x36c78516000000000000000000000000)
                let p := PERMIT2
                let exists := eq(chainid(), 1)
                if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
                if iszero(and(call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00), exists)) {
                    mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                    revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
                }
            }
        }
        /// @dev Permit a user to spend a given amount of
        /// another user's tokens via native EIP-2612 permit if possible, falling
        /// back to Permit2 if native permit fails or is not implemented on the token.
        function permit2(
            address token,
            address owner,
            address spender,
            uint256 amount,
            uint256 deadline,
            uint8 v,
            bytes32 r,
            bytes32 s
        ) internal {
            bool success;
            /// @solidity memory-safe-assembly
            assembly {
                for {} shl(96, xor(token, WETH9)) {} {
                    mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                    if iszero(
                        and( // The arguments of `and` are evaluated from right to left.
                            lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                            // Gas stipend to limit gas burn for tokens that don't refund gas when
                            // an non-existing function is called. 5K should be enough for a SLOAD.
                            staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                        )
                    ) { break }
                    // After here, we can be sure that token is a contract.
                    let m := mload(0x40)
                    mstore(add(m, 0x34), spender)
                    mstore(add(m, 0x20), shl(96, owner))
                    mstore(add(m, 0x74), deadline)
                    if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                        mstore(0x14, owner)
                        mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                        mstore(add(m, 0x94), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                        mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                        // `nonces` is already at `add(m, 0x54)`.
                        // `1` is already stored at `add(m, 0x94)`.
                        mstore(add(m, 0xb4), and(0xff, v))
                        mstore(add(m, 0xd4), r)
                        mstore(add(m, 0xf4), s)
                        success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                        break
                    }
                    mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                    mstore(add(m, 0x54), amount)
                    mstore(add(m, 0x94), and(0xff, v))
                    mstore(add(m, 0xb4), r)
                    mstore(add(m, 0xd4), s)
                    success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                    break
                }
            }
            if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
        }
        /// @dev Simple permit on the Permit2 contract.
        function simplePermit2(
            address token,
            address owner,
            address spender,
            uint256 amount,
            uint256 deadline,
            uint8 v,
            bytes32 r,
            bytes32 s
        ) internal {
            /// @solidity memory-safe-assembly
            assembly {
                let m := mload(0x40)
                mstore(m, 0x927da105) // `allowance(address,address,address)`.
                {
                    let addressMask := shr(96, not(0))
                    mstore(add(m, 0x20), and(addressMask, owner))
                    mstore(add(m, 0x40), and(addressMask, token))
                    mstore(add(m, 0x60), and(addressMask, spender))
                    mstore(add(m, 0xc0), and(addressMask, spender))
                }
                let p := mul(PERMIT2, iszero(shr(160, amount)))
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                        staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                    )
                ) {
                    mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                    revert(add(0x18, shl(2, iszero(p))), 0x04)
                }
                mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
                // `owner` is already `add(m, 0x20)`.
                // `token` is already at `add(m, 0x40)`.
                mstore(add(m, 0x60), amount)
                mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
                // `nonce` is already at `add(m, 0xa0)`.
                // `spender` is already at `add(m, 0xc0)`.
                mstore(add(m, 0xe0), deadline)
                mstore(add(m, 0x100), 0x100) // `signature` offset.
                mstore(add(m, 0x120), 0x41) // `signature` length.
                mstore(add(m, 0x140), r)
                mstore(add(m, 0x160), s)
                mstore(add(m, 0x180), shl(248, v))
                if iszero(call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00)) {
                    mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.24;
    /// @notice Reentrancy guard mixin.
    /// @author Soledge (https://github.com/vectorized/soledge/blob/main/src/utils/ReentrancyGuard.sol)
    ///
    /// Note: This implementation utilizes the `TSTORE` and `TLOAD` opcodes.
    /// Please ensure that the chain you are deploying on supports them.
    abstract contract ReentrancyGuard {
        /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/
        /*                       CUSTOM ERRORS                        */
        /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/
        /// @dev Unauthorized reentrant call.
        error Reentrancy();
        /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/
        /*                          STORAGE                           */
        /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/
        /// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
        /// 9 bytes is large enough to avoid collisions in practice,
        /// but not too large to result in excessive bytecode bloat.
        uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;
        /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/
        /*                      REENTRANCY GUARD                      */
        /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/
        /// @dev Guards a function from reentrancy.
        modifier nonReentrant() virtual {
            /// @solidity memory-safe-assembly
            assembly {
                if tload(_REENTRANCY_GUARD_SLOT) {
                    mstore(0x00, 0xab143c06) // `Reentrancy()`.
                    revert(0x1c, 0x04)
                }
                tstore(_REENTRANCY_GUARD_SLOT, address())
            }
            _;
            /// @solidity memory-safe-assembly
            assembly {
                tstore(_REENTRANCY_GUARD_SLOT, 0)
            }
        }
        /// @dev Guards a view function from read-only reentrancy.
        modifier nonReadReentrant() virtual {
            /// @solidity memory-safe-assembly
            assembly {
                if tload(_REENTRANCY_GUARD_SLOT) {
                    mstore(0x00, 0xab143c06) // `Reentrancy()`.
                    revert(0x1c, 0x04)
                }
            }
            _;
        }
    }
    

    File 2 of 3: BoredApeYachtClub
    // File: @openzeppelin/contracts/utils/Context.sol
    
    // SPDX-License-Identifier: MIT
    
    pragma solidity >=0.6.0 <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 GSN 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 payable) {
            return msg.sender;
        }
    
        function _msgData() internal view virtual returns (bytes memory) {
            this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
            return msg.data;
        }
    }
    
    // File: @openzeppelin/contracts/introspection/IERC165.sol
    
    
    
    pragma solidity >=0.6.0 <0.8.0;
    
    /**
     * @dev Interface of the ERC165 standard, as defined in the
     * https://eips.ethereum.org/EIPS/eip-165[EIP].
     *
     * Implementers can declare support of contract interfaces, which can then be
     * queried by others ({ERC165Checker}).
     *
     * For an implementation, see {ERC165}.
     */
    interface IERC165 {
        /**
         * @dev Returns true if this contract implements the interface defined by
         * `interfaceId`. See the corresponding
         * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
         * to learn more about how these ids are created.
         *
         * This function call must use less than 30 000 gas.
         */
        function supportsInterface(bytes4 interfaceId) external view returns (bool);
    }
    
    // File: @openzeppelin/contracts/token/ERC721/IERC721.sol
    
    
    
    pragma solidity >=0.6.2 <0.8.0;
    
    
    /**
     * @dev Required interface of an ERC721 compliant contract.
     */
    interface IERC721 is IERC165 {
        /**
         * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
         */
        event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
    
        /**
         * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
         */
        event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
    
        /**
         * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
         */
        event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
    
        /**
         * @dev Returns the number of tokens in ``owner``'s account.
         */
        function balanceOf(address owner) external view returns (uint256 balance);
    
        /**
         * @dev Returns the owner of the `tokenId` token.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function ownerOf(uint256 tokenId) external view returns (address owner);
    
        /**
         * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
         * are aware of the ERC721 protocol to prevent tokens from being forever locked.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must exist and be owned by `from`.
         * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function safeTransferFrom(address from, address to, uint256 tokenId) external;
    
        /**
         * @dev Transfers `tokenId` token from `from` to `to`.
         *
         * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must be owned by `from`.
         * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
         *
         * Emits a {Transfer} event.
         */
        function transferFrom(address from, address to, uint256 tokenId) external;
    
        /**
         * @dev Gives permission to `to` to transfer `tokenId` token to another account.
         * The approval is cleared when the token is transferred.
         *
         * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
         *
         * Requirements:
         *
         * - The caller must own the token or be an approved operator.
         * - `tokenId` must exist.
         *
         * Emits an {Approval} event.
         */
        function approve(address to, uint256 tokenId) external;
    
        /**
         * @dev Returns the account approved for `tokenId` token.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function getApproved(uint256 tokenId) external view returns (address operator);
    
        /**
         * @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 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);
    
        /**
          * @dev Safely transfers `tokenId` token from `from` to `to`.
          *
          * Requirements:
          *
          * - `from` cannot be the zero address.
          * - `to` cannot be the zero address.
          * - `tokenId` token must exist and be owned by `from`.
          * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
          * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
          *
          * Emits a {Transfer} event.
          */
        function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
    }
    
    // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
    
    
    
    pragma solidity >=0.6.2 <0.8.0;
    
    
    /**
     * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
     * @dev See https://eips.ethereum.org/EIPS/eip-721
     */
    interface IERC721Metadata is IERC721 {
    
        /**
         * @dev Returns the token collection name.
         */
        function name() external view returns (string memory);
    
        /**
         * @dev Returns the token collection symbol.
         */
        function symbol() external view returns (string memory);
    
        /**
         * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
         */
        function tokenURI(uint256 tokenId) external view returns (string memory);
    }
    
    // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
    
    
    
    pragma solidity >=0.6.2 <0.8.0;
    
    
    /**
     * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
     * @dev See https://eips.ethereum.org/EIPS/eip-721
     */
    interface IERC721Enumerable is IERC721 {
    
        /**
         * @dev Returns the total amount of tokens stored by the contract.
         */
        function totalSupply() external view returns (uint256);
    
        /**
         * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
         * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
         */
        function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
    
        /**
         * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
         * Use along with {totalSupply} to enumerate all tokens.
         */
        function tokenByIndex(uint256 index) external view returns (uint256);
    }
    
    // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
    
    
    
    pragma solidity >=0.6.0 <0.8.0;
    
    /**
     * @title ERC721 token receiver interface
     * @dev Interface for any contract that wants to support safeTransfers
     * from ERC721 asset contracts.
     */
    interface IERC721Receiver {
        /**
         * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
         * by `operator` from `from`, this function is called.
         *
         * It must return its Solidity selector to confirm the token transfer.
         * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
         *
         * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
         */
        function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
    }
    
    // File: @openzeppelin/contracts/introspection/ERC165.sol
    
    
    
    pragma solidity >=0.6.0 <0.8.0;
    
    
    /**
     * @dev Implementation of the {IERC165} interface.
     *
     * Contracts may inherit from this and call {_registerInterface} to declare
     * their support of an interface.
     */
    abstract contract ERC165 is IERC165 {
        /*
         * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
         */
        bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
    
        /**
         * @dev Mapping of interface ids to whether or not it's supported.
         */
        mapping(bytes4 => bool) private _supportedInterfaces;
    
        constructor () internal {
            // Derived contracts need only register support for their own interfaces,
            // we register support for ERC165 itself here
            _registerInterface(_INTERFACE_ID_ERC165);
        }
    
        /**
         * @dev See {IERC165-supportsInterface}.
         *
         * Time complexity O(1), guaranteed to always use less than 30 000 gas.
         */
        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
            return _supportedInterfaces[interfaceId];
        }
    
        /**
         * @dev Registers the contract as an implementer of the interface defined by
         * `interfaceId`. Support of the actual ERC165 interface is automatic and
         * registering its interface id is not required.
         *
         * See {IERC165-supportsInterface}.
         *
         * Requirements:
         *
         * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
         */
        function _registerInterface(bytes4 interfaceId) internal virtual {
            require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
            _supportedInterfaces[interfaceId] = true;
        }
    }
    
    // File: @openzeppelin/contracts/math/SafeMath.sol
    
    
    
    pragma solidity >=0.6.0 <0.8.0;
    
    /**
     * @dev Wrappers over Solidity's arithmetic operations with added overflow
     * checks.
     *
     * Arithmetic operations in Solidity wrap on overflow. This can easily result
     * in bugs, because programmers usually assume that an overflow raises an
     * error, which is the standard behavior in high level programming languages.
     * `SafeMath` restores this intuition by reverting the transaction when an
     * operation overflows.
     *
     * Using this library instead of the unchecked operations eliminates an entire
     * class of bugs, so it's recommended to use it always.
     */
    library SafeMath {
        /**
         * @dev Returns the addition of two unsigned integers, with an overflow flag.
         *
         * _Available since v3.4._
         */
        function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    
        /**
         * @dev Returns the substraction of two unsigned integers, with an overflow flag.
         *
         * _Available since v3.4._
         */
        function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    
        /**
         * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
         *
         * _Available since v3.4._
         */
        function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    
        /**
         * @dev Returns the division of two unsigned integers, with a division by zero flag.
         *
         * _Available since v3.4._
         */
        function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    
        /**
         * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
         *
         * _Available since v3.4._
         */
        function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    
        /**
         * @dev Returns the addition of two unsigned integers, reverting on
         * overflow.
         *
         * Counterpart to Solidity's `+` operator.
         *
         * Requirements:
         *
         * - Addition cannot overflow.
         */
        function add(uint256 a, uint256 b) internal pure returns (uint256) {
            uint256 c = a + b;
            require(c >= a, "SafeMath: addition overflow");
            return c;
        }
    
        /**
         * @dev Returns the subtraction of two unsigned integers, reverting on
         * overflow (when the result is negative).
         *
         * Counterpart to Solidity's `-` operator.
         *
         * Requirements:
         *
         * - Subtraction cannot overflow.
         */
        function sub(uint256 a, uint256 b) internal pure returns (uint256) {
            require(b <= a, "SafeMath: subtraction overflow");
            return a - b;
        }
    
        /**
         * @dev Returns the multiplication of two unsigned integers, reverting on
         * overflow.
         *
         * Counterpart to Solidity's `*` operator.
         *
         * Requirements:
         *
         * - Multiplication cannot overflow.
         */
        function mul(uint256 a, uint256 b) internal pure returns (uint256) {
            if (a == 0) return 0;
            uint256 c = a * b;
            require(c / a == b, "SafeMath: multiplication overflow");
            return c;
        }
    
        /**
         * @dev Returns the integer division of two unsigned integers, reverting on
         * division by zero. The result is rounded towards zero.
         *
         * Counterpart to Solidity's `/` operator. Note: this function uses a
         * `revert` opcode (which leaves remaining gas untouched) while Solidity
         * uses an invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function div(uint256 a, uint256 b) internal pure returns (uint256) {
            require(b > 0, "SafeMath: division by zero");
            return a / b;
        }
    
        /**
         * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
         * reverting when dividing by zero.
         *
         * Counterpart to Solidity's `%` operator. This function uses a `revert`
         * opcode (which leaves remaining gas untouched) while Solidity uses an
         * invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function mod(uint256 a, uint256 b) internal pure returns (uint256) {
            require(b > 0, "SafeMath: modulo by zero");
            return a % b;
        }
    
        /**
         * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
         * overflow (when the result is negative).
         *
         * CAUTION: This function is deprecated because it requires allocating memory for the error
         * message unnecessarily. For custom revert reasons use {trySub}.
         *
         * Counterpart to Solidity's `-` operator.
         *
         * Requirements:
         *
         * - Subtraction cannot overflow.
         */
        function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
            require(b <= a, errorMessage);
            return a - b;
        }
    
        /**
         * @dev Returns the integer division of two unsigned integers, reverting with custom message on
         * division by zero. The result is rounded towards zero.
         *
         * CAUTION: This function is deprecated because it requires allocating memory for the error
         * message unnecessarily. For custom revert reasons use {tryDiv}.
         *
         * Counterpart to Solidity's `/` operator. Note: this function uses a
         * `revert` opcode (which leaves remaining gas untouched) while Solidity
         * uses an invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
            require(b > 0, errorMessage);
            return a / b;
        }
    
        /**
         * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
         * reverting with custom message when dividing by zero.
         *
         * CAUTION: This function is deprecated because it requires allocating memory for the error
         * message unnecessarily. For custom revert reasons use {tryMod}.
         *
         * Counterpart to Solidity's `%` operator. This function uses a `revert`
         * opcode (which leaves remaining gas untouched) while Solidity uses an
         * invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
    
    // File: @openzeppelin/contracts/utils/Address.sol
    
    
    
    pragma solidity >=0.6.2 <0.8.0;
    
    /**
     * @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
         * ====
         */
        function isContract(address account) internal view returns (bool) {
            // This method relies on extcodesize, which returns 0 for contracts in
            // construction, since the code is only stored at the end of the
            // constructor execution.
    
            uint256 size;
            // solhint-disable-next-line no-inline-assembly
            assembly { size := extcodesize(account) }
            return size > 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");
    
            // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
            (bool success, ) = recipient.call{ value: amount }("");
            require(success, "Address: unable to send value, recipient may have reverted");
        }
    
        /**
         * @dev Performs a Solidity function call using a low level `call`. A
         * plain`call` is an unsafe replacement for a function call: use this
         * function instead.
         *
         * If `target` reverts with a revert reason, it is bubbled up by this
         * function (like regular Solidity function calls).
         *
         * Returns the raw returned data. To convert to the expected return value,
         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
         *
         * Requirements:
         *
         * - `target` must be a contract.
         * - calling `target` with `data` must not revert.
         *
         * _Available since v3.1._
         */
        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
          return functionCall(target, data, "Address: low-level call failed");
        }
    
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
         * `errorMessage` as a fallback revert reason when `target` reverts.
         *
         * _Available since v3.1._
         */
        function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
            return functionCallWithValue(target, data, 0, errorMessage);
        }
    
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but also transferring `value` wei to `target`.
         *
         * Requirements:
         *
         * - the calling contract must have an ETH balance of at least `value`.
         * - the called Solidity function must be `payable`.
         *
         * _Available since v3.1._
         */
        function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
        }
    
        /**
         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
         * with `errorMessage` as a fallback revert reason when `target` reverts.
         *
         * _Available since v3.1._
         */
        function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
            require(address(this).balance >= value, "Address: insufficient balance for call");
            require(isContract(target), "Address: call to non-contract");
    
            // solhint-disable-next-line avoid-low-level-calls
            (bool success, bytes memory returndata) = target.call{ value: value }(data);
            return _verifyCallResult(success, returndata, errorMessage);
        }
    
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but performing a static call.
         *
         * _Available since v3.3._
         */
        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
            return functionStaticCall(target, data, "Address: low-level static call failed");
        }
    
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
         * but performing a static call.
         *
         * _Available since v3.3._
         */
        function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
            require(isContract(target), "Address: static call to non-contract");
    
            // solhint-disable-next-line avoid-low-level-calls
            (bool success, bytes memory returndata) = target.staticcall(data);
            return _verifyCallResult(success, returndata, errorMessage);
        }
    
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but performing a delegate call.
         *
         * _Available since v3.4._
         */
        function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
            return functionDelegateCall(target, data, "Address: low-level delegate call failed");
        }
    
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
         * but performing a delegate call.
         *
         * _Available since v3.4._
         */
        function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
            require(isContract(target), "Address: delegate call to non-contract");
    
            // solhint-disable-next-line avoid-low-level-calls
            (bool success, bytes memory returndata) = target.delegatecall(data);
            return _verifyCallResult(success, returndata, errorMessage);
        }
    
        function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
            if (success) {
                return returndata;
            } else {
                // Look for revert reason and bubble it up if present
                if (returndata.length > 0) {
                    // The easiest way to bubble the revert reason is using memory via assembly
    
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
    }
    
    // File: @openzeppelin/contracts/utils/EnumerableSet.sol
    
    
    
    pragma solidity >=0.6.0 <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.
     */
    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;
    
                // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
                // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
    
                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] = toDeleteIndex + 1; // All indexes are 1-based
    
                // 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) {
            require(set._values.length > index, "EnumerableSet: index out of bounds");
            return set._values[index];
        }
    
        // 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);
        }
    
        // 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))));
        }
    
    
        // 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 on 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));
        }
    }
    
    // File: @openzeppelin/contracts/utils/EnumerableMap.sol
    
    
    
    pragma solidity >=0.6.0 <0.8.0;
    
    /**
     * @dev Library for managing an enumerable variant of Solidity's
     * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
     * type.
     *
     * Maps have the following properties:
     *
     * - Entries are added, removed, and checked for existence in constant time
     * (O(1)).
     * - Entries are enumerated in O(n). No guarantees are made on the ordering.
     *
     * ```
     * contract Example {
     *     // Add the library methods
     *     using EnumerableMap for EnumerableMap.UintToAddressMap;
     *
     *     // Declare a set state variable
     *     EnumerableMap.UintToAddressMap private myMap;
     * }
     * ```
     *
     * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
     * supported.
     */
    library EnumerableMap {
        // To implement this library for multiple types with as little code
        // repetition as possible, we write it in terms of a generic Map type with
        // bytes32 keys and values.
        // The Map implementation uses private functions, and user-facing
        // implementations (such as Uint256ToAddressMap) are just wrappers around
        // the underlying Map.
        // This means that we can only create new EnumerableMaps for types that fit
        // in bytes32.
    
        struct MapEntry {
            bytes32 _key;
            bytes32 _value;
        }
    
        struct Map {
            // Storage of map keys and values
            MapEntry[] _entries;
    
            // Position of the entry defined by a key in the `entries` array, plus 1
            // because index 0 means a key is not in the map.
            mapping (bytes32 => uint256) _indexes;
        }
    
        /**
         * @dev Adds a key-value pair to a map, or updates the value for an existing
         * key. O(1).
         *
         * Returns true if the key was added to the map, that is if it was not
         * already present.
         */
        function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
            // We read and store the key's index to prevent multiple reads from the same storage slot
            uint256 keyIndex = map._indexes[key];
    
            if (keyIndex == 0) { // Equivalent to !contains(map, key)
                map._entries.push(MapEntry({ _key: key, _value: value }));
                // The entry is stored at length-1, but we add 1 to all indexes
                // and use 0 as a sentinel value
                map._indexes[key] = map._entries.length;
                return true;
            } else {
                map._entries[keyIndex - 1]._value = value;
                return false;
            }
        }
    
        /**
         * @dev Removes a key-value pair from a map. O(1).
         *
         * Returns true if the key was removed from the map, that is if it was present.
         */
        function _remove(Map storage map, bytes32 key) private returns (bool) {
            // We read and store the key's index to prevent multiple reads from the same storage slot
            uint256 keyIndex = map._indexes[key];
    
            if (keyIndex != 0) { // Equivalent to contains(map, key)
                // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
                // in the array, and then remove the last entry (sometimes called as 'swap and pop').
                // This modifies the order of the array, as noted in {at}.
    
                uint256 toDeleteIndex = keyIndex - 1;
                uint256 lastIndex = map._entries.length - 1;
    
                // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
                // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
    
                MapEntry storage lastEntry = map._entries[lastIndex];
    
                // Move the last entry to the index where the entry to delete is
                map._entries[toDeleteIndex] = lastEntry;
                // Update the index for the moved entry
                map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
    
                // Delete the slot where the moved entry was stored
                map._entries.pop();
    
                // Delete the index for the deleted slot
                delete map._indexes[key];
    
                return true;
            } else {
                return false;
            }
        }
    
        /**
         * @dev Returns true if the key is in the map. O(1).
         */
        function _contains(Map storage map, bytes32 key) private view returns (bool) {
            return map._indexes[key] != 0;
        }
    
        /**
         * @dev Returns the number of key-value pairs in the map. O(1).
         */
        function _length(Map storage map) private view returns (uint256) {
            return map._entries.length;
        }
    
       /**
        * @dev Returns the key-value pair stored at position `index` in the map. O(1).
        *
        * Note that there are no guarantees on the ordering of entries inside the
        * array, and it may change when more entries are added or removed.
        *
        * Requirements:
        *
        * - `index` must be strictly less than {length}.
        */
        function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
            require(map._entries.length > index, "EnumerableMap: index out of bounds");
    
            MapEntry storage entry = map._entries[index];
            return (entry._key, entry._value);
        }
    
        /**
         * @dev Tries to returns the value associated with `key`.  O(1).
         * Does not revert if `key` is not in the map.
         */
        function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
            uint256 keyIndex = map._indexes[key];
            if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
            return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
        }
    
        /**
         * @dev Returns the value associated with `key`.  O(1).
         *
         * Requirements:
         *
         * - `key` must be in the map.
         */
        function _get(Map storage map, bytes32 key) private view returns (bytes32) {
            uint256 keyIndex = map._indexes[key];
            require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
            return map._entries[keyIndex - 1]._value; // All indexes are 1-based
        }
    
        /**
         * @dev Same as {_get}, with a custom error message when `key` is not in the map.
         *
         * CAUTION: This function is deprecated because it requires allocating memory for the error
         * message unnecessarily. For custom revert reasons use {_tryGet}.
         */
        function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
            uint256 keyIndex = map._indexes[key];
            require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
            return map._entries[keyIndex - 1]._value; // All indexes are 1-based
        }
    
        // UintToAddressMap
    
        struct UintToAddressMap {
            Map _inner;
        }
    
        /**
         * @dev Adds a key-value pair to a map, or updates the value for an existing
         * key. O(1).
         *
         * Returns true if the key was added to the map, that is if it was not
         * already present.
         */
        function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
            return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
        }
    
        /**
         * @dev Removes a value from a set. O(1).
         *
         * Returns true if the key was removed from the map, that is if it was present.
         */
        function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
            return _remove(map._inner, bytes32(key));
        }
    
        /**
         * @dev Returns true if the key is in the map. O(1).
         */
        function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
            return _contains(map._inner, bytes32(key));
        }
    
        /**
         * @dev Returns the number of elements in the map. O(1).
         */
        function length(UintToAddressMap storage map) internal view returns (uint256) {
            return _length(map._inner);
        }
    
       /**
        * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
            (bytes32 key, bytes32 value) = _at(map._inner, index);
            return (uint256(key), address(uint160(uint256(value))));
        }
    
        /**
         * @dev Tries to returns the value associated with `key`.  O(1).
         * Does not revert if `key` is not in the map.
         *
         * _Available since v3.4._
         */
        function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
            (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
            return (success, address(uint160(uint256(value))));
        }
    
        /**
         * @dev Returns the value associated with `key`.  O(1).
         *
         * Requirements:
         *
         * - `key` must be in the map.
         */
        function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
            return address(uint160(uint256(_get(map._inner, bytes32(key)))));
        }
    
        /**
         * @dev Same as {get}, with a custom error message when `key` is not in the map.
         *
         * CAUTION: This function is deprecated because it requires allocating memory for the error
         * message unnecessarily. For custom revert reasons use {tryGet}.
         */
        function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
            return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
        }
    }
    
    // File: @openzeppelin/contracts/utils/Strings.sol
    
    
    
    pragma solidity >=0.6.0 <0.8.0;
    
    /**
     * @dev String operations.
     */
    library Strings {
        /**
         * @dev Converts a `uint256` to its ASCII `string` 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);
            uint256 index = digits - 1;
            temp = value;
            while (temp != 0) {
                buffer[index--] = bytes1(uint8(48 + temp % 10));
                temp /= 10;
            }
            return string(buffer);
        }
    }
    
    // File: @openzeppelin/contracts/token/ERC721/ERC721.sol
    
    
    
    pragma solidity >=0.6.0 <0.8.0;
    
    
    
    
    
    
    
    
    
    
    
    
    /**
     * @title ERC721 Non-Fungible Token Standard basic implementation
     * @dev see https://eips.ethereum.org/EIPS/eip-721
     */
    contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
        using SafeMath for uint256;
        using Address for address;
        using EnumerableSet for EnumerableSet.UintSet;
        using EnumerableMap for EnumerableMap.UintToAddressMap;
        using Strings for uint256;
    
        // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
        // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
        bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
    
        // Mapping from holder address to their (enumerable) set of owned tokens
        mapping (address => EnumerableSet.UintSet) private _holderTokens;
    
        // Enumerable mapping from token ids to their owners
        EnumerableMap.UintToAddressMap private _tokenOwners;
    
        // Mapping from token ID to approved address
        mapping (uint256 => address) private _tokenApprovals;
    
        // Mapping from owner to operator approvals
        mapping (address => mapping (address => bool)) private _operatorApprovals;
    
        // Token name
        string private _name;
    
        // Token symbol
        string private _symbol;
    
        // Optional mapping for token URIs
        mapping (uint256 => string) private _tokenURIs;
    
        // Base URI
        string private _baseURI;
    
        /*
         *     bytes4(keccak256('balanceOf(address)')) == 0x70a08231
         *     bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
         *     bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
         *     bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
         *     bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
         *     bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
         *     bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
         *     bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
         *     bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
         *
         *     => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
         *        0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
         */
        bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
    
        /*
         *     bytes4(keccak256('name()')) == 0x06fdde03
         *     bytes4(keccak256('symbol()')) == 0x95d89b41
         *     bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
         *
         *     => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
         */
        bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
    
        /*
         *     bytes4(keccak256('totalSupply()')) == 0x18160ddd
         *     bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
         *     bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
         *
         *     => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
         */
        bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
    
        /**
         * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
         */
        constructor (string memory name_, string memory symbol_) public {
            _name = name_;
            _symbol = symbol_;
    
            // register the supported interfaces to conform to ERC721 via ERC165
            _registerInterface(_INTERFACE_ID_ERC721);
            _registerInterface(_INTERFACE_ID_ERC721_METADATA);
            _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
        }
    
        /**
         * @dev See {IERC721-balanceOf}.
         */
        function balanceOf(address owner) public view virtual override returns (uint256) {
            require(owner != address(0), "ERC721: balance query for the zero address");
            return _holderTokens[owner].length();
        }
    
        /**
         * @dev See {IERC721-ownerOf}.
         */
        function ownerOf(uint256 tokenId) public view virtual override returns (address) {
            return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
        }
    
        /**
         * @dev See {IERC721Metadata-name}.
         */
        function name() public view virtual override returns (string memory) {
            return _name;
        }
    
        /**
         * @dev See {IERC721Metadata-symbol}.
         */
        function symbol() public view virtual override returns (string memory) {
            return _symbol;
        }
    
        /**
         * @dev See {IERC721Metadata-tokenURI}.
         */
        function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
            require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
    
            string memory _tokenURI = _tokenURIs[tokenId];
            string memory base = baseURI();
    
            // If there is no base URI, return the token URI.
            if (bytes(base).length == 0) {
                return _tokenURI;
            }
            // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
            if (bytes(_tokenURI).length > 0) {
                return string(abi.encodePacked(base, _tokenURI));
            }
            // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
            return string(abi.encodePacked(base, tokenId.toString()));
        }
    
        /**
        * @dev Returns the base URI set via {_setBaseURI}. This will be
        * automatically added as a prefix in {tokenURI} to each token's URI, or
        * to the token ID if no specific URI is set for that token ID.
        */
        function baseURI() public view virtual returns (string memory) {
            return _baseURI;
        }
    
        /**
         * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
         */
        function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
            return _holderTokens[owner].at(index);
        }
    
        /**
         * @dev See {IERC721Enumerable-totalSupply}.
         */
        function totalSupply() public view virtual override returns (uint256) {
            // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
            return _tokenOwners.length();
        }
    
        /**
         * @dev See {IERC721Enumerable-tokenByIndex}.
         */
        function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
            (uint256 tokenId, ) = _tokenOwners.at(index);
            return tokenId;
        }
    
        /**
         * @dev See {IERC721-approve}.
         */
        function approve(address to, uint256 tokenId) public virtual override {
            address owner = ERC721.ownerOf(tokenId);
            require(to != owner, "ERC721: approval to current owner");
    
            require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
                "ERC721: approve caller is not owner nor approved for all"
            );
    
            _approve(to, tokenId);
        }
    
        /**
         * @dev See {IERC721-getApproved}.
         */
        function getApproved(uint256 tokenId) public view virtual override returns (address) {
            require(_exists(tokenId), "ERC721: approved query for nonexistent token");
    
            return _tokenApprovals[tokenId];
        }
    
        /**
         * @dev See {IERC721-setApprovalForAll}.
         */
        function setApprovalForAll(address operator, bool approved) public virtual override {
            require(operator != _msgSender(), "ERC721: approve to caller");
    
            _operatorApprovals[_msgSender()][operator] = approved;
            emit ApprovalForAll(_msgSender(), operator, approved);
        }
    
        /**
         * @dev See {IERC721-isApprovedForAll}.
         */
        function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
            return _operatorApprovals[owner][operator];
        }
    
        /**
         * @dev See {IERC721-transferFrom}.
         */
        function transferFrom(address from, address to, uint256 tokenId) public virtual override {
            //solhint-disable-next-line max-line-length
            require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
    
            _transfer(from, to, tokenId);
        }
    
        /**
         * @dev See {IERC721-safeTransferFrom}.
         */
        function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
            safeTransferFrom(from, to, tokenId, "");
        }
    
        /**
         * @dev See {IERC721-safeTransferFrom}.
         */
        function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
            require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
            _safeTransfer(from, to, tokenId, _data);
        }
    
        /**
         * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
         * are aware of the ERC721 protocol to prevent tokens from being forever locked.
         *
         * `_data` is additional data, it has no specified format and it is sent in call to `to`.
         *
         * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
         * implement alternative mechanisms to perform token transfer, such as signature-based.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must exist and be owned by `from`.
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
            _transfer(from, to, tokenId);
            require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
        }
    
        /**
         * @dev Returns whether `tokenId` exists.
         *
         * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
         *
         * Tokens start existing when they are minted (`_mint`),
         * and stop existing when they are burned (`_burn`).
         */
        function _exists(uint256 tokenId) internal view virtual returns (bool) {
            return _tokenOwners.contains(tokenId);
        }
    
        /**
         * @dev Returns whether `spender` is allowed to manage `tokenId`.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
            require(_exists(tokenId), "ERC721: operator query for nonexistent token");
            address owner = ERC721.ownerOf(tokenId);
            return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
        }
    
        /**
         * @dev Safely mints `tokenId` and transfers it to `to`.
         *
         * Requirements:
         d*
         * - `tokenId` must not exist.
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function _safeMint(address to, uint256 tokenId) internal virtual {
            _safeMint(to, tokenId, "");
        }
    
        /**
         * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
         * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
         */
        function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
            _mint(to, tokenId);
            require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
        }
    
        /**
         * @dev Mints `tokenId` and transfers it to `to`.
         *
         * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
         *
         * Requirements:
         *
         * - `tokenId` must not exist.
         * - `to` cannot be the zero address.
         *
         * Emits a {Transfer} event.
         */
        function _mint(address to, uint256 tokenId) internal virtual {
            require(to != address(0), "ERC721: mint to the zero address");
            require(!_exists(tokenId), "ERC721: token already minted");
    
            _beforeTokenTransfer(address(0), to, tokenId);
    
            _holderTokens[to].add(tokenId);
    
            _tokenOwners.set(tokenId, to);
    
            emit Transfer(address(0), to, tokenId);
        }
    
        /**
         * @dev Destroys `tokenId`.
         * The approval is cleared when the token is burned.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         *
         * Emits a {Transfer} event.
         */
        function _burn(uint256 tokenId) internal virtual {
            address owner = ERC721.ownerOf(tokenId); // internal owner
    
            _beforeTokenTransfer(owner, address(0), tokenId);
    
            // Clear approvals
            _approve(address(0), tokenId);
    
            // Clear metadata (if any)
            if (bytes(_tokenURIs[tokenId]).length != 0) {
                delete _tokenURIs[tokenId];
            }
    
            _holderTokens[owner].remove(tokenId);
    
            _tokenOwners.remove(tokenId);
    
            emit Transfer(owner, address(0), tokenId);
        }
    
        /**
         * @dev Transfers `tokenId` from `from` to `to`.
         *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
         *
         * Requirements:
         *
         * - `to` cannot be the zero address.
         * - `tokenId` token must be owned by `from`.
         *
         * Emits a {Transfer} event.
         */
        function _transfer(address from, address to, uint256 tokenId) internal virtual {
            require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
            require(to != address(0), "ERC721: transfer to the zero address");
    
            _beforeTokenTransfer(from, to, tokenId);
    
            // Clear approvals from the previous owner
            _approve(address(0), tokenId);
    
            _holderTokens[from].remove(tokenId);
            _holderTokens[to].add(tokenId);
    
            _tokenOwners.set(tokenId, to);
    
            emit Transfer(from, to, tokenId);
        }
    
        /**
         * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
            require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
            _tokenURIs[tokenId] = _tokenURI;
        }
    
        /**
         * @dev Internal function to set the base URI for all token IDs. It is
         * automatically added as a prefix to the value returned in {tokenURI},
         * or to the token ID if {tokenURI} is empty.
         */
        function _setBaseURI(string memory baseURI_) internal virtual {
            _baseURI = baseURI_;
        }
    
        /**
         * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
         * The call is not executed if the target address is not a contract.
         *
         * @param from address representing the previous owner of the given token ID
         * @param to target address that will receive the tokens
         * @param tokenId uint256 ID of the token to be transferred
         * @param _data bytes optional data to send along with the call
         * @return bool whether the call correctly returned the expected magic value
         */
        function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
            private returns (bool)
        {
            if (!to.isContract()) {
                return true;
            }
            bytes memory returndata = to.functionCall(abi.encodeWithSelector(
                IERC721Receiver(to).onERC721Received.selector,
                _msgSender(),
                from,
                tokenId,
                _data
            ), "ERC721: transfer to non ERC721Receiver implementer");
            bytes4 retval = abi.decode(returndata, (bytes4));
            return (retval == _ERC721_RECEIVED);
        }
    
        /**
         * @dev Approve `to` to operate on `tokenId`
         *
         * Emits an {Approval} event.
         */
        function _approve(address to, uint256 tokenId) internal virtual {
            _tokenApprovals[tokenId] = to;
            emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
        }
    
        /**
         * @dev Hook that is called before any token transfer. This includes minting
         * and burning.
         *
         * Calling conditions:
         *
         * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
         * transferred to `to`.
         * - When `from` is zero, `tokenId` will be minted for `to`.
         * - When `to` is zero, ``from``'s `tokenId` will be burned.
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         *
         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
         */
        function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
    }
    
    // File: @openzeppelin/contracts/access/Ownable.sol
    
    
    
    pragma solidity >=0.6.0 <0.8.0;
    
    /**
     * @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 () internal {
            address msgSender = _msgSender();
            _owner = msgSender;
            emit OwnershipTransferred(address(0), msgSender);
        }
    
        /**
         * @dev Returns the address of the current owner.
         */
        function owner() public view virtual returns (address) {
            return _owner;
        }
    
        /**
         * @dev Throws if called by any account other than the owner.
         */
        modifier onlyOwner() {
            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 {
            emit OwnershipTransferred(_owner, address(0));
            _owner = 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");
            emit OwnershipTransferred(_owner, newOwner);
            _owner = newOwner;
        }
    }
    
    // File: contracts/BoredApeYachtClub.sol
    
    
    pragma solidity ^0.7.0;
    
    
    
    /**
     * @title BoredApeYachtClub contract
     * @dev Extends ERC721 Non-Fungible Token Standard basic implementation
     */
    contract BoredApeYachtClub is ERC721, Ownable {
        using SafeMath for uint256;
    
        string public BAYC_PROVENANCE = "";
    
        uint256 public startingIndexBlock;
    
        uint256 public startingIndex;
    
        uint256 public constant apePrice = 80000000000000000; //0.08 ETH
    
        uint public constant maxApePurchase = 20;
    
        uint256 public MAX_APES;
    
        bool public saleIsActive = false;
    
        uint256 public REVEAL_TIMESTAMP;
    
        constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 saleStart) ERC721(name, symbol) {
            MAX_APES = maxNftSupply;
            REVEAL_TIMESTAMP = saleStart + (86400 * 9);
        }
    
        function withdraw() public onlyOwner {
            uint balance = address(this).balance;
            msg.sender.transfer(balance);
        }
    
        /**
         * Set some Bored Apes aside
         */
        function reserveApes() public onlyOwner {        
            uint supply = totalSupply();
            uint i;
            for (i = 0; i < 30; i++) {
                _safeMint(msg.sender, supply + i);
            }
        }
    
        /**
         * DM Gargamel in Discord that you're standing right behind him.
         */
        function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner {
            REVEAL_TIMESTAMP = revealTimeStamp;
        } 
    
        /*     
        * Set provenance once it's calculated
        */
        function setProvenanceHash(string memory provenanceHash) public onlyOwner {
            BAYC_PROVENANCE = provenanceHash;
        }
    
        function setBaseURI(string memory baseURI) public onlyOwner {
            _setBaseURI(baseURI);
        }
    
        /*
        * Pause sale if active, make active if paused
        */
        function flipSaleState() public onlyOwner {
            saleIsActive = !saleIsActive;
        }
    
        /**
        * Mints Bored Apes
        */
        function mintApe(uint numberOfTokens) public payable {
            require(saleIsActive, "Sale must be active to mint Ape");
            require(numberOfTokens <= maxApePurchase, "Can only mint 20 tokens at a time");
            require(totalSupply().add(numberOfTokens) <= MAX_APES, "Purchase would exceed max supply of Apes");
            require(apePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
            
            for(uint i = 0; i < numberOfTokens; i++) {
                uint mintIndex = totalSupply();
                if (totalSupply() < MAX_APES) {
                    _safeMint(msg.sender, mintIndex);
                }
            }
    
            // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after
            // the end of pre-sale, set the starting index block
            if (startingIndexBlock == 0 && (totalSupply() == MAX_APES || block.timestamp >= REVEAL_TIMESTAMP)) {
                startingIndexBlock = block.number;
            } 
        }
    
        /**
         * Set the starting index for the collection
         */
        function setStartingIndex() public {
            require(startingIndex == 0, "Starting index is already set");
            require(startingIndexBlock != 0, "Starting index block must be set");
            
            startingIndex = uint(blockhash(startingIndexBlock)) % MAX_APES;
            // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
            if (block.number.sub(startingIndexBlock) > 255) {
                startingIndex = uint(blockhash(block.number - 1)) % MAX_APES;
            }
            // Prevent default sequence
            if (startingIndex == 0) {
                startingIndex = startingIndex.add(1);
            }
        }
    
        /**
         * Set the starting index block for the collection, essentially unblocking
         * setting starting index
         */
        function emergencySetStartingIndexBlock() public onlyOwner {
            require(startingIndex == 0, "Starting index is already set");
            
            startingIndexBlock = block.number;
        }
    }

    File 3 of 3: MutantApeYachtClub
    // SPDX-License-Identifier: MIT
    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() {
            _setOwner(_msgSender());
        }
        /**
         * @dev Returns the address of the current owner.
         */
        function owner() public view virtual returns (address) {
            return _owner;
        }
        /**
         * @dev Throws if called by any account other than the owner.
         */
        modifier onlyOwner() {
            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 {
            _setOwner(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");
            _setOwner(newOwner);
        }
        function _setOwner(address newOwner) private {
            address oldOwner = _owner;
            _owner = newOwner;
            emit OwnershipTransferred(oldOwner, newOwner);
        }
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    import "../utils/Context.sol";
    /**
     * @dev Contract module which allows children to implement an emergency stop
     * mechanism that can be triggered by an authorized account.
     *
     * This module is used through inheritance. It will make available the
     * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
     * the functions of your contract. Note that they will not be pausable by
     * simply including this module, only once the modifiers are put in place.
     */
    abstract contract Pausable is Context {
        /**
         * @dev Emitted when the pause is triggered by `account`.
         */
        event Paused(address account);
        /**
         * @dev Emitted when the pause is lifted by `account`.
         */
        event Unpaused(address account);
        bool private _paused;
        /**
         * @dev Initializes the contract in unpaused state.
         */
        constructor() {
            _paused = false;
        }
        /**
         * @dev Returns true if the contract is paused, and false otherwise.
         */
        function paused() public view virtual returns (bool) {
            return _paused;
        }
        /**
         * @dev Modifier to make a function callable only when the contract is not paused.
         *
         * Requirements:
         *
         * - The contract must not be paused.
         */
        modifier whenNotPaused() {
            require(!paused(), "Pausable: paused");
            _;
        }
        /**
         * @dev Modifier to make a function callable only when the contract is paused.
         *
         * Requirements:
         *
         * - The contract must be paused.
         */
        modifier whenPaused() {
            require(paused(), "Pausable: not paused");
            _;
        }
        /**
         * @dev Triggers stopped state.
         *
         * Requirements:
         *
         * - The contract must not be paused.
         */
        function _pause() internal virtual whenNotPaused {
            _paused = true;
            emit Paused(_msgSender());
        }
        /**
         * @dev Returns to normal state.
         *
         * Requirements:
         *
         * - The contract must be paused.
         */
        function _unpause() internal virtual whenPaused {
            _paused = false;
            emit Unpaused(_msgSender());
        }
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    /**
     * @dev Contract module that helps prevent reentrant calls to a function.
     *
     * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
     * available, which can be applied to functions to make sure there are no nested
     * (reentrant) calls to them.
     *
     * Note that because there is a single `nonReentrant` guard, functions marked as
     * `nonReentrant` may not call one another. This can be worked around by making
     * those functions `private`, and then adding `external` `nonReentrant` entry
     * points to them.
     *
     * TIP: If you would like to learn more about reentrancy and alternative ways
     * to protect against it, check out our blog post
     * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
     */
    abstract contract ReentrancyGuard {
        // Booleans are more expensive than uint256 or any type that takes up a full
        // word because each write operation emits an extra SLOAD to first read the
        // slot's contents, replace the bits taken up by the boolean, and then write
        // back. This is the compiler's defense against contract upgrades and
        // pointer aliasing, and it cannot be disabled.
        // The values being non-zero value makes deployment a bit more expensive,
        // but in exchange the refund on every call to nonReentrant will be lower in
        // amount. Since refunds are capped to a percentage of the total
        // transaction's gas, it is best to keep them low in cases like this one, to
        // increase the likelihood of the full refund coming into effect.
        uint256 private constant _NOT_ENTERED = 1;
        uint256 private constant _ENTERED = 2;
        uint256 private _status;
        constructor() {
            _status = _NOT_ENTERED;
        }
        /**
         * @dev Prevents a contract from calling itself, directly or indirectly.
         * Calling a `nonReentrant` function from another `nonReentrant`
         * function is not supported. It is possible to prevent this from happening
         * by making the `nonReentrant` function external, and make it call a
         * `private` function that does the actual work.
         */
        modifier nonReentrant() {
            // On the first call to nonReentrant, _notEntered will be true
            require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
            // Any calls to nonReentrant after this point will fail
            _status = _ENTERED;
            _;
            // By storing the original value once again, a refund is triggered (see
            // https://eips.ethereum.org/EIPS/eip-2200)
            _status = _NOT_ENTERED;
        }
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    import "./IERC721.sol";
    import "./IERC721Receiver.sol";
    import "./extensions/IERC721Metadata.sol";
    import "../../utils/Address.sol";
    import "../../utils/Context.sol";
    import "../../utils/Strings.sol";
    import "../../utils/introspection/ERC165.sol";
    /**
     * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
     * the Metadata extension, but not including the Enumerable extension, which is available separately as
     * {ERC721Enumerable}.
     */
    contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
        using Address for address;
        using Strings for uint256;
        // Token name
        string private _name;
        // Token symbol
        string private _symbol;
        // Mapping from token ID to owner address
        mapping(uint256 => address) private _owners;
        // Mapping owner address to token count
        mapping(address => uint256) private _balances;
        // Mapping from token ID to approved address
        mapping(uint256 => address) private _tokenApprovals;
        // Mapping from owner to operator approvals
        mapping(address => mapping(address => bool)) private _operatorApprovals;
        /**
         * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
         */
        constructor(string memory name_, string memory symbol_) {
            _name = name_;
            _symbol = symbol_;
        }
        /**
         * @dev See {IERC165-supportsInterface}.
         */
        function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
            return
                interfaceId == type(IERC721).interfaceId ||
                interfaceId == type(IERC721Metadata).interfaceId ||
                super.supportsInterface(interfaceId);
        }
        /**
         * @dev See {IERC721-balanceOf}.
         */
        function balanceOf(address owner) public view virtual override returns (uint256) {
            require(owner != address(0), "ERC721: balance query for the zero address");
            return _balances[owner];
        }
        /**
         * @dev See {IERC721-ownerOf}.
         */
        function ownerOf(uint256 tokenId) public view virtual override returns (address) {
            address owner = _owners[tokenId];
            require(owner != address(0), "ERC721: owner query for nonexistent token");
            return owner;
        }
        /**
         * @dev See {IERC721Metadata-name}.
         */
        function name() public view virtual override returns (string memory) {
            return _name;
        }
        /**
         * @dev See {IERC721Metadata-symbol}.
         */
        function symbol() public view virtual override returns (string memory) {
            return _symbol;
        }
        /**
         * @dev See {IERC721Metadata-tokenURI}.
         */
        function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
            require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
            string memory baseURI = _baseURI();
            return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
        }
        /**
         * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
         * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
         * by default, can be overriden in child contracts.
         */
        function _baseURI() internal view virtual returns (string memory) {
            return "";
        }
        /**
         * @dev See {IERC721-approve}.
         */
        function approve(address to, uint256 tokenId) public virtual override {
            address owner = ERC721.ownerOf(tokenId);
            require(to != owner, "ERC721: approval to current owner");
            require(
                _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
                "ERC721: approve caller is not owner nor approved for all"
            );
            _approve(to, tokenId);
        }
        /**
         * @dev See {IERC721-getApproved}.
         */
        function getApproved(uint256 tokenId) public view virtual override returns (address) {
            require(_exists(tokenId), "ERC721: approved query for nonexistent token");
            return _tokenApprovals[tokenId];
        }
        /**
         * @dev See {IERC721-setApprovalForAll}.
         */
        function setApprovalForAll(address operator, bool approved) public virtual override {
            require(operator != _msgSender(), "ERC721: approve to caller");
            _operatorApprovals[_msgSender()][operator] = approved;
            emit ApprovalForAll(_msgSender(), operator, approved);
        }
        /**
         * @dev See {IERC721-isApprovedForAll}.
         */
        function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
            return _operatorApprovals[owner][operator];
        }
        /**
         * @dev See {IERC721-transferFrom}.
         */
        function transferFrom(
            address from,
            address to,
            uint256 tokenId
        ) public virtual override {
            //solhint-disable-next-line max-line-length
            require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
            _transfer(from, to, tokenId);
        }
        /**
         * @dev See {IERC721-safeTransferFrom}.
         */
        function safeTransferFrom(
            address from,
            address to,
            uint256 tokenId
        ) public virtual override {
            safeTransferFrom(from, to, tokenId, "");
        }
        /**
         * @dev See {IERC721-safeTransferFrom}.
         */
        function safeTransferFrom(
            address from,
            address to,
            uint256 tokenId,
            bytes memory _data
        ) public virtual override {
            require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
            _safeTransfer(from, to, tokenId, _data);
        }
        /**
         * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
         * are aware of the ERC721 protocol to prevent tokens from being forever locked.
         *
         * `_data` is additional data, it has no specified format and it is sent in call to `to`.
         *
         * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
         * implement alternative mechanisms to perform token transfer, such as signature-based.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must exist and be owned by `from`.
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function _safeTransfer(
            address from,
            address to,
            uint256 tokenId,
            bytes memory _data
        ) internal virtual {
            _transfer(from, to, tokenId);
            require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
        }
        /**
         * @dev Returns whether `tokenId` exists.
         *
         * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
         *
         * Tokens start existing when they are minted (`_mint`),
         * and stop existing when they are burned (`_burn`).
         */
        function _exists(uint256 tokenId) internal view virtual returns (bool) {
            return _owners[tokenId] != address(0);
        }
        /**
         * @dev Returns whether `spender` is allowed to manage `tokenId`.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
            require(_exists(tokenId), "ERC721: operator query for nonexistent token");
            address owner = ERC721.ownerOf(tokenId);
            return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
        }
        /**
         * @dev Safely mints `tokenId` and transfers it to `to`.
         *
         * Requirements:
         *
         * - `tokenId` must not exist.
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function _safeMint(address to, uint256 tokenId) internal virtual {
            _safeMint(to, tokenId, "");
        }
        /**
         * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
         * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
         */
        function _safeMint(
            address to,
            uint256 tokenId,
            bytes memory _data
        ) internal virtual {
            _mint(to, tokenId);
            require(
                _checkOnERC721Received(address(0), to, tokenId, _data),
                "ERC721: transfer to non ERC721Receiver implementer"
            );
        }
        /**
         * @dev Mints `tokenId` and transfers it to `to`.
         *
         * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
         *
         * Requirements:
         *
         * - `tokenId` must not exist.
         * - `to` cannot be the zero address.
         *
         * Emits a {Transfer} event.
         */
        function _mint(address to, uint256 tokenId) internal virtual {
            require(to != address(0), "ERC721: mint to the zero address");
            require(!_exists(tokenId), "ERC721: token already minted");
            _beforeTokenTransfer(address(0), to, tokenId);
            _balances[to] += 1;
            _owners[tokenId] = to;
            emit Transfer(address(0), to, tokenId);
        }
        /**
         * @dev Destroys `tokenId`.
         * The approval is cleared when the token is burned.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         *
         * Emits a {Transfer} event.
         */
        function _burn(uint256 tokenId) internal virtual {
            address owner = ERC721.ownerOf(tokenId);
            _beforeTokenTransfer(owner, address(0), tokenId);
            // Clear approvals
            _approve(address(0), tokenId);
            _balances[owner] -= 1;
            delete _owners[tokenId];
            emit Transfer(owner, address(0), tokenId);
        }
        /**
         * @dev Transfers `tokenId` from `from` to `to`.
         *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
         *
         * Requirements:
         *
         * - `to` cannot be the zero address.
         * - `tokenId` token must be owned by `from`.
         *
         * Emits a {Transfer} event.
         */
        function _transfer(
            address from,
            address to,
            uint256 tokenId
        ) internal virtual {
            require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
            require(to != address(0), "ERC721: transfer to the zero address");
            _beforeTokenTransfer(from, to, tokenId);
            // Clear approvals from the previous owner
            _approve(address(0), tokenId);
            _balances[from] -= 1;
            _balances[to] += 1;
            _owners[tokenId] = to;
            emit Transfer(from, to, tokenId);
        }
        /**
         * @dev Approve `to` to operate on `tokenId`
         *
         * Emits a {Approval} event.
         */
        function _approve(address to, uint256 tokenId) internal virtual {
            _tokenApprovals[tokenId] = to;
            emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
        }
        /**
         * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
         * The call is not executed if the target address is not a contract.
         *
         * @param from address representing the previous owner of the given token ID
         * @param to target address that will receive the tokens
         * @param tokenId uint256 ID of the token to be transferred
         * @param _data bytes optional data to send along with the call
         * @return bool whether the call correctly returned the expected magic value
         */
        function _checkOnERC721Received(
            address from,
            address to,
            uint256 tokenId,
            bytes memory _data
        ) private returns (bool) {
            if (to.isContract()) {
                try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
                    return retval == IERC721Receiver(to).onERC721Received.selector;
                } catch (bytes memory reason) {
                    if (reason.length == 0) {
                        revert("ERC721: transfer to non ERC721Receiver implementer");
                    } else {
                        assembly {
                            revert(add(32, reason), mload(reason))
                        }
                    }
                }
            } else {
                return true;
            }
        }
        /**
         * @dev Hook that is called before any token transfer. This includes minting
         * and burning.
         *
         * Calling conditions:
         *
         * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
         * transferred to `to`.
         * - When `from` is zero, `tokenId` will be minted for `to`.
         * - When `to` is zero, ``from``'s `tokenId` will be burned.
         * - `from` and `to` are never both zero.
         *
         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
         */
        function _beforeTokenTransfer(
            address from,
            address to,
            uint256 tokenId
        ) internal virtual {}
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    import "../../utils/introspection/IERC165.sol";
    /**
     * @dev Required interface of an ERC721 compliant contract.
     */
    interface IERC721 is IERC165 {
        /**
         * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
         */
        event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
        /**
         * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
         */
        event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
        /**
         * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
         */
        event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
        /**
         * @dev Returns the number of tokens in ``owner``'s account.
         */
        function balanceOf(address owner) external view returns (uint256 balance);
        /**
         * @dev Returns the owner of the `tokenId` token.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function ownerOf(uint256 tokenId) external view returns (address owner);
        /**
         * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
         * are aware of the ERC721 protocol to prevent tokens from being forever locked.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must exist and be owned by `from`.
         * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function safeTransferFrom(
            address from,
            address to,
            uint256 tokenId
        ) external;
        /**
         * @dev Transfers `tokenId` token from `from` to `to`.
         *
         * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must be owned by `from`.
         * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
         *
         * Emits a {Transfer} event.
         */
        function transferFrom(
            address from,
            address to,
            uint256 tokenId
        ) external;
        /**
         * @dev Gives permission to `to` to transfer `tokenId` token to another account.
         * The approval is cleared when the token is transferred.
         *
         * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
         *
         * Requirements:
         *
         * - The caller must own the token or be an approved operator.
         * - `tokenId` must exist.
         *
         * Emits an {Approval} event.
         */
        function approve(address to, uint256 tokenId) external;
        /**
         * @dev Returns the account approved for `tokenId` token.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function getApproved(uint256 tokenId) external view returns (address operator);
        /**
         * @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 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);
        /**
         * @dev Safely transfers `tokenId` token from `from` to `to`.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must exist and be owned by `from`.
         * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function safeTransferFrom(
            address from,
            address to,
            uint256 tokenId,
            bytes calldata data
        ) external;
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    /**
     * @title ERC721 token receiver interface
     * @dev Interface for any contract that wants to support safeTransfers
     * from ERC721 asset contracts.
     */
    interface IERC721Receiver {
        /**
         * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
         * by `operator` from `from`, this function is called.
         *
         * It must return its Solidity selector to confirm the token transfer.
         * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
         *
         * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
         */
        function onERC721Received(
            address operator,
            address from,
            uint256 tokenId,
            bytes calldata data
        ) external returns (bytes4);
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    import "../ERC721.sol";
    import "./IERC721Enumerable.sol";
    /**
     * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
     * enumerability of all the token ids in the contract as well as all token ids owned by each
     * account.
     */
    abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
        // Mapping from owner to list of owned token IDs
        mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
        // Mapping from token ID to index of the owner tokens list
        mapping(uint256 => uint256) private _ownedTokensIndex;
        // Array with all token ids, used for enumeration
        uint256[] private _allTokens;
        // Mapping from token id to position in the allTokens array
        mapping(uint256 => uint256) private _allTokensIndex;
        /**
         * @dev See {IERC165-supportsInterface}.
         */
        function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
            return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
        }
        /**
         * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
         */
        function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
            require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
            return _ownedTokens[owner][index];
        }
        /**
         * @dev See {IERC721Enumerable-totalSupply}.
         */
        function totalSupply() public view virtual override returns (uint256) {
            return _allTokens.length;
        }
        /**
         * @dev See {IERC721Enumerable-tokenByIndex}.
         */
        function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
            require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
            return _allTokens[index];
        }
        /**
         * @dev Hook that is called before any token transfer. This includes minting
         * and burning.
         *
         * Calling conditions:
         *
         * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
         * transferred to `to`.
         * - When `from` is zero, `tokenId` will be minted for `to`.
         * - When `to` is zero, ``from``'s `tokenId` will be burned.
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         *
         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
         */
        function _beforeTokenTransfer(
            address from,
            address to,
            uint256 tokenId
        ) internal virtual override {
            super._beforeTokenTransfer(from, to, tokenId);
            if (from == address(0)) {
                _addTokenToAllTokensEnumeration(tokenId);
            } else if (from != to) {
                _removeTokenFromOwnerEnumeration(from, tokenId);
            }
            if (to == address(0)) {
                _removeTokenFromAllTokensEnumeration(tokenId);
            } else if (to != from) {
                _addTokenToOwnerEnumeration(to, tokenId);
            }
        }
        /**
         * @dev Private function to add a token to this extension's ownership-tracking data structures.
         * @param to address representing the new owner of the given token ID
         * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
         */
        function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
            uint256 length = ERC721.balanceOf(to);
            _ownedTokens[to][length] = tokenId;
            _ownedTokensIndex[tokenId] = length;
        }
        /**
         * @dev Private function to add a token to this extension's token tracking data structures.
         * @param tokenId uint256 ID of the token to be added to the tokens list
         */
        function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
            _allTokensIndex[tokenId] = _allTokens.length;
            _allTokens.push(tokenId);
        }
        /**
         * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
         * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
         * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
         * This has O(1) time complexity, but alters the order of the _ownedTokens array.
         * @param from address representing the previous owner of the given token ID
         * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
         */
        function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
            // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
            // then delete the last slot (swap and pop).
            uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
            uint256 tokenIndex = _ownedTokensIndex[tokenId];
            // When the token to delete is the last token, the swap operation is unnecessary
            if (tokenIndex != lastTokenIndex) {
                uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
                _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
                _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
            }
            // This also deletes the contents at the last position of the array
            delete _ownedTokensIndex[tokenId];
            delete _ownedTokens[from][lastTokenIndex];
        }
        /**
         * @dev Private function to remove a token from this extension's token tracking data structures.
         * This has O(1) time complexity, but alters the order of the _allTokens array.
         * @param tokenId uint256 ID of the token to be removed from the tokens list
         */
        function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
            // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
            // then delete the last slot (swap and pop).
            uint256 lastTokenIndex = _allTokens.length - 1;
            uint256 tokenIndex = _allTokensIndex[tokenId];
            // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
            // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
            // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
            uint256 lastTokenId = _allTokens[lastTokenIndex];
            _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
            // This also deletes the contents at the last position of the array
            delete _allTokensIndex[tokenId];
            _allTokens.pop();
        }
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    import "../IERC721.sol";
    /**
     * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
     * @dev See https://eips.ethereum.org/EIPS/eip-721
     */
    interface IERC721Enumerable is IERC721 {
        /**
         * @dev Returns the total amount of tokens stored by the contract.
         */
        function totalSupply() external view returns (uint256);
        /**
         * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
         * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
         */
        function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
        /**
         * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
         * Use along with {totalSupply} to enumerate all tokens.
         */
        function tokenByIndex(uint256 index) external view returns (uint256);
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    import "../IERC721.sol";
    /**
     * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
     * @dev See https://eips.ethereum.org/EIPS/eip-721
     */
    interface IERC721Metadata is IERC721 {
        /**
         * @dev Returns the token collection name.
         */
        function name() external view returns (string memory);
        /**
         * @dev Returns the token collection symbol.
         */
        function symbol() external view returns (string memory);
        /**
         * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
         */
        function tokenURI(uint256 tokenId) external view returns (string memory);
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
    /**
     * @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
         * ====
         */
        function isContract(address account) internal view returns (bool) {
            // This method relies on extcodesize, which returns 0 for contracts in
            // construction, since the code is only stored at the end of the
            // constructor execution.
            uint256 size;
            assembly {
                size := extcodesize(account)
            }
            return size > 0;
        }
        /**
         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
         * `recipient`, forwarding all available gas and reverting on errors.
         *
         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
         * of certain opcodes, possibly making contracts go over the 2300 gas limit
         * imposed by `transfer`, making them unable to receive funds via
         * `transfer`. {sendValue} removes this limitation.
         *
         * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
         *
         * IMPORTANT: because control is transferred to `recipient`, care must be
         * taken to not create reentrancy vulnerabilities. Consider using
         * {ReentrancyGuard} or the
         * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
         */
        function sendValue(address payable recipient, uint256 amount) internal {
            require(address(this).balance >= amount, "Address: insufficient balance");
            (bool success, ) = recipient.call{value: amount}("");
            require(success, "Address: unable to send value, recipient may have reverted");
        }
        /**
         * @dev Performs a Solidity function call using a low level `call`. A
         * plain `call` is an unsafe replacement for a function call: use this
         * function instead.
         *
         * If `target` reverts with a revert reason, it is bubbled up by this
         * function (like regular Solidity function calls).
         *
         * Returns the raw returned data. To convert to the expected return value,
         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
         *
         * Requirements:
         *
         * - `target` must be a contract.
         * - calling `target` with `data` must not revert.
         *
         * _Available since v3.1._
         */
        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
            return functionCall(target, data, "Address: low-level call failed");
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
         * `errorMessage` as a fallback revert reason when `target` reverts.
         *
         * _Available since v3.1._
         */
        function functionCall(
            address target,
            bytes memory data,
            string memory errorMessage
        ) internal returns (bytes memory) {
            return functionCallWithValue(target, data, 0, errorMessage);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but also transferring `value` wei to `target`.
         *
         * Requirements:
         *
         * - the calling contract must have an ETH balance of at least `value`.
         * - the called Solidity function must be `payable`.
         *
         * _Available since v3.1._
         */
        function functionCallWithValue(
            address target,
            bytes memory data,
            uint256 value
        ) internal returns (bytes memory) {
            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
        }
        /**
         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
         * with `errorMessage` as a fallback revert reason when `target` reverts.
         *
         * _Available since v3.1._
         */
        function functionCallWithValue(
            address target,
            bytes memory data,
            uint256 value,
            string memory errorMessage
        ) internal returns (bytes memory) {
            require(address(this).balance >= value, "Address: insufficient balance for call");
            require(isContract(target), "Address: call to non-contract");
            (bool success, bytes memory returndata) = target.call{value: value}(data);
            return _verifyCallResult(success, returndata, errorMessage);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but performing a static call.
         *
         * _Available since v3.3._
         */
        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
            return functionStaticCall(target, data, "Address: low-level static call failed");
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
         * but performing a static call.
         *
         * _Available since v3.3._
         */
        function functionStaticCall(
            address target,
            bytes memory data,
            string memory errorMessage
        ) internal view returns (bytes memory) {
            require(isContract(target), "Address: static call to non-contract");
            (bool success, bytes memory returndata) = target.staticcall(data);
            return _verifyCallResult(success, returndata, errorMessage);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but performing a delegate call.
         *
         * _Available since v3.4._
         */
        function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
            return functionDelegateCall(target, data, "Address: low-level delegate call failed");
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
         * but performing a delegate call.
         *
         * _Available since v3.4._
         */
        function functionDelegateCall(
            address target,
            bytes memory data,
            string memory errorMessage
        ) internal returns (bytes memory) {
            require(isContract(target), "Address: delegate call to non-contract");
            (bool success, bytes memory returndata) = target.delegatecall(data);
            return _verifyCallResult(success, returndata, errorMessage);
        }
        function _verifyCallResult(
            bool success,
            bytes memory returndata,
            string memory errorMessage
        ) private pure returns (bytes memory) {
            if (success) {
                return returndata;
            } else {
                // Look for revert reason and bubble it up if present
                if (returndata.length > 0) {
                    // The easiest way to bubble the revert reason is using memory via assembly
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
    }
    // SPDX-License-Identifier: MIT
    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.0;
    /**
     * @dev String operations.
     */
    library Strings {
        bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
        /**
         * @dev Converts a `uint256` to its ASCII `string` decimal representation.
         */
        function toString(uint256 value) internal pure returns (string memory) {
            // Inspired by OraclizeAPI's implementation - MIT licence
            // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
            if (value == 0) {
                return "0";
            }
            uint256 temp = value;
            uint256 digits;
            while (temp != 0) {
                digits++;
                temp /= 10;
            }
            bytes memory buffer = new bytes(digits);
            while (value != 0) {
                digits -= 1;
                buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                value /= 10;
            }
            return string(buffer);
        }
        /**
         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
         */
        function toHexString(uint256 value) internal pure returns (string memory) {
            if (value == 0) {
                return "0x00";
            }
            uint256 temp = value;
            uint256 length = 0;
            while (temp != 0) {
                length++;
                temp >>= 8;
            }
            return toHexString(value, length);
        }
        /**
         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
         */
        function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
            bytes memory buffer = new bytes(2 * length + 2);
            buffer[0] = "0";
            buffer[1] = "x";
            for (uint256 i = 2 * length + 1; i > 1; --i) {
                buffer[i] = _HEX_SYMBOLS[value & 0xf];
                value >>= 4;
            }
            require(value == 0, "Strings: hex length insufficient");
            return string(buffer);
        }
    }
    // SPDX-License-Identifier: MIT
    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
    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.6;
    abstract contract Bacc {
        function burnSerumForAddress(uint256 typeId, address burnTokenAddress)
            external
            virtual;
        function balanceOf(address account, uint256 id)
            public
            view
            virtual
            returns (uint256);
    }
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.6;
    abstract contract Bayc {
        function ownerOf(uint256 tokenId) public view virtual returns (address);
    }
    // SPDX-License-Identifier: MIT
    pragma solidity 0.8.6;
    import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
    import "@openzeppelin/contracts/access/Ownable.sol";
    import "@openzeppelin/contracts/security/Pausable.sol";
    import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
    import "@openzeppelin/contracts/utils/Strings.sol";
    import "./Bayc.sol";
    import "./Bacc.sol";
    //      |||||\\          |||||\\               |||||\\           |||||\\
    //      ||||| |         ||||| |              ||||| |          ||||| |
    //       \\__|||||\\  |||||\\___\\|               \\__|||||\\   |||||\\___\\|
    //          ||||| | ||||| |                      ||||| |  ||||| |
    //           \\__|||||\\___\\|       Y u g a         \\__|||||\\___\\|
    //              ||||| |             L a b s          ||||| |
    //          |||||\\___\\|                          |||||\\___\\|
    //          ||||| |                              ||||| |
    //           \\__|||||||||||\\                      \\__|||||||||||\\
    //              ||||||||||| |                        ||||||||||| |
    //               \\_________\\|                         \\_________\\|
    contract MutantApeYachtClub is ERC721Enumerable, Ownable, ReentrancyGuard {
        // Provenance hash for all mutants (Minted, Mutated Ape, MEGA)
        string public constant MAYC_PROVENANCE = "ca7151cc436da0dc3a3d662694f8c9da5ae39a7355fabaafc00e6aa580927175";
        
        // IDs 0 - 9999: Minted Mutants
        // IDs 10000 - 29999: Mutated Apes
        // IDs 30000 - 3007: MEGA Mutants
        uint8 private constant NUM_MUTANT_TYPES = 2;
        uint256 private constant MEGA_MUTATION_TYPE = 69;
        uint256 public constant NUM_MEGA_MUTANTS = 8;
        uint16 private constant MAX_MEGA_MUTATION_ID = 30007;
        uint256 public constant SERUM_MUTATION_OFFSET = 10000;
        uint256 public constant PS_MAX_MUTANT_PURCHASE = 20;
        // Max supply of Minted Mutants
        uint256 public constant PS_MAX_MUTANTS = 10000;
        // Public sale final price - 0.01 ETH
        uint256 public constant PS_MUTANT_ENDING_PRICE = 10000000000000000;
        // Public sale starting price - mutable, in case we need to pause
        // and restart the sale
        uint256 public publicSaleMutantStartingPrice;
        // Supply of Minted Mutants (not Mutated Apes)
        uint256 public numMutantsMinted;
        // Public sale params
        uint256 public publicSaleDuration;
        uint256 public publicSaleStartTime;
        // Sale switches
        bool public publicSaleActive;
        bool public serumMutationActive;
        // Starting index block for the entire collection
        uint256 public collectionStartingIndexBlock;
        // Starting index for Minted Mutants
        uint256 public mintedMutantsStartingIndex;
        // Starting index for MEGA Mutants
        uint256 public megaMutantsStartingIndex;
        uint16 private currentMegaMutationId = 30000;
        mapping(uint256 => uint256) private megaMutationIdsByApe;
        string private baseURI;
        Bayc private immutable bayc;
        Bacc private immutable bacc;
        event MutantPublicSaleStart(
            uint256 indexed _saleDuration,
            uint256 indexed _saleStartTime
        );
        event MutantPublicSalePaused(
            uint256 indexed _currentPrice,
            uint256 indexed _timeElapsed
        );
        event StartingIndicesSet(
            uint256 indexed _mintedMutantsStartingIndex,
            uint256 indexed _megaMutantsStartingIndex
        );
        modifier whenPublicSaleActive() {
            require(publicSaleActive, "Public sale is not active");
            _;
        }
        modifier startingIndicesNotSet() {
            require(
                mintedMutantsStartingIndex == 0,
                "Minted Mutants starting index is already set"
            );
            require(
                megaMutantsStartingIndex == 0,
                "Mega Mutants starting index is already set"
            );
            _;
        }
        constructor(
            string memory name,
            string memory symbol,
            address baycAddress,
            address baccAddress
        ) ERC721(name, symbol) {
            bayc = Bayc(baycAddress);
            bacc = Bacc(baccAddress);
        }
        function startPublicSale(uint256 saleDuration, uint256 saleStartPrice)
            external
            onlyOwner
        {
            require(!publicSaleActive, "Public sale has already begun");
            publicSaleDuration = saleDuration;
            publicSaleMutantStartingPrice = saleStartPrice;
            publicSaleStartTime = block.timestamp;
            publicSaleActive = true;
            emit MutantPublicSaleStart(saleDuration, publicSaleStartTime);
        }
        function pausePublicSale() external onlyOwner whenPublicSaleActive {
            uint256 currentSalePrice = getMintPrice();
            publicSaleActive = false;
            emit MutantPublicSalePaused(currentSalePrice, getElapsedSaleTime());
        }
        function getElapsedSaleTime() internal view returns (uint256) {
            return
                publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0;
        }
        function getRemainingSaleTime() external view returns (uint256) {
            require(publicSaleStartTime > 0, "Public sale hasn't started yet");
            if (getElapsedSaleTime() >= publicSaleDuration) {
                return 0;
            }
            return (publicSaleStartTime + publicSaleDuration) - block.timestamp;
        }
        function getMintPrice() public view whenPublicSaleActive returns (uint256) {
            uint256 elapsed = getElapsedSaleTime();
            if (elapsed >= publicSaleDuration) {
                return PS_MUTANT_ENDING_PRICE;
            } else {
                uint256 currentPrice = ((publicSaleDuration - elapsed) *
                    publicSaleMutantStartingPrice) / publicSaleDuration;
                return
                    currentPrice > PS_MUTANT_ENDING_PRICE
                        ? currentPrice
                        : PS_MUTANT_ENDING_PRICE;
            }
        }
        function withdraw() external onlyOwner {
            uint256 balance = address(this).balance;
            Address.sendValue(payable(owner()), balance);
        }
        function mintMutants(uint256 numMutants)
            external
            payable
            whenPublicSaleActive
            nonReentrant
        {
            require(
                numMutantsMinted + numMutants <= PS_MAX_MUTANTS,
                "Minting would exceed max supply"
            );
            require(numMutants > 0, "Must mint at least one mutant");
            require(
                numMutants <= PS_MAX_MUTANT_PURCHASE,
                "Requested number exceeds maximum"
            );
            uint256 costToMint = getMintPrice() * numMutants;
            require(costToMint <= msg.value, "Ether value sent is not correct");
            
            if (mintedMutantsStartingIndex == 0) {
                collectionStartingIndexBlock = block.number;
            }
            for (uint256 i = 0; i < numMutants; i++) {
                uint256 mintIndex = numMutantsMinted;
                if (numMutantsMinted < PS_MAX_MUTANTS) {
                    numMutantsMinted++;
                    _safeMint(msg.sender, mintIndex);
                }
            }
            if (msg.value > costToMint) {
                Address.sendValue(payable(msg.sender), msg.value - costToMint);
            }
        }
        
        function mutateApeWithSerum(uint256 serumTypeId, uint256 apeId)
            external
            nonReentrant
        {
            require(serumMutationActive, "Serum Mutation is not active");
            require(
                bayc.ownerOf(apeId) == msg.sender,
                "Must own the ape you're attempting to mutate"
            );
            require(
                bacc.balanceOf(msg.sender, serumTypeId) > 0,
                "Must own at least one of this serum type to mutate"
            );
            uint256 mutantId;
            if (serumTypeId == MEGA_MUTATION_TYPE) {
                require(
                    currentMegaMutationId <= MAX_MEGA_MUTATION_ID,
                    "Would exceed supply of serum-mutatable MEGA MUTANTS"
                );
                require(
                    megaMutationIdsByApe[apeId] == 0,
                    "Ape already mutated with MEGA MUTATION SERUM"
                );
                mutantId = currentMegaMutationId;
                megaMutationIdsByApe[apeId] = mutantId;
                currentMegaMutationId++;
            } else {
                mutantId = getMutantId(serumTypeId, apeId);
                require(
                    !_exists(mutantId),
                    "Ape already mutated with this type of serum"
                );
            }
            bacc.burnSerumForAddress(serumTypeId, msg.sender);
            _safeMint(msg.sender, mutantId);
        }
        function getMutantIdForApeAndSerumCombination(
            uint256 apeId,
            uint8 serumTypeId
        ) external view returns (uint256) {
            uint256 mutantId;
            if (serumTypeId == MEGA_MUTATION_TYPE) {
                mutantId = megaMutationIdsByApe[apeId];
                require(mutantId > 0, "Invalid MEGA Mutant Id");
            } else {
                mutantId = getMutantId(serumTypeId, apeId);
            }
            require(_exists(mutantId), "Query for nonexistent mutant");
            return mutantId;
        }
        function hasApeBeenMutatedWithType(uint8 serumType, uint256 apeId)
            external
            view
            returns (bool)
        {
            if (serumType == MEGA_MUTATION_TYPE) {
                return megaMutationIdsByApe[apeId] > 0;
            }
            uint256 mutantId = getMutantId(serumType, apeId);
            return _exists(mutantId);
        }
        function getMutantId(uint256 serumType, uint256 apeId)
            internal
            pure
            returns (uint256)
        {
            require(
                serumType != MEGA_MUTATION_TYPE,
                "Mega mutant ID can't be calculated"
            );
            return (apeId * NUM_MUTANT_TYPES) + serumType + SERUM_MUTATION_OFFSET;
        }
        function isMinted(uint256 tokenId) external view returns (bool) {
            require(
                tokenId < MAX_MEGA_MUTATION_ID,
                "tokenId outside collection bounds"
            );
            return _exists(tokenId);
        }
        function totalApesMutated() external view returns (uint256) {
            return totalSupply() - numMutantsMinted;
        }
        function _baseURI() internal view override returns (string memory) {
            return baseURI;
        }
        function setBaseURI(string memory uri) external onlyOwner {
            baseURI = uri;
        }
        function togglePublicSaleActive() external onlyOwner {
            publicSaleActive = !publicSaleActive;
        }
        function toggleSerumMutationActive() external onlyOwner {
            serumMutationActive = !serumMutationActive;
        }
        function calculateStartingIndex(uint256 blockNumber, uint256 collectionSize)
            internal
            view
            returns (uint256)
        {
            return uint256(blockhash(blockNumber)) % collectionSize;
        }
        
        function setStartingIndices() external startingIndicesNotSet {
            require(
                collectionStartingIndexBlock != 0,
                "Starting index block must be set"
            );
            uint256 elapsed = getElapsedSaleTime();
            require(
                elapsed >= publicSaleDuration && publicSaleStartTime > 0,
                "Invalid setStartingIndices conditions"
            );
            mintedMutantsStartingIndex = calculateStartingIndex(
                collectionStartingIndexBlock,
                PS_MAX_MUTANTS
            );
            megaMutantsStartingIndex = calculateStartingIndex(
                collectionStartingIndexBlock,
                NUM_MEGA_MUTANTS
            );
            
            if ((block.number - collectionStartingIndexBlock) > 255) {
                mintedMutantsStartingIndex = calculateStartingIndex(
                    block.number - 1,
                    PS_MAX_MUTANTS
                );
                megaMutantsStartingIndex = calculateStartingIndex(
                    block.number - 1,
                    NUM_MEGA_MUTANTS
                );
            }
            // Prevent default sequence
            if (mintedMutantsStartingIndex == 0) {
                mintedMutantsStartingIndex++;
            }
            if (megaMutantsStartingIndex == 0) {
                megaMutantsStartingIndex++;
            }
            emit StartingIndicesSet(
                mintedMutantsStartingIndex,
                megaMutantsStartingIndex
            );
        }
    }