ETH Price: $1,804.55 (-0.46%)

Transaction Decoder

Block:
17701183 at Jul-15-2023 08:37:47 PM +UTC
Transaction Fee:
0.000968016407381365 ETH $1.75
Gas Used:
84,263 Gas / 11.488036355 Gwei

Emitted Events:

375 SimpleToken.Transfer( from=[Receiver] ApeCoinStaking, to=[Sender] 0xca2d5af4869c3461ee9069ccc49df085a51e6950, value=326459931678603047388 )
376 ApeCoinStaking.ClaimRewardsNft( user=[Sender] 0xca2d5af4869c3461ee9069ccc49df085a51e6950, poolId=1, amount=326459931678603047388, tokenId=5153 )

Account State Difference:

  Address   Before After State Difference Code
0x4d224452...b5D594381
0x5954aB96...c8a2AFbb9
(Apecoin: Staking)
(builder0x69)
1.235846861107340824 Eth1.235855287407340824 Eth0.0000084263
0xCA2D5AF4...5A51e6950
0.097698533065461294 Eth
Nonce: 142
0.096730516658079929 Eth
Nonce: 143
0.000968016407381365

Execution Trace

ApeCoinStaking.claimSelfBAYC( _nfts=[5153] )
  • BoredApeYachtClub.ownerOf( tokenId=5153 ) => ( 0xCA2D5AF4869C3461ee9069CCC49df085A51e6950 )
  • SimpleToken.transfer( recipient=0xCA2D5AF4869C3461ee9069CCC49df085A51e6950, amount=326459931678603047388 ) => ( True )
    File 1 of 3: ApeCoinStaking
    //SPDX-License-Identifier: MIT
    /*
    ApeStake Smart Contract Disclaimer
    The ApeStake smart contract (the “Smart Contract”) was developed at the direction of the ApeCoin DAO community pursuant
    to a grant by the Ape Foundation.  The grant instructs the development of the Smart Contract and the developer’s user
    interface to enable a non-exclusive, user friendly means of access to the rewards program offered to the APE community
    by the Ape Foundation pursuant to the specifications set forth in AIPs 21/22. The Smart Contract is made up of free,
    public, open-source or source-available software deployed on the Ethereum Blockchain.
    Use Disclaimer.
    Your use of the Smart Contract involves various risks, including, but not limited to, losses while digital
    assets are being supplied and/or removed from the Smart Contract, losses due to the volatility of token price,
    risks in connection with your personal wallet access, system failures, opportunity loss while participating in the
    Smart Contract, loss of tokens in connection with non-fungible token transfers, risk of cyber attack and/or security
    breach, risk of legal uncertainty and/or changes in legal environment, and additional risks which may be based upon
    utilization of any third party other than the Smart Contract developer who provides you with access to the Smart
    Contract. Before using the Smart Contract, you should review the relevant documentation to make sure you understand
    how the Smart Contract works. Additionally, because you may be able to access the Smart Contract through other web or
    mobile interfaces than the Smart Contract developer’s user interface provided pursuant to the Ape Foundation grant,
    you are responsible for doing your own diligence on those interfaces to understand the fees and risks they present.
    THE SMART CONTRACT IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
    The developer was contracted by APE Foundation to develop the initial code to implement AIP 21/22.
    The developer does not own or control the staking rewards program, which is run on the Smart Contracts deployed on
    the Ethereum blockchain.  Upgrades and modifications will be managed in a community-driven way by holders of the APE
    governance token and may be undertaken and/or implemented with no involvement of the developer.
    No liability.
    No developer or entity involved in creating the Smart Contract or “platform as a service” will be liable for any
    claims or damages whatsoever associated with your use, inability to use, or your interaction with the Smart Contract
    or the developer’s user interface provided pursuant to the Ape Foundation grant, including any direct, indirect,
    incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens,
    or anything else of value.
    Access to Third Parties.
    Any party who uses or provides access to the Smart Contract to third parties must (a) not provide such access in
    violation of any applicable law or regulation, (b) inform such third parties of any and all risks, and (c) is solely
    responsible to such third parties for any and all liability, claims or damages relating to such party’s provision of
    access to the Smart Contract.
    */
    pragma solidity 0.8.10;
    import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
    import "@openzeppelin/contracts/utils/math/SafeCast.sol";
    import "@openzeppelin/contracts/access/Ownable.sol";
    import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
    /**
     * @title ApeCoin Staking Contract
     * @notice Stake ApeCoin across four different pools that release hourly rewards
     * @author HorizenLabs
     */
    contract ApeCoinStaking is Ownable {
        using SafeCast for uint256;
        using SafeCast for int256;
        /// @notice State for ApeCoin, BAYC, MAYC, and Pair Pools
        struct Pool {
            uint48 lastRewardedTimestampHour;
            uint16 lastRewardsRangeIndex;
            uint96 stakedAmount;
            uint96 accumulatedRewardsPerShare;
            TimeRange[] timeRanges;
        }
        /// @notice Pool rules valid for a given duration of time.
        /// @dev All TimeRange timestamp values must represent whole hours
        struct TimeRange {
            uint48 startTimestampHour;
            uint48 endTimestampHour;
            uint96 rewardsPerHour;
            uint96 capPerPosition;
        }
        /// @dev Convenience struct for front-end applications
        struct PoolUI {
            uint256 poolId;
            uint256 stakedAmount;
            TimeRange currentTimeRange;
        }
        /// @dev Per address amount and reward tracking
        struct Position {
            uint256 stakedAmount;
            int256 rewardsDebt;
        }
        mapping (address => Position) public addressPosition;
        /// @dev Struct for depositing and withdrawing from the BAYC and MAYC NFT pools
        struct SingleNft {
            uint32 tokenId;
            uint224 amount;
        }
        /// @dev Struct for depositing from the BAKC (Pair) pool
        struct PairNftDepositWithAmount {
            uint32 mainTokenId;
            uint32 bakcTokenId;
            uint184 amount;
        }
        /// @dev Struct for withdrawing from the BAKC (Pair) pool
        struct PairNftWithdrawWithAmount {
            uint32 mainTokenId;
            uint32 bakcTokenId;
            uint184 amount;
            bool isUncommit;
        }
        /// @dev Struct for claiming from an NFT pool
        struct PairNft {
            uint128 mainTokenId;
            uint128 bakcTokenId;
        }
        /// @dev NFT paired status.  Can be used bi-directionally (BAYC/MAYC -> BAKC) or (BAKC -> BAYC/MAYC)
        struct PairingStatus {
            uint248 tokenId;
            bool isPaired;
        }
        // @dev UI focused payload
        struct DashboardStake {
            uint256 poolId;
            uint256 tokenId;
            uint256 deposited;
            uint256 unclaimed;
            uint256 rewards24hr;
            DashboardPair pair;
        }
        /// @dev Sub struct for DashboardStake
        struct DashboardPair {
            uint256 mainTokenId;
            uint256 mainTypePoolId;
        }
        /// @dev Placeholder for pair status, used by ApeCoin Pool
        DashboardPair private NULL_PAIR = DashboardPair(0, 0);
        /// @notice Internal ApeCoin amount for distributing staking reward claims
        IERC20 public immutable apeCoin;
        uint256 private constant APE_COIN_PRECISION = 1e18;
        uint256 private constant MIN_DEPOSIT = 1 * APE_COIN_PRECISION;
        uint256 private constant SECONDS_PER_HOUR = 3600;
        uint256 private constant SECONDS_PER_MINUTE = 60;
        uint256 constant APECOIN_POOL_ID = 0;
        uint256 constant BAYC_POOL_ID = 1;
        uint256 constant MAYC_POOL_ID = 2;
        uint256 constant BAKC_POOL_ID = 3;
        Pool[4] public pools;
        /// @dev NFT contract mapping per pool
        mapping(uint256 => ERC721Enumerable) public nftContracts;
        /// @dev poolId => tokenId => nft position
        mapping(uint256 => mapping(uint256 => Position)) public nftPosition;
        /// @dev main type pool ID: 1: BAYC 2: MAYC => main token ID => bakc token ID
        mapping(uint256 => mapping(uint256 => PairingStatus)) public mainToBakc;
        /// @dev bakc Token ID => main type pool ID: 1: BAYC 2: MAYC => main token ID
        mapping(uint256 => mapping(uint256 => PairingStatus)) public bakcToMain;
        /** Custom Events */
        event UpdatePool(
            uint256 indexed poolId,
            uint256 lastRewardedBlock,
            uint256 stakedAmount,
            uint256 accumulatedRewardsPerShare
        );
        event Deposit(
            address indexed user,
            uint256 amount,
            address recipient
        );
        event DepositNft(
            address indexed user,
            uint256 indexed poolId,
            uint256 amount,
            uint256 tokenId
        );
        event DepositPairNft(
            address indexed user,
            uint256 amount,
            uint256 mainTypePoolId,
            uint256 mainTokenId,
            uint256 bakcTokenId
        );
        event Withdraw(
            address indexed user,
            uint256 amount,
            address recipient
        );
        event WithdrawNft(
            address indexed user,
            uint256 indexed poolId,
            uint256 amount,
            address recipient,
            uint256 tokenId
        );
        event WithdrawPairNft(
            address indexed user,
            uint256 amount,
            uint256 mainTypePoolId,
            uint256 mainTokenId,
            uint256 bakcTokenId
        );
        event ClaimRewards(
            address indexed user,
            uint256 amount,
            address recipient
        );
        event ClaimRewardsNft(
            address indexed user,
            uint256 indexed poolId,
            uint256 amount,
            uint256 tokenId
        );
        event ClaimRewardsPairNft(
            address indexed user,
            uint256 amount,
            uint256 mainTypePoolId,
            uint256 mainTokenId,
            uint256 bakcTokenId
        );
        error DepositMoreThanOneAPE();
        error InvalidPoolId();
        error StartMustBeGreaterThanEnd();
        error StartNotWholeHour();
        error EndNotWholeHour();
        error StartMustEqualLastEnd();
        error CallerNotOwner();
        error MainTokenNotOwnedOrPaired();
        error BAKCNotOwnedOrPaired();
        error BAKCAlreadyPaired();
        error ExceededCapAmount();
        error NotOwnerOfMain();
        error NotOwnerOfBAKC();
        error ProvidedTokensNotPaired();
        error ExceededStakedAmount();
        error NeitherTokenInPairOwnedByCaller();
        error SplitPairCantPartiallyWithdraw();
        error UncommitWrongParameters();
        /**
         * @notice Construct a new ApeCoinStaking instance
         * @param _apeCoinContractAddress The ApeCoin ERC20 contract address
         * @param _baycContractAddress The BAYC NFT contract address
         * @param _maycContractAddress The MAYC NFT contract address
         * @param _bakcContractAddress The BAKC NFT contract address
         */
        constructor(
            address _apeCoinContractAddress,
            address _baycContractAddress,
            address _maycContractAddress,
            address _bakcContractAddress
        ) {
            apeCoin = IERC20(_apeCoinContractAddress);
            nftContracts[BAYC_POOL_ID] = ERC721Enumerable(_baycContractAddress);
            nftContracts[MAYC_POOL_ID] = ERC721Enumerable(_maycContractAddress);
            nftContracts[BAKC_POOL_ID] = ERC721Enumerable(_bakcContractAddress);
        }
        // Deposit/Commit Methods
        /**
         * @notice Deposit ApeCoin to the ApeCoin Pool
         * @param _amount Amount in ApeCoin
         * @param _recipient Address the deposit it stored to
         * @dev ApeCoin deposit must be >= 1 ApeCoin
         */
        function depositApeCoin(uint256 _amount, address _recipient) public {
            if (_amount < MIN_DEPOSIT) revert DepositMoreThanOneAPE();
            updatePool(APECOIN_POOL_ID);
            Position storage position = addressPosition[_recipient];
            _deposit(APECOIN_POOL_ID, position, _amount);
            apeCoin.transferFrom(msg.sender, address(this), _amount);
            emit Deposit(msg.sender, _amount, _recipient);
        }
        /**
         * @notice Deposit ApeCoin to the ApeCoin Pool
         * @param _amount Amount in ApeCoin
         * @dev Deposit on behalf of msg.sender. ApeCoin deposit must be >= 1 ApeCoin
         */
        function depositSelfApeCoin(uint256 _amount) external {
            depositApeCoin(_amount, msg.sender);
        }
        /**
         * @notice Deposit ApeCoin to the BAYC Pool
         * @param _nfts Array of SingleNft structs
         * @dev Commits 1 or more BAYC NFTs, each with an ApeCoin amount to the BAYC pool.\\
         * Each BAYC committed must attach an ApeCoin amount >= 1 ApeCoin and <= the BAYC pool cap amount.
         */
        function depositBAYC(SingleNft[] calldata _nfts) external {
            _depositNft(BAYC_POOL_ID, _nfts);
        }
        /**
         * @notice Deposit ApeCoin to the MAYC Pool
         * @param _nfts Array of SingleNft structs
         * @dev Commits 1 or more MAYC NFTs, each with an ApeCoin amount to the MAYC pool.\\
         * Each MAYC committed must attach an ApeCoin amount >= 1 ApeCoin and <= the MAYC pool cap amount.
         */
        function depositMAYC(SingleNft[] calldata _nfts) external {
            _depositNft(MAYC_POOL_ID, _nfts);
        }
        /**
         * @notice Deposit ApeCoin to the Pair Pool, where Pair = (BAYC + BAKC) or (MAYC + BAKC)
         * @param _baycPairs Array of PairNftDepositWithAmount structs
         * @param _maycPairs Array of PairNftDepositWithAmount structs
         * @dev Commits 1 or more Pairs, each with an ApeCoin amount to the Pair pool.\\
         * Each BAKC committed must attach an ApeCoin amount >= 1 ApeCoin and <= the Pair pool cap amount.\\
         * Example 1: BAYC + BAKC + 1 ApeCoin:  [[0, 0, "1000000000000000000"],[]]\\
         * Example 2: MAYC + BAKC + 1 ApeCoin:  [[], [0, 0, "1000000000000000000"]]\\
         * Example 3: (BAYC + BAKC + 1 ApeCoin) and (MAYC + BAKC + 1 ApeCoin): [[0, 0, "1000000000000000000"], [0, 1, "1000000000000000000"]]
         */
        function depositBAKC(PairNftDepositWithAmount[] calldata _baycPairs, PairNftDepositWithAmount[] calldata _maycPairs) external {
            updatePool(BAKC_POOL_ID);
            _depositPairNft(BAYC_POOL_ID, _baycPairs);
            _depositPairNft(MAYC_POOL_ID, _maycPairs);
        }
        // Claim Rewards Methods
        /**
         * @notice Claim rewards for msg.sender and send to recipient
         * @param _recipient Address to send claim reward to
         */
        function claimApeCoin(address _recipient) public {
            updatePool(APECOIN_POOL_ID);
            Position storage position = addressPosition[msg.sender];
            uint256 rewardsToBeClaimed = _claim(APECOIN_POOL_ID, position, _recipient);
            emit ClaimRewards(msg.sender, rewardsToBeClaimed, _recipient);
        }
        /// @notice Claim and send rewards
        function claimSelfApeCoin() external {
            claimApeCoin(msg.sender);
        }
        /**
         * @notice Claim rewards for array of BAYC NFTs and send to recipient
         * @param _nfts Array of NFTs owned and committed by the msg.sender
         * @param _recipient Address to send claim reward to
         */
        function claimBAYC(uint256[] calldata _nfts, address _recipient) external {
            _claimNft(BAYC_POOL_ID, _nfts, _recipient);
        }
        /**
         * @notice Claim rewards for array of BAYC NFTs
         * @param _nfts Array of NFTs owned and committed by the msg.sender
         */
        function claimSelfBAYC(uint256[] calldata _nfts) external {
            _claimNft(BAYC_POOL_ID, _nfts, msg.sender);
        }
        /**
         * @notice Claim rewards for array of MAYC NFTs and send to recipient
         * @param _nfts Array of NFTs owned and committed by the msg.sender
         * @param _recipient Address to send claim reward to
         */
        function claimMAYC(uint256[] calldata _nfts, address _recipient) external {
            _claimNft(MAYC_POOL_ID, _nfts, _recipient);
        }
        /**
         * @notice Claim rewards for array of MAYC NFTs
         * @param _nfts Array of NFTs owned and committed by the msg.sender
         */
        function claimSelfMAYC(uint256[] calldata _nfts) external {
            _claimNft(MAYC_POOL_ID, _nfts, msg.sender);
        }
        /**
         * @notice Claim rewards for array of Paired NFTs and send to recipient
         * @param _baycPairs Array of Paired BAYC NFTs owned and committed by the msg.sender
         * @param _maycPairs Array of Paired MAYC NFTs owned and committed by the msg.sender
         * @param _recipient Address to send claim reward to
         */
        function claimBAKC(PairNft[] calldata _baycPairs, PairNft[] calldata _maycPairs, address _recipient) public {
            updatePool(BAKC_POOL_ID);
            _claimPairNft(BAYC_POOL_ID, _baycPairs, _recipient);
            _claimPairNft(MAYC_POOL_ID, _maycPairs, _recipient);
        }
        /**
         * @notice Claim rewards for array of Paired NFTs
         * @param _baycPairs Array of Paired BAYC NFTs owned and committed by the msg.sender
         * @param _maycPairs Array of Paired MAYC NFTs owned and committed by the msg.sender
         */
        function claimSelfBAKC(PairNft[] calldata _baycPairs, PairNft[] calldata _maycPairs) external {
            claimBAKC(_baycPairs, _maycPairs, msg.sender);
        }
        // Uncommit/Withdraw Methods
        /**
         * @notice Withdraw staked ApeCoin from the ApeCoin pool.  Performs an automatic claim as part of the withdraw process.
         * @param _amount Amount of ApeCoin
         * @param _recipient Address to send withdraw amount and claim to
         */
        function withdrawApeCoin(uint256 _amount, address _recipient) public {
            updatePool(APECOIN_POOL_ID);
            Position storage position = addressPosition[msg.sender];
            if (_amount == position.stakedAmount) {
                uint256 rewardsToBeClaimed = _claim(APECOIN_POOL_ID, position, _recipient);
                emit ClaimRewards(msg.sender, rewardsToBeClaimed, _recipient);
            }
            _withdraw(APECOIN_POOL_ID, position, _amount);
            apeCoin.transfer(_recipient, _amount);
            emit Withdraw(msg.sender, _amount, _recipient);
        }
        /**
         * @notice Withdraw staked ApeCoin from the ApeCoin pool.  If withdraw is total staked amount, performs an automatic claim.
         * @param _amount Amount of ApeCoin
         */
        function withdrawSelfApeCoin(uint256 _amount) external {
            withdrawApeCoin(_amount, msg.sender);
        }
        /**
         * @notice Withdraw staked ApeCoin from the BAYC pool.  If withdraw is total staked amount, performs an automatic claim.
         * @param _nfts Array of BAYC NFT's with staked amounts
         * @param _recipient Address to send withdraw amount and claim to
         */
        function withdrawBAYC(SingleNft[] calldata _nfts, address _recipient) external {
            _withdrawNft(BAYC_POOL_ID, _nfts, _recipient);
        }
        /**
         * @notice Withdraw staked ApeCoin from the BAYC pool.  If withdraw is total staked amount, performs an automatic claim.
         * @param _nfts Array of BAYC NFT's with staked amounts
         */
        function withdrawSelfBAYC(SingleNft[] calldata _nfts) external {
            _withdrawNft(BAYC_POOL_ID, _nfts, msg.sender);
        }
        /**
         * @notice Withdraw staked ApeCoin from the MAYC pool.  If withdraw is total staked amount, performs an automatic claim.
         * @param _nfts Array of MAYC NFT's with staked amounts
         * @param _recipient Address to send withdraw amount and claim to
         */
        function withdrawMAYC(SingleNft[] calldata _nfts, address _recipient) external {
            _withdrawNft(MAYC_POOL_ID, _nfts, _recipient);
        }
        /**
         * @notice Withdraw staked ApeCoin from the MAYC pool.  If withdraw is total staked amount, performs an automatic claim.
         * @param _nfts Array of MAYC NFT's with staked amounts
         */
        function withdrawSelfMAYC(SingleNft[] calldata _nfts) external {
            _withdrawNft(MAYC_POOL_ID, _nfts, msg.sender);
        }
        /**
         * @notice Withdraw staked ApeCoin from the Pair pool.  If withdraw is total staked amount, performs an automatic claim.
         * @param _baycPairs Array of Paired BAYC NFT's with staked amounts and isUncommit boolean
         * @param _maycPairs Array of Paired MAYC NFT's with staked amounts and isUncommit boolean
         * @dev if pairs have split ownership and BAKC is attempting a withdraw, the withdraw must be for the total staked amount
         */
        function withdrawBAKC(PairNftWithdrawWithAmount[] calldata _baycPairs, PairNftWithdrawWithAmount[] calldata _maycPairs) external {
            updatePool(BAKC_POOL_ID);
            _withdrawPairNft(BAYC_POOL_ID, _baycPairs);
            _withdrawPairNft(MAYC_POOL_ID, _maycPairs);
        }
        // Time Range Methods
        /**
         * @notice Add single time range with a given rewards per hour for a given pool
         * @dev In practice one Time Range will represent one quarter (defined by `_startTimestamp`and `_endTimeStamp` as whole hours)
         * where the rewards per hour is constant for a given pool.
         * @param _poolId Available pool values 0-3
         * @param _amount Total amount of ApeCoin to be distributed over the range
         * @param _startTimestamp Whole hour timestamp representation
         * @param _endTimeStamp Whole hour timestamp representation
         * @param _capPerPosition Per position cap amount determined by poolId
         */
        function addTimeRange(
            uint256 _poolId,
            uint256 _amount,
            uint256 _startTimestamp,
            uint256 _endTimeStamp,
            uint256 _capPerPosition) external onlyOwner
        {
            if (_poolId > BAKC_POOL_ID) revert InvalidPoolId();
            if (_startTimestamp >= _endTimeStamp) revert StartMustBeGreaterThanEnd();
            if (getMinute(_startTimestamp) > 0 || getSecond(_startTimestamp) > 0) revert StartNotWholeHour();
            if (getMinute(_endTimeStamp) > 0 || getSecond(_endTimeStamp) > 0) revert EndNotWholeHour();
            Pool storage pool = pools[_poolId];
            uint256 length = pool.timeRanges.length;
            if (length > 0) {
                if (_startTimestamp != pool.timeRanges[length - 1].endTimestampHour) revert StartMustEqualLastEnd();
            }
            uint256 hoursInSeconds = _endTimeStamp - _startTimestamp;
            uint256 rewardsPerHour = _amount * SECONDS_PER_HOUR / hoursInSeconds;
            TimeRange memory next = TimeRange(_startTimestamp.toUint48(), _endTimeStamp.toUint48(),
                rewardsPerHour.toUint96(), _capPerPosition.toUint96());
            pool.timeRanges.push(next);
        }
        /**
         * @notice Removes the last Time Range for a given pool.
         * @param _poolId Available pool values 0-3
         */
        function removeLastTimeRange(uint256 _poolId) external onlyOwner {
            pools[_poolId].timeRanges.pop();
        }
        /**
         * @notice Lookup method for a TimeRange struct
         * @return TimeRange A Pool's timeRanges struct by index.
         * @param _poolId Available pool values 0-3
         * @param _index Target index in a Pool's timeRanges array
         */
        function getTimeRangeBy(uint256 _poolId, uint256 _index) public view returns (TimeRange memory) {
            return pools[_poolId].timeRanges[_index];
        }
        // Pool Methods
        /**
         * @notice Lookup available rewards for a pool over a given time range
         * @return uint256 The amount of ApeCoin rewards to be distributed by pool for a given time range
         * @return uint256 The amount of time ranges
         * @param _poolId Available pool values 0-3
         * @param _from Whole hour timestamp representation
         * @param _to Whole hour timestamp representation
         */
        function rewardsBy(uint256 _poolId, uint256 _from, uint256 _to) public view returns (uint256, uint256) {
            Pool memory pool = pools[_poolId];
            uint256 currentIndex = pool.lastRewardsRangeIndex;
            if(_to < pool.timeRanges[0].startTimestampHour) return (0, currentIndex);
            while(_from > pool.timeRanges[currentIndex].endTimestampHour && _to > pool.timeRanges[currentIndex].endTimestampHour) {
                unchecked {
                    ++currentIndex;
                }
            }
            uint256 rewards;
            TimeRange memory current;
            uint256 startTimestampHour;
            uint256 endTimestampHour;
            uint256 length = pool.timeRanges.length;
            for(uint256 i = currentIndex; i < length;) {
                current = pool.timeRanges[i];
                startTimestampHour = _from <= current.startTimestampHour ? current.startTimestampHour : _from;
                endTimestampHour = _to <= current.endTimestampHour ? _to : current.endTimestampHour;
                rewards = rewards + (endTimestampHour - startTimestampHour) * current.rewardsPerHour / SECONDS_PER_HOUR;
                if(_to <= endTimestampHour) {
                    return (rewards, i);
                }
                unchecked {
                    ++i;
                }
            }
            return (rewards, length - 1);
        }
        /**
         * @notice Updates reward variables `lastRewardedTimestampHour`, `accumulatedRewardsPerShare` and `lastRewardsRangeIndex`
         * for a given pool.
         * @param _poolId Available pool values 0-3
         */
        function updatePool(uint256 _poolId) public {
            Pool storage pool = pools[_poolId];
            if (block.timestamp < pool.timeRanges[0].startTimestampHour) return;
            if (block.timestamp <= pool.lastRewardedTimestampHour + SECONDS_PER_HOUR) return;
            uint48 lastTimestampHour = pool.timeRanges[pool.timeRanges.length-1].endTimestampHour;
            uint48 previousTimestampHour = getPreviousTimestampHour().toUint48();
            if (pool.stakedAmount == 0) {
                pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour;
                return;
            }
            (uint256 rewards, uint256 index) = rewardsBy(_poolId, pool.lastRewardedTimestampHour, previousTimestampHour);
            if (pool.lastRewardsRangeIndex != index) {
                pool.lastRewardsRangeIndex = index.toUint16();
            }
            pool.accumulatedRewardsPerShare = (pool.accumulatedRewardsPerShare + (rewards * APE_COIN_PRECISION) / pool.stakedAmount).toUint96();
            pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour;
            emit UpdatePool(_poolId, pool.lastRewardedTimestampHour, pool.stakedAmount, pool.accumulatedRewardsPerShare);
        }
        // Read Methods
        function getCurrentTimeRangeIndex(Pool memory pool) private view returns (uint256) {
            uint256 current = pool.lastRewardsRangeIndex;
            if (block.timestamp < pool.timeRanges[current].startTimestampHour) return current;
            for(current = pool.lastRewardsRangeIndex; current < pool.timeRanges.length; ++current) {
                TimeRange memory currentTimeRange = pool.timeRanges[current];
                if (currentTimeRange.startTimestampHour <= block.timestamp && block.timestamp <= currentTimeRange.endTimestampHour) return current;
            }
            revert("distribution ended");
        }
        /**
         * @notice Fetches a PoolUI struct (poolId, stakedAmount, currentTimeRange) for each reward pool
         * @return PoolUI for ApeCoin.
         * @return PoolUI for BAYC.
         * @return PoolUI for MAYC.
         * @return PoolUI for BAKC.
         */
        function getPoolsUI() public view returns (PoolUI memory, PoolUI memory, PoolUI memory, PoolUI memory) {
            Pool memory apeCoinPool = pools[0];
            Pool memory baycPool = pools[1];
            Pool memory maycPool = pools[2];
            Pool memory bakcPool = pools[3];
            uint256 current = getCurrentTimeRangeIndex(apeCoinPool);
            return (PoolUI(0,apeCoinPool.stakedAmount, apeCoinPool.timeRanges[current]),
                    PoolUI(1,baycPool.stakedAmount, baycPool.timeRanges[current]),
                    PoolUI(2,maycPool.stakedAmount, maycPool.timeRanges[current]),
                    PoolUI(3,bakcPool.stakedAmount, bakcPool.timeRanges[current]));
        }
        /**
         * @notice Fetches an address total staked amount, used by voting contract
         * @return amount uint256 staked amount for all pools.
         * @param _address An Ethereum address
         */
        function stakedTotal(address _address) external view returns (uint256) {
            uint256 total = addressPosition[_address].stakedAmount;
            total += _stakedTotal(BAYC_POOL_ID, _address);
            total += _stakedTotal(MAYC_POOL_ID, _address);
            total += _stakedTotalPair(_address);
            return total;
        }
        function _stakedTotal(uint256 _poolId, address _addr) private view returns (uint256) {
            uint256 total = 0;
            uint256 nftCount = nftContracts[_poolId].balanceOf(_addr);
            for(uint256 i = 0; i < nftCount; ++i) {
                uint256 tokenId = nftContracts[_poolId].tokenOfOwnerByIndex(_addr, i);
                total += nftPosition[_poolId][tokenId].stakedAmount;
            }
            return total;
        }
        function _stakedTotalPair(address _addr) private view returns (uint256) {
            uint256 total = 0;
            uint256 nftCount = nftContracts[BAYC_POOL_ID].balanceOf(_addr);
            for(uint256 i = 0; i < nftCount; ++i) {
                uint256 baycTokenId = nftContracts[BAYC_POOL_ID].tokenOfOwnerByIndex(_addr, i);
                if (mainToBakc[BAYC_POOL_ID][baycTokenId].isPaired) {
                    uint256 bakcTokenId = mainToBakc[BAYC_POOL_ID][baycTokenId].tokenId;
                    total += nftPosition[BAKC_POOL_ID][bakcTokenId].stakedAmount;
                }
            }
            nftCount = nftContracts[MAYC_POOL_ID].balanceOf(_addr);
            for(uint256 i = 0; i < nftCount; ++i) {
                uint256 maycTokenId = nftContracts[MAYC_POOL_ID].tokenOfOwnerByIndex(_addr, i);
                if (mainToBakc[MAYC_POOL_ID][maycTokenId].isPaired) {
                    uint256 bakcTokenId = mainToBakc[MAYC_POOL_ID][maycTokenId].tokenId;
                    total += nftPosition[BAKC_POOL_ID][bakcTokenId].stakedAmount;
                }
            }
            return total;
        }
        /**
         * @notice Fetches a DashboardStake = [poolId, tokenId, deposited, unclaimed, rewards24Hrs, paired] \\
         * for each pool, for an Ethereum address
         * @return dashboardStakes An array of DashboardStake structs
         * @param _address An Ethereum address
         */
        function getAllStakes(address _address) public view returns (DashboardStake[] memory) {
            DashboardStake memory apeCoinStake = getApeCoinStake(_address);
            DashboardStake[] memory baycStakes = getBaycStakes(_address);
            DashboardStake[] memory maycStakes = getMaycStakes(_address);
            DashboardStake[] memory bakcStakes = getBakcStakes(_address);
            DashboardStake[] memory splitStakes = getSplitStakes(_address);
            uint256 count = (baycStakes.length + maycStakes.length + bakcStakes.length + splitStakes.length + 1);
            DashboardStake[] memory allStakes = new DashboardStake[](count);
            uint256 offset = 0;
            allStakes[offset] = apeCoinStake;
            ++offset;
            for(uint256 i = 0; i < baycStakes.length; ++i) {
                allStakes[offset] = baycStakes[i];
                ++offset;
            }
            for(uint256 i = 0; i < maycStakes.length; ++i) {
                allStakes[offset] = maycStakes[i];
                ++offset;
            }
            for(uint256 i = 0; i < bakcStakes.length; ++i) {
                allStakes[offset] = bakcStakes[i];
                ++offset;
            }
            for(uint256 i = 0; i < splitStakes.length; ++i) {
                allStakes[offset] = splitStakes[i];
                ++offset;
            }
            return allStakes;
        }
        /**
         * @notice Fetches a DashboardStake for the ApeCoin pool
         * @return dashboardStake A dashboardStake struct
         * @param _address An Ethereum address
         */
        function getApeCoinStake(address _address) public view returns (DashboardStake memory) {
            uint256 tokenId = 0;
            uint256 deposited = addressPosition[_address].stakedAmount;
            uint256 unclaimed = deposited > 0 ? this.pendingRewards(0, _address, tokenId) : 0;
            uint256 rewards24Hrs = deposited > 0 ? _estimate24HourRewards(0, _address, 0) : 0;
            return DashboardStake(APECOIN_POOL_ID, tokenId, deposited, unclaimed, rewards24Hrs, NULL_PAIR);
        }
        /**
         * @notice Fetches an array of DashboardStakes for the BAYC pool
         * @return dashboardStakes An array of DashboardStake structs
         */
        function getBaycStakes(address _address) public view returns (DashboardStake[] memory) {
            return _getStakes(_address, BAYC_POOL_ID);
        }
        /**
         * @notice Fetches an array of DashboardStakes for the MAYC pool
         * @return dashboardStakes An array of DashboardStake structs
         */
        function getMaycStakes(address _address) public view returns (DashboardStake[] memory) {
            return _getStakes(_address, MAYC_POOL_ID);
        }
        /**
         * @notice Fetches an array of DashboardStakes for the BAKC pool
         * @return dashboardStakes An array of DashboardStake structs
         */
        function getBakcStakes(address _address) public view returns (DashboardStake[] memory) {
            return _getStakes(_address, BAKC_POOL_ID);
        }
        /**
         * @notice Fetches an array of DashboardStakes for the Pair Pool when ownership is split \\
         * ie (BAYC/MAYC) and BAKC in pair pool have different owners.
         * @return dashboardStakes An array of DashboardStake structs
         * @param _address An Ethereum address
         */
        function getSplitStakes(address _address) public view returns (DashboardStake[] memory) {
            uint256 baycSplits = _getSplitStakeCount(nftContracts[BAYC_POOL_ID].balanceOf(_address), _address, BAYC_POOL_ID);
            uint256 maycSplits = _getSplitStakeCount(nftContracts[MAYC_POOL_ID].balanceOf(_address), _address, MAYC_POOL_ID);
            uint256 totalSplits = baycSplits + maycSplits;
            if(totalSplits == 0) {
                return new DashboardStake[](0);
            }
            DashboardStake[] memory baycSplitStakes = _getSplitStakes(baycSplits, _address, BAYC_POOL_ID);
            DashboardStake[] memory maycSplitStakes = _getSplitStakes(maycSplits, _address, MAYC_POOL_ID);
            DashboardStake[] memory splitStakes = new DashboardStake[](totalSplits);
            uint256 offset = 0;
            for(uint256 i = 0; i < baycSplitStakes.length; ++i) {
                splitStakes[offset] = baycSplitStakes[i];
                ++offset;
            }
            for(uint256 i = 0; i < maycSplitStakes.length; ++i) {
                splitStakes[offset] = maycSplitStakes[i];
                ++offset;
            }
            return splitStakes;
        }
        function _getSplitStakes(uint256 splits, address _address, uint256 _mainPoolId) private view returns (DashboardStake[] memory) {
            DashboardStake[] memory dashboardStakes = new DashboardStake[](splits);
            uint256 counter;
            for(uint256 i = 0; i < nftContracts[_mainPoolId].balanceOf(_address); ++i) {
                uint256 mainTokenId = nftContracts[_mainPoolId].tokenOfOwnerByIndex(_address, i);
                if(mainToBakc[_mainPoolId][mainTokenId].isPaired) {
                    uint256 bakcTokenId = mainToBakc[_mainPoolId][mainTokenId].tokenId;
                    address currentOwner = nftContracts[BAKC_POOL_ID].ownerOf(bakcTokenId);
                    /* Split Pair Check*/
                    if (currentOwner != _address) {
                        uint256 deposited = nftPosition[BAKC_POOL_ID][bakcTokenId].stakedAmount;
                        uint256 unclaimed = deposited > 0 ? this.pendingRewards(BAKC_POOL_ID, currentOwner, bakcTokenId) : 0;
                        uint256 rewards24Hrs = deposited > 0 ? _estimate24HourRewards(BAKC_POOL_ID, currentOwner, bakcTokenId): 0;
                        DashboardPair memory pair = NULL_PAIR;
                        if(bakcToMain[bakcTokenId][_mainPoolId].isPaired) {
                            pair = DashboardPair(bakcToMain[bakcTokenId][_mainPoolId].tokenId, _mainPoolId);
                        }
                        DashboardStake memory dashboardStake = DashboardStake(BAKC_POOL_ID, bakcTokenId, deposited, unclaimed, rewards24Hrs, pair);
                        dashboardStakes[counter] = dashboardStake;
                        ++counter;
                    }
                }
            }
            return dashboardStakes;
        }
        function _getSplitStakeCount(uint256 nftCount, address _address, uint256 _mainPoolId) private view returns (uint256) {
            uint256 splitCount;
            for(uint256 i = 0; i < nftCount; ++i) {
                uint256 mainTokenId = nftContracts[_mainPoolId].tokenOfOwnerByIndex(_address, i);
                if(mainToBakc[_mainPoolId][mainTokenId].isPaired) {
                    uint256 bakcTokenId = mainToBakc[_mainPoolId][mainTokenId].tokenId;
                    address currentOwner = nftContracts[BAKC_POOL_ID].ownerOf(bakcTokenId);
                    if (currentOwner != _address) {
                        ++splitCount;
                    }
                }
            }
            return splitCount;
        }
        function _getStakes(address _address, uint256 _poolId) private view returns (DashboardStake[] memory) {
            uint256 nftCount = nftContracts[_poolId].balanceOf(_address);
            DashboardStake[] memory dashboardStakes = nftCount > 0 ? new DashboardStake[](nftCount) : new DashboardStake[](0);
            if(nftCount == 0) {
                return dashboardStakes;
            }
            for(uint256 i = 0; i < nftCount; ++i) {
                uint256 tokenId = nftContracts[_poolId].tokenOfOwnerByIndex(_address, i);
                uint256 deposited = nftPosition[_poolId][tokenId].stakedAmount;
                uint256 unclaimed = deposited > 0 ? this.pendingRewards(_poolId, _address, tokenId) : 0;
                uint256 rewards24Hrs = deposited > 0 ? _estimate24HourRewards(_poolId, _address, tokenId): 0;
                DashboardPair memory pair = NULL_PAIR;
                if(_poolId == BAKC_POOL_ID) {
                    if(bakcToMain[tokenId][BAYC_POOL_ID].isPaired) {
                        pair = DashboardPair(bakcToMain[tokenId][BAYC_POOL_ID].tokenId, BAYC_POOL_ID);
                    } else if(bakcToMain[tokenId][MAYC_POOL_ID].isPaired) {
                        pair = DashboardPair(bakcToMain[tokenId][MAYC_POOL_ID].tokenId, MAYC_POOL_ID);
                    }
                }
                DashboardStake memory dashboardStake = DashboardStake(_poolId, tokenId, deposited, unclaimed, rewards24Hrs, pair);
                dashboardStakes[i] = dashboardStake;
            }
            return dashboardStakes;
        }
        function _estimate24HourRewards(uint256 _poolId, address _address, uint256 _tokenId) private view returns (uint256) {
            Pool memory pool = pools[_poolId];
            Position memory position = _poolId == 0 ? addressPosition[_address]: nftPosition[_poolId][_tokenId];
            TimeRange memory rewards = getTimeRangeBy(_poolId, pool.lastRewardsRangeIndex);
            return (position.stakedAmount * uint256(rewards.rewardsPerHour) * 24) / uint256(pool.stakedAmount);
        }
        /**
         * @notice Fetches the current amount of claimable ApeCoin rewards for a given position from a given pool.
         * @return uint256 value of pending rewards
         * @param _poolId Available pool values 0-3
         * @param _address Address to lookup Position for
         * @param _tokenId An NFT id
         */
        function pendingRewards(uint256 _poolId, address _address, uint256 _tokenId) external view returns (uint256) {
            Pool memory pool = pools[_poolId];
            Position memory position = _poolId == 0 ? addressPosition[_address]: nftPosition[_poolId][_tokenId];
            (uint256 rewardsSinceLastCalculated,) = rewardsBy(_poolId, pool.lastRewardedTimestampHour, getPreviousTimestampHour());
            uint256 accumulatedRewardsPerShare = pool.accumulatedRewardsPerShare;
            if (block.timestamp > pool.lastRewardedTimestampHour + SECONDS_PER_HOUR && pool.stakedAmount != 0) {
                accumulatedRewardsPerShare = accumulatedRewardsPerShare + rewardsSinceLastCalculated * APE_COIN_PRECISION / pool.stakedAmount;
            }
            return ((position.stakedAmount * accumulatedRewardsPerShare).toInt256() - position.rewardsDebt).toUint256() / APE_COIN_PRECISION;
        }
        // Convenience methods for timestamp calculation
        /// @notice the minutes (0 to 59) of a timestamp
        function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {
            uint256 secs = timestamp % SECONDS_PER_HOUR;
            minute = secs / SECONDS_PER_MINUTE;
        }
        /// @notice the seconds (0 to 59) of a timestamp
        function getSecond(uint256 timestamp) internal pure returns (uint256 second) {
            second = timestamp % SECONDS_PER_MINUTE;
        }
        /// @notice the previous whole hour of a timestamp
        function getPreviousTimestampHour() internal view returns (uint256) {
            return block.timestamp - (getMinute(block.timestamp) * 60 + getSecond(block.timestamp));
        }
        // Private Methods - shared logic
        function _deposit(uint256 _poolId, Position storage _position, uint256 _amount) private {
            Pool storage pool = pools[_poolId];
            _position.stakedAmount += _amount;
            pool.stakedAmount += _amount.toUint96();
            _position.rewardsDebt += (_amount * pool.accumulatedRewardsPerShare).toInt256();
        }
        function _depositNft(uint256 _poolId, SingleNft[] calldata _nfts) private {
            updatePool(_poolId);
            uint256 tokenId;
            uint256 amount;
            Position storage position;
            uint256 length = _nfts.length;
            uint256 totalDeposit;
            for(uint256 i; i < length;) {
                tokenId = _nfts[i].tokenId;
                position = nftPosition[_poolId][tokenId];
                if (position.stakedAmount == 0) {
                    if (nftContracts[_poolId].ownerOf(tokenId) != msg.sender) revert CallerNotOwner();
                }
                amount = _nfts[i].amount;
                _depositNftGuard(_poolId, position, amount);
                totalDeposit += amount;
                emit DepositNft(msg.sender, _poolId, amount, tokenId);
                unchecked {
                    ++i;
                }
            }
            if (totalDeposit > 0) apeCoin.transferFrom(msg.sender, address(this), totalDeposit);
        }
        function _depositPairNft(uint256 mainTypePoolId, PairNftDepositWithAmount[] calldata _nfts) private {
            uint256 length = _nfts.length;
            uint256 totalDeposit;
            PairNftDepositWithAmount memory pair;
            Position storage position;
            for(uint256 i; i < length;) {
                pair = _nfts[i];
                position = nftPosition[BAKC_POOL_ID][pair.bakcTokenId];
                if(position.stakedAmount == 0) {
                    if (nftContracts[mainTypePoolId].ownerOf(pair.mainTokenId) != msg.sender
                        || mainToBakc[mainTypePoolId][pair.mainTokenId].isPaired) revert MainTokenNotOwnedOrPaired();
                    if (nftContracts[BAKC_POOL_ID].ownerOf(pair.bakcTokenId) != msg.sender
                        || bakcToMain[pair.bakcTokenId][mainTypePoolId].isPaired) revert BAKCNotOwnedOrPaired();
                    mainToBakc[mainTypePoolId][pair.mainTokenId] = PairingStatus(pair.bakcTokenId, true);
                    bakcToMain[pair.bakcTokenId][mainTypePoolId] = PairingStatus(pair.mainTokenId, true);
                } else if (pair.mainTokenId != bakcToMain[pair.bakcTokenId][mainTypePoolId].tokenId
                    || pair.bakcTokenId != mainToBakc[mainTypePoolId][pair.mainTokenId].tokenId)
                        revert BAKCAlreadyPaired();
                _depositNftGuard(BAKC_POOL_ID, position, pair.amount);
                totalDeposit += pair.amount;
                emit DepositPairNft(msg.sender, pair.amount, mainTypePoolId, pair.mainTokenId, pair.bakcTokenId);
                unchecked {
                    ++i;
                }
            }
            if (totalDeposit > 0) apeCoin.transferFrom(msg.sender, address(this), totalDeposit);
        }
        function _depositNftGuard(uint256 _poolId, Position storage _position, uint256 _amount) private {
            if (_amount < MIN_DEPOSIT) revert DepositMoreThanOneAPE();
            if (_amount + _position.stakedAmount > pools[_poolId].timeRanges[pools[_poolId].lastRewardsRangeIndex].capPerPosition)
                revert ExceededCapAmount();
            _deposit(_poolId, _position, _amount);
        }
        function _claim(uint256 _poolId, Position storage _position, address _recipient) private returns (uint256 rewardsToBeClaimed) {
            Pool storage pool = pools[_poolId];
            int256 accumulatedApeCoins = (_position.stakedAmount * uint256(pool.accumulatedRewardsPerShare)).toInt256();
            rewardsToBeClaimed = (accumulatedApeCoins - _position.rewardsDebt).toUint256() / APE_COIN_PRECISION;
            _position.rewardsDebt = accumulatedApeCoins;
            if (rewardsToBeClaimed != 0) {
                apeCoin.transfer(_recipient, rewardsToBeClaimed);
            }
        }
        function _claimNft(uint256 _poolId, uint256[] calldata _nfts, address _recipient) private {
            updatePool(_poolId);
            uint256 tokenId;
            uint256 rewardsToBeClaimed;
            uint256 length = _nfts.length;
            for(uint256 i; i < length;) {
                tokenId = _nfts[i];
                if (nftContracts[_poolId].ownerOf(tokenId) != msg.sender) revert CallerNotOwner();
                Position storage position = nftPosition[_poolId][tokenId];
                rewardsToBeClaimed = _claim(_poolId, position, _recipient);
                emit ClaimRewardsNft(msg.sender, _poolId, rewardsToBeClaimed, tokenId);
                unchecked {
                    ++i;
                }
            }
        }
        function _claimPairNft(uint256 mainTypePoolId, PairNft[] calldata _pairs, address _recipient) private {
            uint256 length = _pairs.length;
            uint256 mainTokenId;
            uint256 bakcTokenId;
            Position storage position;
            PairingStatus storage mainToSecond;
            PairingStatus storage secondToMain;
            for(uint256 i; i < length;) {
                mainTokenId = _pairs[i].mainTokenId;
                if (nftContracts[mainTypePoolId].ownerOf(mainTokenId) != msg.sender) revert NotOwnerOfMain();
                bakcTokenId = _pairs[i].bakcTokenId;
                if (nftContracts[BAKC_POOL_ID].ownerOf(bakcTokenId) != msg.sender) revert NotOwnerOfBAKC();
                mainToSecond = mainToBakc[mainTypePoolId][mainTokenId];
                secondToMain = bakcToMain[bakcTokenId][mainTypePoolId];
                if (mainToSecond.tokenId != bakcTokenId || !mainToSecond.isPaired
                    || secondToMain.tokenId != mainTokenId || !secondToMain.isPaired) revert ProvidedTokensNotPaired();
                position = nftPosition[BAKC_POOL_ID][bakcTokenId];
                uint256 rewardsToBeClaimed = _claim(BAKC_POOL_ID, position, _recipient);
                emit ClaimRewardsPairNft(msg.sender, rewardsToBeClaimed, mainTypePoolId, mainTokenId, bakcTokenId);
                unchecked {
                    ++i;
                }
            }
        }
        function _withdraw(uint256 _poolId, Position storage _position, uint256 _amount) private {
            if (_amount > _position.stakedAmount) revert ExceededStakedAmount();
            Pool storage pool = pools[_poolId];
            _position.stakedAmount -= _amount;
            pool.stakedAmount -= _amount.toUint96();
            _position.rewardsDebt -= (_amount * pool.accumulatedRewardsPerShare).toInt256();
        }
        function _withdrawNft(uint256 _poolId, SingleNft[] calldata _nfts, address _recipient) private {
            updatePool(_poolId);
            uint256 tokenId;
            uint256 amount;
            uint256 length = _nfts.length;
            uint256 totalWithdraw;
            Position storage position;
            for(uint256 i; i < length;) {
                tokenId = _nfts[i].tokenId;
                if (nftContracts[_poolId].ownerOf(tokenId) != msg.sender) revert CallerNotOwner();
                amount = _nfts[i].amount;
                position = nftPosition[_poolId][tokenId];
                if (amount == position.stakedAmount) {
                    uint256 rewardsToBeClaimed = _claim(_poolId, position, _recipient);
                    emit ClaimRewardsNft(msg.sender, _poolId, rewardsToBeClaimed, tokenId);
                }
                _withdraw(_poolId, position, amount);
                totalWithdraw += amount;
                emit WithdrawNft(msg.sender, _poolId, amount, _recipient, tokenId);
                unchecked {
                    ++i;
                }
            }
            if (totalWithdraw > 0) apeCoin.transfer(_recipient, totalWithdraw);
        }
        function _withdrawPairNft(uint256 mainTypePoolId, PairNftWithdrawWithAmount[] calldata _nfts) private {
            address mainTokenOwner;
            address bakcOwner;
            PairNftWithdrawWithAmount memory pair;
            PairingStatus storage mainToSecond;
            PairingStatus storage secondToMain;
            Position storage position;
            uint256 length = _nfts.length;
            for(uint256 i; i < length;) {
                pair = _nfts[i];
                mainTokenOwner = nftContracts[mainTypePoolId].ownerOf(pair.mainTokenId);
                bakcOwner = nftContracts[BAKC_POOL_ID].ownerOf(pair.bakcTokenId);
                if (mainTokenOwner != msg.sender) {
                    if (bakcOwner != msg.sender) revert NeitherTokenInPairOwnedByCaller();
                }
                mainToSecond = mainToBakc[mainTypePoolId][pair.mainTokenId];
                secondToMain = bakcToMain[pair.bakcTokenId][mainTypePoolId];
                if (mainToSecond.tokenId != pair.bakcTokenId || !mainToSecond.isPaired
                    || secondToMain.tokenId != pair.mainTokenId || !secondToMain.isPaired) revert ProvidedTokensNotPaired();
                position = nftPosition[BAKC_POOL_ID][pair.bakcTokenId];
                if(!pair.isUncommit) {
                    if(pair.amount == position.stakedAmount) revert UncommitWrongParameters();
                }
                if (mainTokenOwner != bakcOwner) {
                    if (!pair.isUncommit) revert SplitPairCantPartiallyWithdraw();
                }
                if (pair.isUncommit) {
                    uint256 rewardsToBeClaimed = _claim(BAKC_POOL_ID, position, bakcOwner);
                    mainToBakc[mainTypePoolId][pair.mainTokenId] = PairingStatus(0, false);
                    bakcToMain[pair.bakcTokenId][mainTypePoolId] = PairingStatus(0, false);
                    emit ClaimRewardsPairNft(msg.sender, rewardsToBeClaimed, mainTypePoolId, pair.mainTokenId, pair.bakcTokenId);
                }
                uint256 finalAmountToWithdraw = pair.isUncommit ? position.stakedAmount: pair.amount;
                _withdraw(BAKC_POOL_ID, position, finalAmountToWithdraw);
                apeCoin.transfer(mainTokenOwner, finalAmountToWithdraw);
                emit WithdrawPairNft(msg.sender, finalAmountToWithdraw, mainTypePoolId, pair.mainTokenId, pair.bakcTokenId);
                unchecked {
                    ++i;
                }
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Interface of the ERC20 standard as defined in the EIP.
     */
    interface IERC20 {
        /**
         * @dev Emitted when `value` tokens are moved from one account (`from`) to
         * another (`to`).
         *
         * Note that `value` may be zero.
         */
        event Transfer(address indexed from, address indexed to, uint256 value);
        /**
         * @dev Emitted when the allowance of a `spender` for an `owner` is set by
         * a call to {approve}. `value` is the new allowance.
         */
        event Approval(address indexed owner, address indexed spender, uint256 value);
        /**
         * @dev Returns the amount of tokens in existence.
         */
        function totalSupply() external view returns (uint256);
        /**
         * @dev Returns the amount of tokens owned by `account`.
         */
        function balanceOf(address account) external view returns (uint256);
        /**
         * @dev Moves `amount` tokens from the caller's account to `to`.
         *
         * Returns a boolean value indicating whether the operation succeeded.
         *
         * Emits a {Transfer} event.
         */
        function transfer(address to, uint256 amount) external returns (bool);
        /**
         * @dev Returns the remaining number of tokens that `spender` will be
         * allowed to spend on behalf of `owner` through {transferFrom}. This is
         * zero by default.
         *
         * This value changes when {approve} or {transferFrom} are called.
         */
        function allowance(address owner, address spender) external view returns (uint256);
        /**
         * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
         *
         * Returns a boolean value indicating whether the operation succeeded.
         *
         * IMPORTANT: Beware that changing an allowance with this method brings the risk
         * that someone may use both the old and the new allowance by unfortunate
         * transaction ordering. One possible solution to mitigate this race
         * condition is to first reduce the spender's allowance to 0 and set the
         * desired value afterwards:
         * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
         *
         * Emits an {Approval} event.
         */
        function approve(address spender, uint256 amount) external returns (bool);
        /**
         * @dev Moves `amount` tokens from `from` to `to` using the
         * allowance mechanism. `amount` is then deducted from the caller's
         * allowance.
         *
         * Returns a boolean value indicating whether the operation succeeded.
         *
         * Emits a {Transfer} event.
         */
        function transferFrom(
            address from,
            address to,
            uint256 amount
        ) external returns (bool);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
     * checks.
     *
     * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
     * easily result in undesired exploitation or bugs, since developers usually
     * assume that overflows raise errors. `SafeCast` restores this intuition by
     * reverting the transaction when such 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.
     *
     * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
     * all math on `uint256` and `int256` and then downcasting.
     */
    library SafeCast {
        /**
         * @dev Returns the downcasted uint248 from uint256, reverting on
         * overflow (when the input is greater than largest uint248).
         *
         * Counterpart to Solidity's `uint248` operator.
         *
         * Requirements:
         *
         * - input must fit into 248 bits
         *
         * _Available since v4.7._
         */
        function toUint248(uint256 value) internal pure returns (uint248) {
            require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
            return uint248(value);
        }
        /**
         * @dev Returns the downcasted uint240 from uint256, reverting on
         * overflow (when the input is greater than largest uint240).
         *
         * Counterpart to Solidity's `uint240` operator.
         *
         * Requirements:
         *
         * - input must fit into 240 bits
         *
         * _Available since v4.7._
         */
        function toUint240(uint256 value) internal pure returns (uint240) {
            require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
            return uint240(value);
        }
        /**
         * @dev Returns the downcasted uint232 from uint256, reverting on
         * overflow (when the input is greater than largest uint232).
         *
         * Counterpart to Solidity's `uint232` operator.
         *
         * Requirements:
         *
         * - input must fit into 232 bits
         *
         * _Available since v4.7._
         */
        function toUint232(uint256 value) internal pure returns (uint232) {
            require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
            return uint232(value);
        }
        /**
         * @dev Returns the downcasted uint224 from uint256, reverting on
         * overflow (when the input is greater than largest uint224).
         *
         * Counterpart to Solidity's `uint224` operator.
         *
         * Requirements:
         *
         * - input must fit into 224 bits
         *
         * _Available since v4.2._
         */
        function toUint224(uint256 value) internal pure returns (uint224) {
            require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
            return uint224(value);
        }
        /**
         * @dev Returns the downcasted uint216 from uint256, reverting on
         * overflow (when the input is greater than largest uint216).
         *
         * Counterpart to Solidity's `uint216` operator.
         *
         * Requirements:
         *
         * - input must fit into 216 bits
         *
         * _Available since v4.7._
         */
        function toUint216(uint256 value) internal pure returns (uint216) {
            require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
            return uint216(value);
        }
        /**
         * @dev Returns the downcasted uint208 from uint256, reverting on
         * overflow (when the input is greater than largest uint208).
         *
         * Counterpart to Solidity's `uint208` operator.
         *
         * Requirements:
         *
         * - input must fit into 208 bits
         *
         * _Available since v4.7._
         */
        function toUint208(uint256 value) internal pure returns (uint208) {
            require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
            return uint208(value);
        }
        /**
         * @dev Returns the downcasted uint200 from uint256, reverting on
         * overflow (when the input is greater than largest uint200).
         *
         * Counterpart to Solidity's `uint200` operator.
         *
         * Requirements:
         *
         * - input must fit into 200 bits
         *
         * _Available since v4.7._
         */
        function toUint200(uint256 value) internal pure returns (uint200) {
            require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
            return uint200(value);
        }
        /**
         * @dev Returns the downcasted uint192 from uint256, reverting on
         * overflow (when the input is greater than largest uint192).
         *
         * Counterpart to Solidity's `uint192` operator.
         *
         * Requirements:
         *
         * - input must fit into 192 bits
         *
         * _Available since v4.7._
         */
        function toUint192(uint256 value) internal pure returns (uint192) {
            require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
            return uint192(value);
        }
        /**
         * @dev Returns the downcasted uint184 from uint256, reverting on
         * overflow (when the input is greater than largest uint184).
         *
         * Counterpart to Solidity's `uint184` operator.
         *
         * Requirements:
         *
         * - input must fit into 184 bits
         *
         * _Available since v4.7._
         */
        function toUint184(uint256 value) internal pure returns (uint184) {
            require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
            return uint184(value);
        }
        /**
         * @dev Returns the downcasted uint176 from uint256, reverting on
         * overflow (when the input is greater than largest uint176).
         *
         * Counterpart to Solidity's `uint176` operator.
         *
         * Requirements:
         *
         * - input must fit into 176 bits
         *
         * _Available since v4.7._
         */
        function toUint176(uint256 value) internal pure returns (uint176) {
            require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
            return uint176(value);
        }
        /**
         * @dev Returns the downcasted uint168 from uint256, reverting on
         * overflow (when the input is greater than largest uint168).
         *
         * Counterpart to Solidity's `uint168` operator.
         *
         * Requirements:
         *
         * - input must fit into 168 bits
         *
         * _Available since v4.7._
         */
        function toUint168(uint256 value) internal pure returns (uint168) {
            require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
            return uint168(value);
        }
        /**
         * @dev Returns the downcasted uint160 from uint256, reverting on
         * overflow (when the input is greater than largest uint160).
         *
         * Counterpart to Solidity's `uint160` operator.
         *
         * Requirements:
         *
         * - input must fit into 160 bits
         *
         * _Available since v4.7._
         */
        function toUint160(uint256 value) internal pure returns (uint160) {
            require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
            return uint160(value);
        }
        /**
         * @dev Returns the downcasted uint152 from uint256, reverting on
         * overflow (when the input is greater than largest uint152).
         *
         * Counterpart to Solidity's `uint152` operator.
         *
         * Requirements:
         *
         * - input must fit into 152 bits
         *
         * _Available since v4.7._
         */
        function toUint152(uint256 value) internal pure returns (uint152) {
            require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
            return uint152(value);
        }
        /**
         * @dev Returns the downcasted uint144 from uint256, reverting on
         * overflow (when the input is greater than largest uint144).
         *
         * Counterpart to Solidity's `uint144` operator.
         *
         * Requirements:
         *
         * - input must fit into 144 bits
         *
         * _Available since v4.7._
         */
        function toUint144(uint256 value) internal pure returns (uint144) {
            require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
            return uint144(value);
        }
        /**
         * @dev Returns the downcasted uint136 from uint256, reverting on
         * overflow (when the input is greater than largest uint136).
         *
         * Counterpart to Solidity's `uint136` operator.
         *
         * Requirements:
         *
         * - input must fit into 136 bits
         *
         * _Available since v4.7._
         */
        function toUint136(uint256 value) internal pure returns (uint136) {
            require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
            return uint136(value);
        }
        /**
         * @dev Returns the downcasted uint128 from uint256, reverting on
         * overflow (when the input is greater than largest uint128).
         *
         * Counterpart to Solidity's `uint128` operator.
         *
         * Requirements:
         *
         * - input must fit into 128 bits
         *
         * _Available since v2.5._
         */
        function toUint128(uint256 value) internal pure returns (uint128) {
            require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
            return uint128(value);
        }
        /**
         * @dev Returns the downcasted uint120 from uint256, reverting on
         * overflow (when the input is greater than largest uint120).
         *
         * Counterpart to Solidity's `uint120` operator.
         *
         * Requirements:
         *
         * - input must fit into 120 bits
         *
         * _Available since v4.7._
         */
        function toUint120(uint256 value) internal pure returns (uint120) {
            require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
            return uint120(value);
        }
        /**
         * @dev Returns the downcasted uint112 from uint256, reverting on
         * overflow (when the input is greater than largest uint112).
         *
         * Counterpart to Solidity's `uint112` operator.
         *
         * Requirements:
         *
         * - input must fit into 112 bits
         *
         * _Available since v4.7._
         */
        function toUint112(uint256 value) internal pure returns (uint112) {
            require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
            return uint112(value);
        }
        /**
         * @dev Returns the downcasted uint104 from uint256, reverting on
         * overflow (when the input is greater than largest uint104).
         *
         * Counterpart to Solidity's `uint104` operator.
         *
         * Requirements:
         *
         * - input must fit into 104 bits
         *
         * _Available since v4.7._
         */
        function toUint104(uint256 value) internal pure returns (uint104) {
            require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
            return uint104(value);
        }
        /**
         * @dev Returns the downcasted uint96 from uint256, reverting on
         * overflow (when the input is greater than largest uint96).
         *
         * Counterpart to Solidity's `uint96` operator.
         *
         * Requirements:
         *
         * - input must fit into 96 bits
         *
         * _Available since v4.2._
         */
        function toUint96(uint256 value) internal pure returns (uint96) {
            require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
            return uint96(value);
        }
        /**
         * @dev Returns the downcasted uint88 from uint256, reverting on
         * overflow (when the input is greater than largest uint88).
         *
         * Counterpart to Solidity's `uint88` operator.
         *
         * Requirements:
         *
         * - input must fit into 88 bits
         *
         * _Available since v4.7._
         */
        function toUint88(uint256 value) internal pure returns (uint88) {
            require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
            return uint88(value);
        }
        /**
         * @dev Returns the downcasted uint80 from uint256, reverting on
         * overflow (when the input is greater than largest uint80).
         *
         * Counterpart to Solidity's `uint80` operator.
         *
         * Requirements:
         *
         * - input must fit into 80 bits
         *
         * _Available since v4.7._
         */
        function toUint80(uint256 value) internal pure returns (uint80) {
            require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
            return uint80(value);
        }
        /**
         * @dev Returns the downcasted uint72 from uint256, reverting on
         * overflow (when the input is greater than largest uint72).
         *
         * Counterpart to Solidity's `uint72` operator.
         *
         * Requirements:
         *
         * - input must fit into 72 bits
         *
         * _Available since v4.7._
         */
        function toUint72(uint256 value) internal pure returns (uint72) {
            require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
            return uint72(value);
        }
        /**
         * @dev Returns the downcasted uint64 from uint256, reverting on
         * overflow (when the input is greater than largest uint64).
         *
         * Counterpart to Solidity's `uint64` operator.
         *
         * Requirements:
         *
         * - input must fit into 64 bits
         *
         * _Available since v2.5._
         */
        function toUint64(uint256 value) internal pure returns (uint64) {
            require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
            return uint64(value);
        }
        /**
         * @dev Returns the downcasted uint56 from uint256, reverting on
         * overflow (when the input is greater than largest uint56).
         *
         * Counterpart to Solidity's `uint56` operator.
         *
         * Requirements:
         *
         * - input must fit into 56 bits
         *
         * _Available since v4.7._
         */
        function toUint56(uint256 value) internal pure returns (uint56) {
            require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
            return uint56(value);
        }
        /**
         * @dev Returns the downcasted uint48 from uint256, reverting on
         * overflow (when the input is greater than largest uint48).
         *
         * Counterpart to Solidity's `uint48` operator.
         *
         * Requirements:
         *
         * - input must fit into 48 bits
         *
         * _Available since v4.7._
         */
        function toUint48(uint256 value) internal pure returns (uint48) {
            require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
            return uint48(value);
        }
        /**
         * @dev Returns the downcasted uint40 from uint256, reverting on
         * overflow (when the input is greater than largest uint40).
         *
         * Counterpart to Solidity's `uint40` operator.
         *
         * Requirements:
         *
         * - input must fit into 40 bits
         *
         * _Available since v4.7._
         */
        function toUint40(uint256 value) internal pure returns (uint40) {
            require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
            return uint40(value);
        }
        /**
         * @dev Returns the downcasted uint32 from uint256, reverting on
         * overflow (when the input is greater than largest uint32).
         *
         * Counterpart to Solidity's `uint32` operator.
         *
         * Requirements:
         *
         * - input must fit into 32 bits
         *
         * _Available since v2.5._
         */
        function toUint32(uint256 value) internal pure returns (uint32) {
            require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
            return uint32(value);
        }
        /**
         * @dev Returns the downcasted uint24 from uint256, reverting on
         * overflow (when the input is greater than largest uint24).
         *
         * Counterpart to Solidity's `uint24` operator.
         *
         * Requirements:
         *
         * - input must fit into 24 bits
         *
         * _Available since v4.7._
         */
        function toUint24(uint256 value) internal pure returns (uint24) {
            require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
            return uint24(value);
        }
        /**
         * @dev Returns the downcasted uint16 from uint256, reverting on
         * overflow (when the input is greater than largest uint16).
         *
         * Counterpart to Solidity's `uint16` operator.
         *
         * Requirements:
         *
         * - input must fit into 16 bits
         *
         * _Available since v2.5._
         */
        function toUint16(uint256 value) internal pure returns (uint16) {
            require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
            return uint16(value);
        }
        /**
         * @dev Returns the downcasted uint8 from uint256, reverting on
         * overflow (when the input is greater than largest uint8).
         *
         * Counterpart to Solidity's `uint8` operator.
         *
         * Requirements:
         *
         * - input must fit into 8 bits
         *
         * _Available since v2.5._
         */
        function toUint8(uint256 value) internal pure returns (uint8) {
            require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
            return uint8(value);
        }
        /**
         * @dev Converts a signed int256 into an unsigned uint256.
         *
         * Requirements:
         *
         * - input must be greater than or equal to 0.
         *
         * _Available since v3.0._
         */
        function toUint256(int256 value) internal pure returns (uint256) {
            require(value >= 0, "SafeCast: value must be positive");
            return uint256(value);
        }
        /**
         * @dev Returns the downcasted int248 from int256, reverting on
         * overflow (when the input is less than smallest int248 or
         * greater than largest int248).
         *
         * Counterpart to Solidity's `int248` operator.
         *
         * Requirements:
         *
         * - input must fit into 248 bits
         *
         * _Available since v4.7._
         */
        function toInt248(int256 value) internal pure returns (int248) {
            require(value >= type(int248).min && value <= type(int248).max, "SafeCast: value doesn't fit in 248 bits");
            return int248(value);
        }
        /**
         * @dev Returns the downcasted int240 from int256, reverting on
         * overflow (when the input is less than smallest int240 or
         * greater than largest int240).
         *
         * Counterpart to Solidity's `int240` operator.
         *
         * Requirements:
         *
         * - input must fit into 240 bits
         *
         * _Available since v4.7._
         */
        function toInt240(int256 value) internal pure returns (int240) {
            require(value >= type(int240).min && value <= type(int240).max, "SafeCast: value doesn't fit in 240 bits");
            return int240(value);
        }
        /**
         * @dev Returns the downcasted int232 from int256, reverting on
         * overflow (when the input is less than smallest int232 or
         * greater than largest int232).
         *
         * Counterpart to Solidity's `int232` operator.
         *
         * Requirements:
         *
         * - input must fit into 232 bits
         *
         * _Available since v4.7._
         */
        function toInt232(int256 value) internal pure returns (int232) {
            require(value >= type(int232).min && value <= type(int232).max, "SafeCast: value doesn't fit in 232 bits");
            return int232(value);
        }
        /**
         * @dev Returns the downcasted int224 from int256, reverting on
         * overflow (when the input is less than smallest int224 or
         * greater than largest int224).
         *
         * Counterpart to Solidity's `int224` operator.
         *
         * Requirements:
         *
         * - input must fit into 224 bits
         *
         * _Available since v4.7._
         */
        function toInt224(int256 value) internal pure returns (int224) {
            require(value >= type(int224).min && value <= type(int224).max, "SafeCast: value doesn't fit in 224 bits");
            return int224(value);
        }
        /**
         * @dev Returns the downcasted int216 from int256, reverting on
         * overflow (when the input is less than smallest int216 or
         * greater than largest int216).
         *
         * Counterpart to Solidity's `int216` operator.
         *
         * Requirements:
         *
         * - input must fit into 216 bits
         *
         * _Available since v4.7._
         */
        function toInt216(int256 value) internal pure returns (int216) {
            require(value >= type(int216).min && value <= type(int216).max, "SafeCast: value doesn't fit in 216 bits");
            return int216(value);
        }
        /**
         * @dev Returns the downcasted int208 from int256, reverting on
         * overflow (when the input is less than smallest int208 or
         * greater than largest int208).
         *
         * Counterpart to Solidity's `int208` operator.
         *
         * Requirements:
         *
         * - input must fit into 208 bits
         *
         * _Available since v4.7._
         */
        function toInt208(int256 value) internal pure returns (int208) {
            require(value >= type(int208).min && value <= type(int208).max, "SafeCast: value doesn't fit in 208 bits");
            return int208(value);
        }
        /**
         * @dev Returns the downcasted int200 from int256, reverting on
         * overflow (when the input is less than smallest int200 or
         * greater than largest int200).
         *
         * Counterpart to Solidity's `int200` operator.
         *
         * Requirements:
         *
         * - input must fit into 200 bits
         *
         * _Available since v4.7._
         */
        function toInt200(int256 value) internal pure returns (int200) {
            require(value >= type(int200).min && value <= type(int200).max, "SafeCast: value doesn't fit in 200 bits");
            return int200(value);
        }
        /**
         * @dev Returns the downcasted int192 from int256, reverting on
         * overflow (when the input is less than smallest int192 or
         * greater than largest int192).
         *
         * Counterpart to Solidity's `int192` operator.
         *
         * Requirements:
         *
         * - input must fit into 192 bits
         *
         * _Available since v4.7._
         */
        function toInt192(int256 value) internal pure returns (int192) {
            require(value >= type(int192).min && value <= type(int192).max, "SafeCast: value doesn't fit in 192 bits");
            return int192(value);
        }
        /**
         * @dev Returns the downcasted int184 from int256, reverting on
         * overflow (when the input is less than smallest int184 or
         * greater than largest int184).
         *
         * Counterpart to Solidity's `int184` operator.
         *
         * Requirements:
         *
         * - input must fit into 184 bits
         *
         * _Available since v4.7._
         */
        function toInt184(int256 value) internal pure returns (int184) {
            require(value >= type(int184).min && value <= type(int184).max, "SafeCast: value doesn't fit in 184 bits");
            return int184(value);
        }
        /**
         * @dev Returns the downcasted int176 from int256, reverting on
         * overflow (when the input is less than smallest int176 or
         * greater than largest int176).
         *
         * Counterpart to Solidity's `int176` operator.
         *
         * Requirements:
         *
         * - input must fit into 176 bits
         *
         * _Available since v4.7._
         */
        function toInt176(int256 value) internal pure returns (int176) {
            require(value >= type(int176).min && value <= type(int176).max, "SafeCast: value doesn't fit in 176 bits");
            return int176(value);
        }
        /**
         * @dev Returns the downcasted int168 from int256, reverting on
         * overflow (when the input is less than smallest int168 or
         * greater than largest int168).
         *
         * Counterpart to Solidity's `int168` operator.
         *
         * Requirements:
         *
         * - input must fit into 168 bits
         *
         * _Available since v4.7._
         */
        function toInt168(int256 value) internal pure returns (int168) {
            require(value >= type(int168).min && value <= type(int168).max, "SafeCast: value doesn't fit in 168 bits");
            return int168(value);
        }
        /**
         * @dev Returns the downcasted int160 from int256, reverting on
         * overflow (when the input is less than smallest int160 or
         * greater than largest int160).
         *
         * Counterpart to Solidity's `int160` operator.
         *
         * Requirements:
         *
         * - input must fit into 160 bits
         *
         * _Available since v4.7._
         */
        function toInt160(int256 value) internal pure returns (int160) {
            require(value >= type(int160).min && value <= type(int160).max, "SafeCast: value doesn't fit in 160 bits");
            return int160(value);
        }
        /**
         * @dev Returns the downcasted int152 from int256, reverting on
         * overflow (when the input is less than smallest int152 or
         * greater than largest int152).
         *
         * Counterpart to Solidity's `int152` operator.
         *
         * Requirements:
         *
         * - input must fit into 152 bits
         *
         * _Available since v4.7._
         */
        function toInt152(int256 value) internal pure returns (int152) {
            require(value >= type(int152).min && value <= type(int152).max, "SafeCast: value doesn't fit in 152 bits");
            return int152(value);
        }
        /**
         * @dev Returns the downcasted int144 from int256, reverting on
         * overflow (when the input is less than smallest int144 or
         * greater than largest int144).
         *
         * Counterpart to Solidity's `int144` operator.
         *
         * Requirements:
         *
         * - input must fit into 144 bits
         *
         * _Available since v4.7._
         */
        function toInt144(int256 value) internal pure returns (int144) {
            require(value >= type(int144).min && value <= type(int144).max, "SafeCast: value doesn't fit in 144 bits");
            return int144(value);
        }
        /**
         * @dev Returns the downcasted int136 from int256, reverting on
         * overflow (when the input is less than smallest int136 or
         * greater than largest int136).
         *
         * Counterpart to Solidity's `int136` operator.
         *
         * Requirements:
         *
         * - input must fit into 136 bits
         *
         * _Available since v4.7._
         */
        function toInt136(int256 value) internal pure returns (int136) {
            require(value >= type(int136).min && value <= type(int136).max, "SafeCast: value doesn't fit in 136 bits");
            return int136(value);
        }
        /**
         * @dev Returns the downcasted int128 from int256, reverting on
         * overflow (when the input is less than smallest int128 or
         * greater than largest int128).
         *
         * Counterpart to Solidity's `int128` operator.
         *
         * Requirements:
         *
         * - input must fit into 128 bits
         *
         * _Available since v3.1._
         */
        function toInt128(int256 value) internal pure returns (int128) {
            require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
            return int128(value);
        }
        /**
         * @dev Returns the downcasted int120 from int256, reverting on
         * overflow (when the input is less than smallest int120 or
         * greater than largest int120).
         *
         * Counterpart to Solidity's `int120` operator.
         *
         * Requirements:
         *
         * - input must fit into 120 bits
         *
         * _Available since v4.7._
         */
        function toInt120(int256 value) internal pure returns (int120) {
            require(value >= type(int120).min && value <= type(int120).max, "SafeCast: value doesn't fit in 120 bits");
            return int120(value);
        }
        /**
         * @dev Returns the downcasted int112 from int256, reverting on
         * overflow (when the input is less than smallest int112 or
         * greater than largest int112).
         *
         * Counterpart to Solidity's `int112` operator.
         *
         * Requirements:
         *
         * - input must fit into 112 bits
         *
         * _Available since v4.7._
         */
        function toInt112(int256 value) internal pure returns (int112) {
            require(value >= type(int112).min && value <= type(int112).max, "SafeCast: value doesn't fit in 112 bits");
            return int112(value);
        }
        /**
         * @dev Returns the downcasted int104 from int256, reverting on
         * overflow (when the input is less than smallest int104 or
         * greater than largest int104).
         *
         * Counterpart to Solidity's `int104` operator.
         *
         * Requirements:
         *
         * - input must fit into 104 bits
         *
         * _Available since v4.7._
         */
        function toInt104(int256 value) internal pure returns (int104) {
            require(value >= type(int104).min && value <= type(int104).max, "SafeCast: value doesn't fit in 104 bits");
            return int104(value);
        }
        /**
         * @dev Returns the downcasted int96 from int256, reverting on
         * overflow (when the input is less than smallest int96 or
         * greater than largest int96).
         *
         * Counterpart to Solidity's `int96` operator.
         *
         * Requirements:
         *
         * - input must fit into 96 bits
         *
         * _Available since v4.7._
         */
        function toInt96(int256 value) internal pure returns (int96) {
            require(value >= type(int96).min && value <= type(int96).max, "SafeCast: value doesn't fit in 96 bits");
            return int96(value);
        }
        /**
         * @dev Returns the downcasted int88 from int256, reverting on
         * overflow (when the input is less than smallest int88 or
         * greater than largest int88).
         *
         * Counterpart to Solidity's `int88` operator.
         *
         * Requirements:
         *
         * - input must fit into 88 bits
         *
         * _Available since v4.7._
         */
        function toInt88(int256 value) internal pure returns (int88) {
            require(value >= type(int88).min && value <= type(int88).max, "SafeCast: value doesn't fit in 88 bits");
            return int88(value);
        }
        /**
         * @dev Returns the downcasted int80 from int256, reverting on
         * overflow (when the input is less than smallest int80 or
         * greater than largest int80).
         *
         * Counterpart to Solidity's `int80` operator.
         *
         * Requirements:
         *
         * - input must fit into 80 bits
         *
         * _Available since v4.7._
         */
        function toInt80(int256 value) internal pure returns (int80) {
            require(value >= type(int80).min && value <= type(int80).max, "SafeCast: value doesn't fit in 80 bits");
            return int80(value);
        }
        /**
         * @dev Returns the downcasted int72 from int256, reverting on
         * overflow (when the input is less than smallest int72 or
         * greater than largest int72).
         *
         * Counterpart to Solidity's `int72` operator.
         *
         * Requirements:
         *
         * - input must fit into 72 bits
         *
         * _Available since v4.7._
         */
        function toInt72(int256 value) internal pure returns (int72) {
            require(value >= type(int72).min && value <= type(int72).max, "SafeCast: value doesn't fit in 72 bits");
            return int72(value);
        }
        /**
         * @dev Returns the downcasted int64 from int256, reverting on
         * overflow (when the input is less than smallest int64 or
         * greater than largest int64).
         *
         * Counterpart to Solidity's `int64` operator.
         *
         * Requirements:
         *
         * - input must fit into 64 bits
         *
         * _Available since v3.1._
         */
        function toInt64(int256 value) internal pure returns (int64) {
            require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
            return int64(value);
        }
        /**
         * @dev Returns the downcasted int56 from int256, reverting on
         * overflow (when the input is less than smallest int56 or
         * greater than largest int56).
         *
         * Counterpart to Solidity's `int56` operator.
         *
         * Requirements:
         *
         * - input must fit into 56 bits
         *
         * _Available since v4.7._
         */
        function toInt56(int256 value) internal pure returns (int56) {
            require(value >= type(int56).min && value <= type(int56).max, "SafeCast: value doesn't fit in 56 bits");
            return int56(value);
        }
        /**
         * @dev Returns the downcasted int48 from int256, reverting on
         * overflow (when the input is less than smallest int48 or
         * greater than largest int48).
         *
         * Counterpart to Solidity's `int48` operator.
         *
         * Requirements:
         *
         * - input must fit into 48 bits
         *
         * _Available since v4.7._
         */
        function toInt48(int256 value) internal pure returns (int48) {
            require(value >= type(int48).min && value <= type(int48).max, "SafeCast: value doesn't fit in 48 bits");
            return int48(value);
        }
        /**
         * @dev Returns the downcasted int40 from int256, reverting on
         * overflow (when the input is less than smallest int40 or
         * greater than largest int40).
         *
         * Counterpart to Solidity's `int40` operator.
         *
         * Requirements:
         *
         * - input must fit into 40 bits
         *
         * _Available since v4.7._
         */
        function toInt40(int256 value) internal pure returns (int40) {
            require(value >= type(int40).min && value <= type(int40).max, "SafeCast: value doesn't fit in 40 bits");
            return int40(value);
        }
        /**
         * @dev Returns the downcasted int32 from int256, reverting on
         * overflow (when the input is less than smallest int32 or
         * greater than largest int32).
         *
         * Counterpart to Solidity's `int32` operator.
         *
         * Requirements:
         *
         * - input must fit into 32 bits
         *
         * _Available since v3.1._
         */
        function toInt32(int256 value) internal pure returns (int32) {
            require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
            return int32(value);
        }
        /**
         * @dev Returns the downcasted int24 from int256, reverting on
         * overflow (when the input is less than smallest int24 or
         * greater than largest int24).
         *
         * Counterpart to Solidity's `int24` operator.
         *
         * Requirements:
         *
         * - input must fit into 24 bits
         *
         * _Available since v4.7._
         */
        function toInt24(int256 value) internal pure returns (int24) {
            require(value >= type(int24).min && value <= type(int24).max, "SafeCast: value doesn't fit in 24 bits");
            return int24(value);
        }
        /**
         * @dev Returns the downcasted int16 from int256, reverting on
         * overflow (when the input is less than smallest int16 or
         * greater than largest int16).
         *
         * Counterpart to Solidity's `int16` operator.
         *
         * Requirements:
         *
         * - input must fit into 16 bits
         *
         * _Available since v3.1._
         */
        function toInt16(int256 value) internal pure returns (int16) {
            require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
            return int16(value);
        }
        /**
         * @dev Returns the downcasted int8 from int256, reverting on
         * overflow (when the input is less than smallest int8 or
         * greater than largest int8).
         *
         * Counterpart to Solidity's `int8` operator.
         *
         * Requirements:
         *
         * - input must fit into 8 bits
         *
         * _Available since v3.1._
         */
        function toInt8(int256 value) internal pure returns (int8) {
            require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
            return int8(value);
        }
        /**
         * @dev Converts an unsigned uint256 into a signed int256.
         *
         * Requirements:
         *
         * - input must be less than or equal to maxInt256.
         *
         * _Available since v3.0._
         */
        function toInt256(uint256 value) internal pure returns (int256) {
            // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
            require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
            return int256(value);
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
    pragma solidity ^0.8.0;
    import "../utils/Context.sol";
    /**
     * @dev Contract module which provides a basic access control mechanism, where
     * there is an account (an owner) that can be granted exclusive access to
     * specific functions.
     *
     * By default, the owner account will be the one that deploys the contract. This
     * can later be changed with {transferOwnership}.
     *
     * This module is used through inheritance. It will make available the modifier
     * `onlyOwner`, which can be applied to your functions to restrict their use to
     * the owner.
     */
    abstract contract Ownable is Context {
        address private _owner;
        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
        /**
         * @dev Initializes the contract setting the deployer as the initial owner.
         */
        constructor() {
            _transferOwnership(_msgSender());
        }
        /**
         * @dev Throws if called by any account other than the owner.
         */
        modifier onlyOwner() {
            _checkOwner();
            _;
        }
        /**
         * @dev Returns the address of the current owner.
         */
        function owner() public view virtual returns (address) {
            return _owner;
        }
        /**
         * @dev Throws if the sender is not the owner.
         */
        function _checkOwner() internal view virtual {
            require(owner() == _msgSender(), "Ownable: caller is not the owner");
        }
        /**
         * @dev Leaves the contract without owner. It will not be possible to call
         * `onlyOwner` functions anymore. Can only be called by the current owner.
         *
         * NOTE: Renouncing ownership will leave the contract without an owner,
         * thereby removing any functionality that is only available to the owner.
         */
        function renounceOwnership() public virtual onlyOwner {
            _transferOwnership(address(0));
        }
        /**
         * @dev Transfers ownership of the contract to a new account (`newOwner`).
         * Can only be called by the current owner.
         */
        function transferOwnership(address newOwner) public virtual onlyOwner {
            require(newOwner != address(0), "Ownable: new owner is the zero address");
            _transferOwnership(newOwner);
        }
        /**
         * @dev Transfers ownership of the contract to a new account (`newOwner`).
         * Internal function without access restriction.
         */
        function _transferOwnership(address newOwner) internal virtual {
            address oldOwner = _owner;
            _owner = newOwner;
            emit OwnershipTransferred(oldOwner, newOwner);
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
    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
    // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Provides information about the current execution context, including the
     * sender of the transaction and its data. While these are generally available
     * via msg.sender and msg.data, they should not be accessed in such a direct
     * manner, since when dealing with meta-transactions the account sending and
     * paying for execution may not be the actual sender (as far as an application
     * is concerned).
     *
     * This contract is only required for intermediate, library-like contracts.
     */
    abstract contract Context {
        function _msgSender() internal view virtual returns (address) {
            return msg.sender;
        }
        function _msgData() internal view virtual returns (bytes calldata) {
            return msg.data;
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)
    pragma solidity ^0.8.0;
    import "./IERC721.sol";
    import "./IERC721Receiver.sol";
    import "./extensions/IERC721Metadata.sol";
    import "../../utils/Address.sol";
    import "../../utils/Context.sol";
    import "../../utils/Strings.sol";
    import "../../utils/introspection/ERC165.sol";
    /**
     * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
     * the Metadata extension, but not including the Enumerable extension, which is available separately as
     * {ERC721Enumerable}.
     */
    contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
        using Address for address;
        using Strings for uint256;
        // Token name
        string private _name;
        // Token symbol
        string private _symbol;
        // Mapping from token ID to owner address
        mapping(uint256 => address) private _owners;
        // Mapping owner address to token count
        mapping(address => uint256) private _balances;
        // Mapping from token ID to approved address
        mapping(uint256 => address) private _tokenApprovals;
        // Mapping from owner to operator approvals
        mapping(address => mapping(address => bool)) private _operatorApprovals;
        /**
         * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
         */
        constructor(string memory name_, string memory symbol_) {
            _name = name_;
            _symbol = symbol_;
        }
        /**
         * @dev See {IERC165-supportsInterface}.
         */
        function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
            return
                interfaceId == type(IERC721).interfaceId ||
                interfaceId == type(IERC721Metadata).interfaceId ||
                super.supportsInterface(interfaceId);
        }
        /**
         * @dev See {IERC721-balanceOf}.
         */
        function balanceOf(address owner) public view virtual override returns (uint256) {
            require(owner != address(0), "ERC721: address zero is not a valid owner");
            return _balances[owner];
        }
        /**
         * @dev See {IERC721-ownerOf}.
         */
        function ownerOf(uint256 tokenId) public view virtual override returns (address) {
            address owner = _owners[tokenId];
            require(owner != address(0), "ERC721: invalid token ID");
            return owner;
        }
        /**
         * @dev See {IERC721Metadata-name}.
         */
        function name() public view virtual override returns (string memory) {
            return _name;
        }
        /**
         * @dev See {IERC721Metadata-symbol}.
         */
        function symbol() public view virtual override returns (string memory) {
            return _symbol;
        }
        /**
         * @dev See {IERC721Metadata-tokenURI}.
         */
        function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
            _requireMinted(tokenId);
            string memory baseURI = _baseURI();
            return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
        }
        /**
         * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
         * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
         * by default, can be overridden in child contracts.
         */
        function _baseURI() internal view virtual returns (string memory) {
            return "";
        }
        /**
         * @dev See {IERC721-approve}.
         */
        function approve(address to, uint256 tokenId) public virtual override {
            address owner = ERC721.ownerOf(tokenId);
            require(to != owner, "ERC721: approval to current owner");
            require(
                _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
                "ERC721: approve caller is not token owner nor approved for all"
            );
            _approve(to, tokenId);
        }
        /**
         * @dev See {IERC721-getApproved}.
         */
        function getApproved(uint256 tokenId) public view virtual override returns (address) {
            _requireMinted(tokenId);
            return _tokenApprovals[tokenId];
        }
        /**
         * @dev See {IERC721-setApprovalForAll}.
         */
        function setApprovalForAll(address operator, bool approved) public virtual override {
            _setApprovalForAll(_msgSender(), operator, approved);
        }
        /**
         * @dev See {IERC721-isApprovedForAll}.
         */
        function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
            return _operatorApprovals[owner][operator];
        }
        /**
         * @dev See {IERC721-transferFrom}.
         */
        function transferFrom(
            address from,
            address to,
            uint256 tokenId
        ) public virtual override {
            //solhint-disable-next-line max-line-length
            require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved");
            _transfer(from, to, tokenId);
        }
        /**
         * @dev See {IERC721-safeTransferFrom}.
         */
        function safeTransferFrom(
            address from,
            address to,
            uint256 tokenId
        ) public virtual override {
            safeTransferFrom(from, to, tokenId, "");
        }
        /**
         * @dev See {IERC721-safeTransferFrom}.
         */
        function safeTransferFrom(
            address from,
            address to,
            uint256 tokenId,
            bytes memory data
        ) public virtual override {
            require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved");
            _safeTransfer(from, to, tokenId, data);
        }
        /**
         * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
         * are aware of the ERC721 protocol to prevent tokens from being forever locked.
         *
         * `data` is additional data, it has no specified format and it is sent in call to `to`.
         *
         * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
         * implement alternative mechanisms to perform token transfer, such as signature-based.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must exist and be owned by `from`.
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function _safeTransfer(
            address from,
            address to,
            uint256 tokenId,
            bytes memory data
        ) internal virtual {
            _transfer(from, to, tokenId);
            require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
        }
        /**
         * @dev Returns whether `tokenId` exists.
         *
         * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
         *
         * Tokens start existing when they are minted (`_mint`),
         * and stop existing when they are burned (`_burn`).
         */
        function _exists(uint256 tokenId) internal view virtual returns (bool) {
            return _owners[tokenId] != address(0);
        }
        /**
         * @dev Returns whether `spender` is allowed to manage `tokenId`.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
            address owner = ERC721.ownerOf(tokenId);
            return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
        }
        /**
         * @dev Safely mints `tokenId` and transfers it to `to`.
         *
         * Requirements:
         *
         * - `tokenId` must not exist.
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function _safeMint(address to, uint256 tokenId) internal virtual {
            _safeMint(to, tokenId, "");
        }
        /**
         * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
         * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
         */
        function _safeMint(
            address to,
            uint256 tokenId,
            bytes memory data
        ) internal virtual {
            _mint(to, tokenId);
            require(
                _checkOnERC721Received(address(0), to, tokenId, data),
                "ERC721: transfer to non ERC721Receiver implementer"
            );
        }
        /**
         * @dev Mints `tokenId` and transfers it to `to`.
         *
         * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
         *
         * Requirements:
         *
         * - `tokenId` must not exist.
         * - `to` cannot be the zero address.
         *
         * Emits a {Transfer} event.
         */
        function _mint(address to, uint256 tokenId) internal virtual {
            require(to != address(0), "ERC721: mint to the zero address");
            require(!_exists(tokenId), "ERC721: token already minted");
            _beforeTokenTransfer(address(0), to, tokenId);
            _balances[to] += 1;
            _owners[tokenId] = to;
            emit Transfer(address(0), to, tokenId);
            _afterTokenTransfer(address(0), to, tokenId);
        }
        /**
         * @dev Destroys `tokenId`.
         * The approval is cleared when the token is burned.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         *
         * Emits a {Transfer} event.
         */
        function _burn(uint256 tokenId) internal virtual {
            address owner = ERC721.ownerOf(tokenId);
            _beforeTokenTransfer(owner, address(0), tokenId);
            // Clear approvals
            _approve(address(0), tokenId);
            _balances[owner] -= 1;
            delete _owners[tokenId];
            emit Transfer(owner, address(0), tokenId);
            _afterTokenTransfer(owner, address(0), tokenId);
        }
        /**
         * @dev Transfers `tokenId` from `from` to `to`.
         *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
         *
         * Requirements:
         *
         * - `to` cannot be the zero address.
         * - `tokenId` token must be owned by `from`.
         *
         * Emits a {Transfer} event.
         */
        function _transfer(
            address from,
            address to,
            uint256 tokenId
        ) internal virtual {
            require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
            require(to != address(0), "ERC721: transfer to the zero address");
            _beforeTokenTransfer(from, to, tokenId);
            // Clear approvals from the previous owner
            _approve(address(0), tokenId);
            _balances[from] -= 1;
            _balances[to] += 1;
            _owners[tokenId] = to;
            emit Transfer(from, to, tokenId);
            _afterTokenTransfer(from, to, tokenId);
        }
        /**
         * @dev Approve `to` to operate on `tokenId`
         *
         * Emits an {Approval} event.
         */
        function _approve(address to, uint256 tokenId) internal virtual {
            _tokenApprovals[tokenId] = to;
            emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
        }
        /**
         * @dev Approve `operator` to operate on all of `owner` tokens
         *
         * Emits an {ApprovalForAll} event.
         */
        function _setApprovalForAll(
            address owner,
            address operator,
            bool approved
        ) internal virtual {
            require(owner != operator, "ERC721: approve to caller");
            _operatorApprovals[owner][operator] = approved;
            emit ApprovalForAll(owner, operator, approved);
        }
        /**
         * @dev Reverts if the `tokenId` has not been minted yet.
         */
        function _requireMinted(uint256 tokenId) internal view virtual {
            require(_exists(tokenId), "ERC721: invalid token ID");
        }
        /**
         * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
         * The call is not executed if the target address is not a contract.
         *
         * @param from address representing the previous owner of the given token ID
         * @param to target address that will receive the tokens
         * @param tokenId uint256 ID of the token to be transferred
         * @param data bytes optional data to send along with the call
         * @return bool whether the call correctly returned the expected magic value
         */
        function _checkOnERC721Received(
            address from,
            address to,
            uint256 tokenId,
            bytes memory data
        ) private returns (bool) {
            if (to.isContract()) {
                try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                    return retval == IERC721Receiver.onERC721Received.selector;
                } catch (bytes memory reason) {
                    if (reason.length == 0) {
                        revert("ERC721: transfer to non ERC721Receiver implementer");
                    } else {
                        /// @solidity memory-safe-assembly
                        assembly {
                            revert(add(32, reason), mload(reason))
                        }
                    }
                }
            } else {
                return true;
            }
        }
        /**
         * @dev Hook that is called before any token transfer. This includes minting
         * and burning.
         *
         * Calling conditions:
         *
         * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
         * transferred to `to`.
         * - When `from` is zero, `tokenId` will be minted for `to`.
         * - When `to` is zero, ``from``'s `tokenId` will be burned.
         * - `from` and `to` are never both zero.
         *
         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
         */
        function _beforeTokenTransfer(
            address from,
            address to,
            uint256 tokenId
        ) internal virtual {}
        /**
         * @dev Hook that is called after any transfer of tokens. This includes
         * minting and burning.
         *
         * Calling conditions:
         *
         * - when `from` and `to` are both non-zero.
         * - `from` and `to` are never both zero.
         *
         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
         */
        function _afterTokenTransfer(
            address from,
            address to,
            uint256 tokenId
        ) internal virtual {}
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
    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);
        /**
         * @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
    // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)
    pragma solidity ^0.8.0;
    import "../../utils/introspection/IERC165.sol";
    /**
     * @dev Required interface of an ERC721 compliant contract.
     */
    interface IERC721 is IERC165 {
        /**
         * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
         */
        event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
        /**
         * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
         */
        event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
        /**
         * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
         */
        event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
        /**
         * @dev Returns the number of tokens in ``owner``'s account.
         */
        function balanceOf(address owner) external view returns (uint256 balance);
        /**
         * @dev Returns the owner of the `tokenId` token.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function ownerOf(uint256 tokenId) external view returns (address owner);
        /**
         * @dev Safely transfers `tokenId` token from `from` to `to`.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must exist and be owned by `from`.
         * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function safeTransferFrom(
            address from,
            address to,
            uint256 tokenId,
            bytes calldata data
        ) external;
        /**
         * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
         * are aware of the ERC721 protocol to prevent tokens from being forever locked.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must exist and be owned by `from`.
         * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
         *
         * Emits a {Transfer} event.
         */
        function safeTransferFrom(
            address from,
            address to,
            uint256 tokenId
        ) external;
        /**
         * @dev Transfers `tokenId` token from `from` to `to`.
         *
         * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
         *
         * Requirements:
         *
         * - `from` cannot be the zero address.
         * - `to` cannot be the zero address.
         * - `tokenId` token must be owned by `from`.
         * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
         *
         * Emits a {Transfer} event.
         */
        function transferFrom(
            address from,
            address to,
            uint256 tokenId
        ) external;
        /**
         * @dev Gives permission to `to` to transfer `tokenId` token to another account.
         * The approval is cleared when the token is transferred.
         *
         * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
         *
         * Requirements:
         *
         * - The caller must own the token or be an approved operator.
         * - `tokenId` must exist.
         *
         * Emits an {Approval} event.
         */
        function approve(address to, uint256 tokenId) external;
        /**
         * @dev Approve or remove `operator` as an operator for the caller.
         * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
         *
         * Requirements:
         *
         * - The `operator` cannot be the caller.
         *
         * Emits an {ApprovalForAll} event.
         */
        function setApprovalForAll(address operator, bool _approved) external;
        /**
         * @dev Returns the account approved for `tokenId` token.
         *
         * Requirements:
         *
         * - `tokenId` must exist.
         */
        function getApproved(uint256 tokenId) external view returns (address operator);
        /**
         * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
         *
         * See {setApprovalForAll}
         */
        function isApprovedForAll(address owner, address operator) external view returns (bool);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
    pragma solidity ^0.8.0;
    /**
     * @title ERC721 token receiver interface
     * @dev Interface for any contract that wants to support safeTransfers
     * from ERC721 asset contracts.
     */
    interface IERC721Receiver {
        /**
         * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
         * by `operator` from `from`, this function is called.
         *
         * It must return its Solidity selector to confirm the token transfer.
         * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
         *
         * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
         */
        function onERC721Received(
            address operator,
            address from,
            uint256 tokenId,
            bytes calldata data
        ) external returns (bytes4);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
    pragma solidity ^0.8.0;
    import "../IERC721.sol";
    /**
     * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
     * @dev See https://eips.ethereum.org/EIPS/eip-721
     */
    interface IERC721Metadata is IERC721 {
        /**
         * @dev Returns the token collection name.
         */
        function name() external view returns (string memory);
        /**
         * @dev Returns the token collection symbol.
         */
        function symbol() external view returns (string memory);
        /**
         * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
         */
        function tokenURI(uint256 tokenId) external view returns (string memory);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
    pragma solidity ^0.8.1;
    /**
     * @dev Collection of functions related to the address type
     */
    library Address {
        /**
         * @dev Returns true if `account` is a contract.
         *
         * [IMPORTANT]
         * ====
         * It is unsafe to assume that an address for which this function returns
         * false is an externally-owned account (EOA) and not a contract.
         *
         * Among others, `isContract` will return false for the following
         * types of addresses:
         *
         *  - an externally-owned account
         *  - a contract in construction
         *  - an address where a contract will be created
         *  - an address where a contract lived, but was destroyed
         * ====
         *
         * [IMPORTANT]
         * ====
         * You shouldn't rely on `isContract` to protect against flash loan attacks!
         *
         * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
         * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
         * constructor.
         * ====
         */
        function isContract(address account) internal view returns (bool) {
            // This method relies on extcodesize/address.code.length, which returns 0
            // for contracts in construction, since the code is only stored at the end
            // of the constructor execution.
            return account.code.length > 0;
        }
        /**
         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
         * `recipient`, forwarding all available gas and reverting on errors.
         *
         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
         * of certain opcodes, possibly making contracts go over the 2300 gas limit
         * imposed by `transfer`, making them unable to receive funds via
         * `transfer`. {sendValue} removes this limitation.
         *
         * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
         *
         * IMPORTANT: because control is transferred to `recipient`, care must be
         * taken to not create reentrancy vulnerabilities. Consider using
         * {ReentrancyGuard} or the
         * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
         */
        function sendValue(address payable recipient, uint256 amount) internal {
            require(address(this).balance >= amount, "Address: insufficient balance");
            (bool success, ) = recipient.call{value: amount}("");
            require(success, "Address: unable to send value, recipient may have reverted");
        }
        /**
         * @dev Performs a Solidity function call using a low level `call`. A
         * plain `call` is an unsafe replacement for a function call: use this
         * function instead.
         *
         * If `target` reverts with a revert reason, it is bubbled up by this
         * function (like regular Solidity function calls).
         *
         * Returns the raw returned data. To convert to the expected return value,
         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
         *
         * Requirements:
         *
         * - `target` must be a contract.
         * - calling `target` with `data` must not revert.
         *
         * _Available since v3.1._
         */
        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
            return functionCall(target, data, "Address: low-level call failed");
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
         * `errorMessage` as a fallback revert reason when `target` reverts.
         *
         * _Available since v3.1._
         */
        function functionCall(
            address target,
            bytes memory data,
            string memory errorMessage
        ) internal returns (bytes memory) {
            return functionCallWithValue(target, data, 0, errorMessage);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but also transferring `value` wei to `target`.
         *
         * Requirements:
         *
         * - the calling contract must have an ETH balance of at least `value`.
         * - the called Solidity function must be `payable`.
         *
         * _Available since v3.1._
         */
        function functionCallWithValue(
            address target,
            bytes memory data,
            uint256 value
        ) internal returns (bytes memory) {
            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
        }
        /**
         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
         * with `errorMessage` as a fallback revert reason when `target` reverts.
         *
         * _Available since v3.1._
         */
        function functionCallWithValue(
            address target,
            bytes memory data,
            uint256 value,
            string memory errorMessage
        ) internal returns (bytes memory) {
            require(address(this).balance >= value, "Address: insufficient balance for call");
            require(isContract(target), "Address: call to non-contract");
            (bool success, bytes memory returndata) = target.call{value: value}(data);
            return verifyCallResult(success, returndata, errorMessage);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but performing a static call.
         *
         * _Available since v3.3._
         */
        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
            return functionStaticCall(target, data, "Address: low-level static call failed");
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
         * but performing a static call.
         *
         * _Available since v3.3._
         */
        function functionStaticCall(
            address target,
            bytes memory data,
            string memory errorMessage
        ) internal view returns (bytes memory) {
            require(isContract(target), "Address: static call to non-contract");
            (bool success, bytes memory returndata) = target.staticcall(data);
            return verifyCallResult(success, returndata, errorMessage);
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
         * but performing a delegate call.
         *
         * _Available since v3.4._
         */
        function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
            return functionDelegateCall(target, data, "Address: low-level delegate call failed");
        }
        /**
         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
         * but performing a delegate call.
         *
         * _Available since v3.4._
         */
        function functionDelegateCall(
            address target,
            bytes memory data,
            string memory errorMessage
        ) internal returns (bytes memory) {
            require(isContract(target), "Address: delegate call to non-contract");
            (bool success, bytes memory returndata) = target.delegatecall(data);
            return verifyCallResult(success, returndata, errorMessage);
        }
        /**
         * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
         * revert reason using the provided one.
         *
         * _Available since v4.3._
         */
        function verifyCallResult(
            bool success,
            bytes memory returndata,
            string memory errorMessage
        ) internal pure returns (bytes memory) {
            if (success) {
                return returndata;
            } else {
                // Look for revert reason and bubble it up if present
                if (returndata.length > 0) {
                    // The easiest way to bubble the revert reason is using memory via assembly
                    /// @solidity memory-safe-assembly
                    assembly {
                        let returndata_size := mload(returndata)
                        revert(add(32, returndata), returndata_size)
                    }
                } else {
                    revert(errorMessage);
                }
            }
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev String operations.
     */
    library Strings {
        bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
        uint8 private constant _ADDRESS_LENGTH = 20;
        /**
         * @dev Converts a `uint256` to its ASCII `string` decimal representation.
         */
        function toString(uint256 value) internal pure returns (string memory) {
            // Inspired by OraclizeAPI's implementation - MIT licence
            // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
            if (value == 0) {
                return "0";
            }
            uint256 temp = value;
            uint256 digits;
            while (temp != 0) {
                digits++;
                temp /= 10;
            }
            bytes memory buffer = new bytes(digits);
            while (value != 0) {
                digits -= 1;
                buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                value /= 10;
            }
            return string(buffer);
        }
        /**
         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
         */
        function toHexString(uint256 value) internal pure returns (string memory) {
            if (value == 0) {
                return "0x00";
            }
            uint256 temp = value;
            uint256 length = 0;
            while (temp != 0) {
                length++;
                temp >>= 8;
            }
            return toHexString(value, length);
        }
        /**
         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
         */
        function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
            bytes memory buffer = new bytes(2 * length + 2);
            buffer[0] = "0";
            buffer[1] = "x";
            for (uint256 i = 2 * length + 1; i > 1; --i) {
                buffer[i] = _HEX_SYMBOLS[value & 0xf];
                value >>= 4;
            }
            require(value == 0, "Strings: hex length insufficient");
            return string(buffer);
        }
        /**
         * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
         */
        function toHexString(address addr) internal pure returns (string memory) {
            return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
    pragma solidity ^0.8.0;
    import "./IERC165.sol";
    /**
     * @dev Implementation of the {IERC165} interface.
     *
     * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
     * for the additional interface id that will be supported. For example:
     *
     * ```solidity
     * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
     *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
     * }
     * ```
     *
     * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
     */
    abstract contract ERC165 is IERC165 {
        /**
         * @dev See {IERC165-supportsInterface}.
         */
        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
            return interfaceId == type(IERC165).interfaceId;
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Interface of the ERC165 standard, as defined in the
     * https://eips.ethereum.org/EIPS/eip-165[EIP].
     *
     * Implementers can declare support of contract interfaces, which can then be
     * queried by others ({ERC165Checker}).
     *
     * For an implementation, see {ERC165}.
     */
    interface IERC165 {
        /**
         * @dev Returns true if this contract implements the interface defined by
         * `interfaceId`. See the corresponding
         * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
         * to learn more about how these ids are created.
         *
         * This function call must use less than 30 000 gas.
         */
        function supportsInterface(bytes4 interfaceId) external view returns (bool);
    }
    

    File 2 of 3: SimpleToken
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.10;
    import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
    contract SimpleToken is ERC20 {
        constructor(
            string memory name,
            string memory symbol,
            uint256 totalSupply_
        ) ERC20(name, symbol) {
            _mint(msg.sender, totalSupply_);
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Provides information about the current execution context, including the
     * sender of the transaction and its data. While these are generally available
     * via msg.sender and msg.data, they should not be accessed in such a direct
     * manner, since when dealing with meta-transactions the account sending and
     * paying for execution may not be the actual sender (as far as an application
     * is concerned).
     *
     * This contract is only required for intermediate, library-like contracts.
     */
    abstract contract Context {
        function _msgSender() internal view virtual returns (address) {
            return msg.sender;
        }
        function _msgData() internal view virtual returns (bytes calldata) {
            return msg.data;
        }
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
    pragma solidity ^0.8.0;
    import "../IERC20.sol";
    /**
     * @dev Interface for the optional metadata functions from the ERC20 standard.
     *
     * _Available since v4.1._
     */
    interface IERC20Metadata is IERC20 {
        /**
         * @dev Returns the name of the token.
         */
        function name() external view returns (string memory);
        /**
         * @dev Returns the symbol of the token.
         */
        function symbol() external view returns (string memory);
        /**
         * @dev Returns the decimals places of the token.
         */
        function decimals() external view returns (uint8);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
    pragma solidity ^0.8.0;
    /**
     * @dev Interface of the ERC20 standard as defined in the EIP.
     */
    interface IERC20 {
        /**
         * @dev Returns the amount of tokens in existence.
         */
        function totalSupply() external view returns (uint256);
        /**
         * @dev Returns the amount of tokens owned by `account`.
         */
        function balanceOf(address account) external view returns (uint256);
        /**
         * @dev Moves `amount` tokens from the caller's account to `recipient`.
         *
         * Returns a boolean value indicating whether the operation succeeded.
         *
         * Emits a {Transfer} event.
         */
        function transfer(address recipient, uint256 amount) external returns (bool);
        /**
         * @dev Returns the remaining number of tokens that `spender` will be
         * allowed to spend on behalf of `owner` through {transferFrom}. This is
         * zero by default.
         *
         * This value changes when {approve} or {transferFrom} are called.
         */
        function allowance(address owner, address spender) external view returns (uint256);
        /**
         * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
         *
         * Returns a boolean value indicating whether the operation succeeded.
         *
         * IMPORTANT: Beware that changing an allowance with this method brings the risk
         * that someone may use both the old and the new allowance by unfortunate
         * transaction ordering. One possible solution to mitigate this race
         * condition is to first reduce the spender's allowance to 0 and set the
         * desired value afterwards:
         * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
         *
         * Emits an {Approval} event.
         */
        function approve(address spender, uint256 amount) external returns (bool);
        /**
         * @dev Moves `amount` tokens from `sender` to `recipient` using the
         * allowance mechanism. `amount` is then deducted from the caller's
         * allowance.
         *
         * Returns a boolean value indicating whether the operation succeeded.
         *
         * Emits a {Transfer} event.
         */
        function transferFrom(
            address sender,
            address recipient,
            uint256 amount
        ) external returns (bool);
        /**
         * @dev Emitted when `value` tokens are moved from one account (`from`) to
         * another (`to`).
         *
         * Note that `value` may be zero.
         */
        event Transfer(address indexed from, address indexed to, uint256 value);
        /**
         * @dev Emitted when the allowance of a `spender` for an `owner` is set by
         * a call to {approve}. `value` is the new allowance.
         */
        event Approval(address indexed owner, address indexed spender, uint256 value);
    }
    // SPDX-License-Identifier: MIT
    // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
    pragma solidity ^0.8.0;
    import "./IERC20.sol";
    import "./extensions/IERC20Metadata.sol";
    import "../../utils/Context.sol";
    /**
     * @dev Implementation of the {IERC20} interface.
     *
     * This implementation is agnostic to the way tokens are created. This means
     * that a supply mechanism has to be added in a derived contract using {_mint}.
     * For a generic mechanism see {ERC20PresetMinterPauser}.
     *
     * TIP: For a detailed writeup see our guide
     * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
     * to implement supply mechanisms].
     *
     * We have followed general OpenZeppelin Contracts guidelines: functions revert
     * instead returning `false` on failure. This behavior is nonetheless
     * conventional and does not conflict with the expectations of ERC20
     * applications.
     *
     * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
     * This allows applications to reconstruct the allowance for all accounts just
     * by listening to said events. Other implementations of the EIP may not emit
     * these events, as it isn't required by the specification.
     *
     * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
     * functions have been added to mitigate the well-known issues around setting
     * allowances. See {IERC20-approve}.
     */
    contract ERC20 is Context, IERC20, IERC20Metadata {
        mapping(address => uint256) private _balances;
        mapping(address => mapping(address => uint256)) private _allowances;
        uint256 private _totalSupply;
        string private _name;
        string private _symbol;
        /**
         * @dev Sets the values for {name} and {symbol}.
         *
         * The default value of {decimals} is 18. To select a different value for
         * {decimals} you should overload it.
         *
         * All two of these values are immutable: they can only be set once during
         * construction.
         */
        constructor(string memory name_, string memory symbol_) {
            _name = name_;
            _symbol = symbol_;
        }
        /**
         * @dev Returns the name of the token.
         */
        function name() public view virtual override returns (string memory) {
            return _name;
        }
        /**
         * @dev Returns the symbol of the token, usually a shorter version of the
         * name.
         */
        function symbol() public view virtual override returns (string memory) {
            return _symbol;
        }
        /**
         * @dev Returns the number of decimals used to get its user representation.
         * For example, if `decimals` equals `2`, a balance of `505` tokens should
         * be displayed to a user as `5.05` (`505 / 10 ** 2`).
         *
         * Tokens usually opt for a value of 18, imitating the relationship between
         * Ether and Wei. This is the value {ERC20} uses, unless this function is
         * overridden;
         *
         * NOTE: This information is only used for _display_ purposes: it in
         * no way affects any of the arithmetic of the contract, including
         * {IERC20-balanceOf} and {IERC20-transfer}.
         */
        function decimals() public view virtual override returns (uint8) {
            return 18;
        }
        /**
         * @dev See {IERC20-totalSupply}.
         */
        function totalSupply() public view virtual override returns (uint256) {
            return _totalSupply;
        }
        /**
         * @dev See {IERC20-balanceOf}.
         */
        function balanceOf(address account) public view virtual override returns (uint256) {
            return _balances[account];
        }
        /**
         * @dev See {IERC20-transfer}.
         *
         * Requirements:
         *
         * - `recipient` cannot be the zero address.
         * - the caller must have a balance of at least `amount`.
         */
        function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
            _transfer(_msgSender(), recipient, amount);
            return true;
        }
        /**
         * @dev See {IERC20-allowance}.
         */
        function allowance(address owner, address spender) public view virtual override returns (uint256) {
            return _allowances[owner][spender];
        }
        /**
         * @dev See {IERC20-approve}.
         *
         * Requirements:
         *
         * - `spender` cannot be the zero address.
         */
        function approve(address spender, uint256 amount) public virtual override returns (bool) {
            _approve(_msgSender(), spender, amount);
            return true;
        }
        /**
         * @dev See {IERC20-transferFrom}.
         *
         * Emits an {Approval} event indicating the updated allowance. This is not
         * required by the EIP. See the note at the beginning of {ERC20}.
         *
         * Requirements:
         *
         * - `sender` and `recipient` cannot be the zero address.
         * - `sender` must have a balance of at least `amount`.
         * - the caller must have allowance for ``sender``'s tokens of at least
         * `amount`.
         */
        function transferFrom(
            address sender,
            address recipient,
            uint256 amount
        ) public virtual override returns (bool) {
            _transfer(sender, recipient, amount);
            uint256 currentAllowance = _allowances[sender][_msgSender()];
            require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
            unchecked {
                _approve(sender, _msgSender(), currentAllowance - amount);
            }
            return true;
        }
        /**
         * @dev Atomically increases the allowance granted to `spender` by the caller.
         *
         * This is an alternative to {approve} that can be used as a mitigation for
         * problems described in {IERC20-approve}.
         *
         * Emits an {Approval} event indicating the updated allowance.
         *
         * Requirements:
         *
         * - `spender` cannot be the zero address.
         */
        function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
            _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
            return true;
        }
        /**
         * @dev Atomically decreases the allowance granted to `spender` by the caller.
         *
         * This is an alternative to {approve} that can be used as a mitigation for
         * problems described in {IERC20-approve}.
         *
         * Emits an {Approval} event indicating the updated allowance.
         *
         * Requirements:
         *
         * - `spender` cannot be the zero address.
         * - `spender` must have allowance for the caller of at least
         * `subtractedValue`.
         */
        function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
            uint256 currentAllowance = _allowances[_msgSender()][spender];
            require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
            unchecked {
                _approve(_msgSender(), spender, currentAllowance - subtractedValue);
            }
            return true;
        }
        /**
         * @dev Moves `amount` of tokens from `sender` to `recipient`.
         *
         * This internal function is equivalent to {transfer}, and can be used to
         * e.g. implement automatic token fees, slashing mechanisms, etc.
         *
         * Emits a {Transfer} event.
         *
         * Requirements:
         *
         * - `sender` cannot be the zero address.
         * - `recipient` cannot be the zero address.
         * - `sender` must have a balance of at least `amount`.
         */
        function _transfer(
            address sender,
            address recipient,
            uint256 amount
        ) internal virtual {
            require(sender != address(0), "ERC20: transfer from the zero address");
            require(recipient != address(0), "ERC20: transfer to the zero address");
            _beforeTokenTransfer(sender, recipient, amount);
            uint256 senderBalance = _balances[sender];
            require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
            unchecked {
                _balances[sender] = senderBalance - amount;
            }
            _balances[recipient] += amount;
            emit Transfer(sender, recipient, amount);
            _afterTokenTransfer(sender, recipient, amount);
        }
        /** @dev Creates `amount` tokens and assigns them to `account`, increasing
         * the total supply.
         *
         * Emits a {Transfer} event with `from` set to the zero address.
         *
         * Requirements:
         *
         * - `account` cannot be the zero address.
         */
        function _mint(address account, uint256 amount) internal virtual {
            require(account != address(0), "ERC20: mint to the zero address");
            _beforeTokenTransfer(address(0), account, amount);
            _totalSupply += amount;
            _balances[account] += amount;
            emit Transfer(address(0), account, amount);
            _afterTokenTransfer(address(0), account, amount);
        }
        /**
         * @dev Destroys `amount` tokens from `account`, reducing the
         * total supply.
         *
         * Emits a {Transfer} event with `to` set to the zero address.
         *
         * Requirements:
         *
         * - `account` cannot be the zero address.
         * - `account` must have at least `amount` tokens.
         */
        function _burn(address account, uint256 amount) internal virtual {
            require(account != address(0), "ERC20: burn from the zero address");
            _beforeTokenTransfer(account, address(0), amount);
            uint256 accountBalance = _balances[account];
            require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
            unchecked {
                _balances[account] = accountBalance - amount;
            }
            _totalSupply -= amount;
            emit Transfer(account, address(0), amount);
            _afterTokenTransfer(account, address(0), amount);
        }
        /**
         * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
         *
         * This internal function is equivalent to `approve`, and can be used to
         * e.g. set automatic allowances for certain subsystems, etc.
         *
         * Emits an {Approval} event.
         *
         * Requirements:
         *
         * - `owner` cannot be the zero address.
         * - `spender` cannot be the zero address.
         */
        function _approve(
            address owner,
            address spender,
            uint256 amount
        ) internal virtual {
            require(owner != address(0), "ERC20: approve from the zero address");
            require(spender != address(0), "ERC20: approve to the zero address");
            _allowances[owner][spender] = amount;
            emit Approval(owner, spender, amount);
        }
        /**
         * @dev Hook that is called before any transfer of tokens. This includes
         * minting and burning.
         *
         * Calling conditions:
         *
         * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
         * will be transferred to `to`.
         * - when `from` is zero, `amount` tokens will be minted for `to`.
         * - when `to` is zero, `amount` of ``from``'s tokens 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 amount
        ) internal virtual {}
        /**
         * @dev Hook that is called after any transfer of tokens. This includes
         * minting and burning.
         *
         * Calling conditions:
         *
         * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
         * has been transferred to `to`.
         * - when `from` is zero, `amount` tokens have been minted for `to`.
         * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
            address from,
            address to,
            uint256 amount
        ) internal virtual {}
    }
    

    File 3 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;
        }
    }