Skip to content
Verified contractPartialMIT

NFTMasterChefBatch

Address0x5d9e2a79fab2b31eceaee13167e2ac9b4440c257
Balance

0 ETH

 

Transactions

14

 

Compiler

solc 0.8.10

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.10+commit.fc410830
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
15,230,350
Creation transaction
0x39d2edca29…f911b8cd53

NFTMasterChefBatch.sol

// ░██████╗████████╗░█████╗░██████╗░██████╗░██╗░░░░░░█████╗░░█████╗░██╗░░██╗
// ██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗██║░░░░░██╔══██╗██╔══██╗██║░██╔╝
// ╚█████╗░░░░██║░░░███████║██████╔╝██████╦╝██║░░░░░██║░░██║██║░░╚═╝█████═╝░
// ░╚═══██╗░░░██║░░░██╔══██║██╔══██╗██╔══██╗██║░░░░░██║░░██║██║░░██╗██╔═██╗░
// ██████╔╝░░░██║░░░██║░░██║██║░░██║██████╦╝███████╗╚█████╔╝╚█████╔╝██║░╚██╗
// ╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝╚═════╝░╚══════╝░╚════╝░░╚════╝░╚═╝░░╚═╝

// SPDX-License-Identifier: MIT
// StarBlock DAO Contracts, https://www.starblockdao.io/

pragma solidity ^0.8.0;

import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./Ownable.sol";
import "./ReentrancyGuard.sol";

import "./NFTMasterChef_interfaces.sol";

contract NFTMasterChefBatch is INFTMasterChefBatch, Ownable, ReentrancyGuard {
    INFTPool public immutable nftPool;
    INFTMasterChef public immutable nftMasterChef;
    ITokenPriceUtils public tokenPriceUtils;//tokenPriceUtils Contract of $STB

    ICollectionUtils public collectionUtils;

    IERC20 public immutable weth;
    
    struct WrappedPoolInfo {
        uint256 pid;
        INFTMasterChef.PoolInfo poolInfo;
        INFTMasterChef.RewardInfo currentReward;
        UserInfo userInfo;
        uint256 currentRewardIndex;
        uint256 currentRewardEndBlock;
        uint256 endBlock;
        IERC721Metadata nft;
        INFTMasterChef.RewardInfo[] rewards;

        uint256 rewardedToken;
        uint256 rewardedDividend;
    }
   
    struct UserInfo {
        uint256 ethBalance;
        uint256 wethBalance;
        uint256 tokenBalance;

        uint256 mining;
        uint256 dividend;
        uint256 nftQuantity;
        uint256 wnftQuantity;
        bool isNFTApproved;
        bool isWNFTApproved;

        uint256[] ownedNFTTokenIds;
        uint256[] ownedWNFTTokenIds;
    }

    struct PoolSta {
        uint256 blockNumber;
        uint256 blockTime;
        uint256 tokenPrice;
        uint256 totalPoolAmount;
        uint256 totalNFTAmount;
        uint256 totalRewardedToken;
        uint256 totalRewardedDividend;
    }

    struct NFTDepositInfo {
        uint256 tokenId;
        address owner;
        bool deposited;// Is it deposited in NFTMasterChef
        uint256 mining;
        uint256 dividend;
        bool withdrawedInWNFT;// Is it withdrawed from WNFT contract
    }

    mapping(uint256 => uint256) poolDividends;

    constructor(ICollectionUtils _collectionUtils, INFTPool _nftPool, ITokenPriceUtils _tokenPriceUtils, IERC20 _weth) {
        require(address(_collectionUtils) != address(0) && address(_nftPool) != address(0), "Batch: error!");
        collectionUtils = _collectionUtils;

        nftPool = _nftPool;
        nftMasterChef = _nftPool.nftMasterChef();
        require(address(nftMasterChef) != address(0), "Batch: error!");
        
        tokenPriceUtils = _tokenPriceUtils;
        weth = _weth;
    }
    
    function setCollectionUtils(ICollectionUtils _collectionUtils) external onlyOwner nonReentrant {
        require(address(_collectionUtils) != address(0), "Batch: _collectionUtils can not be zero!");
        collectionUtils = _collectionUtils;
    }
   
    function setTokenPriceUtils(ITokenPriceUtils _tokenPriceUtils) external onlyOwner nonReentrant {
        require(address(_tokenPriceUtils) != address(0), "Batch: _tokenPriceUtils can not be zero!");
        tokenPriceUtils = _tokenPriceUtils;
    }

    function getTokenPrice() public view returns (uint256) {
        if(address(tokenPriceUtils) != address(0)){
            return tokenPriceUtils.getTokenPrice(address(nftMasterChef.token()));
        }
        return 0;
    }
    
    function addPoolDividends(uint256[] memory _pids, uint256[] memory _dividends) external onlyOwner nonReentrant {
        require(_pids.length > 0 && (_pids.length == _dividends.length), "Batch: error!");
        for(uint256 index = 0; index < _pids.length; index ++){
            poolDividends[_pids[index]] += _dividends[index];
        }
    }

    function getPoolSta(address _user, bool _withPoolInfo) external view returns (PoolSta memory _poolSta, UserInfo memory _userInfo, WrappedPoolInfo[] memory _wrappedPoolInfos) {
        _poolSta.blockNumber = block.number;
        _poolSta.blockTime = block.timestamp;
        _poolSta.tokenPrice = getTokenPrice();
        _poolSta.totalPoolAmount = nftMasterChef.poolLength();
        if(_user != address(0)){
            _userInfo.ethBalance = _user.balance;
            if(address(weth) != address(0)){
                _userInfo.wethBalance = weth.balanceOf(_user);
            }
            _userInfo.tokenBalance = nftMasterChef.token().balanceOf(_user);
        }
        if(_withPoolInfo){
            _wrappedPoolInfos = new WrappedPoolInfo[](_poolSta.totalPoolAmount);
        }
        for(uint256 pid = 0; pid < _poolSta.totalPoolAmount; pid ++){
            WrappedPoolInfo memory _wrappedPoolInfo = getPoolInfo(pid, _user, false);
            if(_withPoolInfo){
                _wrappedPoolInfos[pid] = _wrappedPoolInfo;
            }
            _poolSta.totalNFTAmount += _wrappedPoolInfo.poolInfo.amount;
            _poolSta.totalRewardedToken += _wrappedPoolInfo.rewardedToken;
            _poolSta.totalRewardedDividend += _wrappedPoolInfo.rewardedDividend;

            if(_user != address(0)){
                UserInfo memory userInfo = _wrappedPoolInfo.userInfo;
                _userInfo.mining += userInfo.mining;
                _userInfo.dividend += userInfo.dividend;
                _userInfo.nftQuantity += userInfo.nftQuantity;
                _userInfo.wnftQuantity += userInfo.wnftQuantity;
            }
        }
    }

    function getAllPoolInfos(address _user, bool _canDeposite, bool _deposited) external view returns (WrappedPoolInfo[] memory _wrappedPoolInfos) {
        if(_user == address(0)){
            _canDeposite = false;
            _deposited = false;
        }
        uint256 maxPid = nftMasterChef.poolLength() - 1;
        if(maxPid > 0){
            uint256 number;
            if(!_canDeposite && !_deposited){
                number = maxPid + 1;
            }else{
                for(uint256 pid = 0; pid <= maxPid; pid ++){
                    IWrappedNFT wnft = nftMasterChef.poolInfos(pid).wnft;
                    if((_canDeposite && wnft.nft().balanceOf(_user) > 0) 
                        || (_deposited && wnft.balanceOf(_user) > 0)){
                        number ++;
                    }
                }
            }
            if(number > 0){
                _wrappedPoolInfos = new WrappedPoolInfo[](number);
                uint256 index = 0;
                for(uint256 pid = 0; pid <= maxPid; pid ++){
                    IWrappedNFT wnft = nftMasterChef.poolInfos(pid).wnft;
                    if((!_canDeposite && !_deposited) 
                        || (_canDeposite && wnft.nft().balanceOf(_user) > 0) 
                        || (_deposited && wnft.balanceOf(_user) > 0)){
                        _wrappedPoolInfos[index] = getPoolInfo(pid, _user, false);
                        index ++;
                    }
                }
            }
        }
    }

    function getPoolInfo(uint256 _pid, address _user, bool _withOwnedTokenIds) public view returns (WrappedPoolInfo memory _wrappedPoolInfo) {
        require(_pid < nftMasterChef.poolLength(), "Batch: error!");
        _wrappedPoolInfo.pid = _pid;
        _wrappedPoolInfo.poolInfo = nftMasterChef.poolInfos(_pid);
        _wrappedPoolInfo.endBlock = nftMasterChef.getPoolEndBlock(_pid);
        _wrappedPoolInfo.nft = _wrappedPoolInfo.poolInfo.wnft.nft();
        _wrappedPoolInfo.rewards = getPoolRewards(_pid);
        (_wrappedPoolInfo.rewardedToken, _wrappedPoolInfo.rewardedDividend) = poolRewarded(_pid);

        _wrappedPoolInfo.currentRewardIndex = _wrappedPoolInfo.poolInfo.currentRewardIndex;
        _wrappedPoolInfo.currentRewardEndBlock = _wrappedPoolInfo.poolInfo.currentRewardEndBlock;
        uint256 poolRewardNumber = _wrappedPoolInfo.rewards.length;
        _wrappedPoolInfo.currentReward = _wrappedPoolInfo.rewards[_wrappedPoolInfo.currentRewardIndex];
        // Check whether to adjust multipliers and reward per block
        while ((block.number > _wrappedPoolInfo.currentRewardEndBlock) && (_wrappedPoolInfo.currentRewardIndex < (poolRewardNumber - 1))) {
            // Update rewards per block
            _wrappedPoolInfo.currentRewardIndex ++;
            _wrappedPoolInfo.currentReward = _wrappedPoolInfo.rewards[_wrappedPoolInfo.currentRewardIndex];
            // Adjust the end block
            _wrappedPoolInfo.currentRewardEndBlock += _wrappedPoolInfo.currentReward.rewardBlock;
        }

        if (_user != address(0)) {
            _wrappedPoolInfo.userInfo = getUserInfo(_pid, _user, _withOwnedTokenIds);
        }
    }

    function pending(uint256 _pid, uint256[] memory _wnftTokenIds) public view returns (uint256 _mining, uint256 _dividend){
        (_mining, _dividend) = nftPool.pending(_pid, _wnftTokenIds);
    }

    function getUserInfo(uint256 _pid, address _user, bool _withOwnedTokenIds) public view returns (UserInfo memory _userInfo) {
        require(_pid < nftMasterChef.poolLength(), "Batch: error!");
        if (_user != address(0)) {
            IWrappedNFT wnft = nftMasterChef.poolInfos(_pid).wnft;
            uint256[] memory ownedWNFTTokenIds = collectionUtils.ownedNFTTokenIds(wnft, _user);
            if (ownedWNFTTokenIds.length > 0) {
                (_userInfo.mining, _userInfo.dividend) = pending(_pid, ownedWNFTTokenIds);
            }
            _userInfo.nftQuantity = wnft.nft().balanceOf(_user);
            _userInfo.wnftQuantity = wnft.balanceOf(_user);
            _userInfo.isNFTApproved = wnft.nft().isApprovedForAll(_user, address(wnft));
            _userInfo.isWNFTApproved = wnft.isApprovedForAll(_user, address(nftMasterChef));

            if(_withOwnedTokenIds){
                _userInfo.ownedNFTTokenIds = collectionUtils.ownedNFTTokenIds(wnft.nft(), _user);
                _userInfo.ownedWNFTTokenIds = ownedWNFTTokenIds;
            }
       }
    }
    
    function getPoolInfosByPids(uint256[] memory _pids, address _user, bool _withOwnedTokenIds) external view returns (WrappedPoolInfo[] memory _wrappedPoolInfos) {
        require(_pids.length > 0, "Batch: error!");
        _wrappedPoolInfos = new WrappedPoolInfo[](_pids.length);
        for(uint256 index = 0; index < _pids.length; index ++){
            _wrappedPoolInfos[index] = getPoolInfo(_pids[index], _user, _withOwnedTokenIds);
        }
    }

    function getPoolInfosUserCanDeposit(address _user, bool _withOwnedTokenIds) external view returns (WrappedPoolInfo[] memory _wrappedPoolInfos) {
    	require(nftMasterChef.poolLength() > 0 && _user != address(0), "Batch: error!");
    	uint256 maxPid = nftMasterChef.poolLength() - 1;

        uint256 number;
        for(uint256 pid = 0; pid <= maxPid; pid ++){
        	IWrappedNFT wnft = nftMasterChef.poolInfos(pid).wnft;
        	if(wnft.nft().balanceOf(_user) > 0){
        		number ++;
        	}
        }
        if(number > 0){
            _wrappedPoolInfos = new WrappedPoolInfo[](number);
            uint256 index = 0;
            for(uint256 pid = 0; pid <= maxPid; pid ++){
                IWrappedNFT wnft = nftMasterChef.poolInfos(pid).wnft;
                if(wnft.nft().balanceOf(_user) > 0){
                    _wrappedPoolInfos[index] = getPoolInfo(pid, _user, _withOwnedTokenIds);
                    index ++;
                }
            }
        }
    }

    function getPoolInfosUserDeposited(address _user, bool _withOwnedTokenIds) external view returns (WrappedPoolInfo[] memory _wrappedPoolInfos) {
    	require(nftMasterChef.poolLength() > 0 && _user != address(0), "Batch: error!");
    	uint256 maxPid = nftMasterChef.poolLength() - 1;

        uint256 number;
        for(uint256 pid = 0; pid <= maxPid; pid ++){
        	IWrappedNFT wnft = nftMasterChef.poolInfos(pid).wnft;
        	if(wnft.balanceOf(_user) > 0){
        		number ++;
        	}
        }

        if(number > 0){
            _wrappedPoolInfos = new WrappedPoolInfo[](number);
            uint256 index = 0;
            for(uint256 pid = 0; pid <= maxPid; pid ++){
                IWrappedNFT wnft = nftMasterChef.poolInfos(pid).wnft;
                if(wnft.balanceOf(_user) > 0){
                    _wrappedPoolInfos[index] = getPoolInfo(pid, _user, _withOwnedTokenIds);
                    index ++;
                }
            }
        }
    }

    function getPoolInfosByNFTorWNFTs(IERC721Metadata[] memory _nftOrWNFTs, address _user, bool _withOwnedTokenIds) 
            external view returns (WrappedPoolInfo[] memory _wrappedPoolInfos) {
        require(_nftOrWNFTs.length > 0, "Batch: error!");
        _wrappedPoolInfos = new WrappedPoolInfo[](_nftOrWNFTs.length);
        for(uint256 index = 0; index < _nftOrWNFTs.length; index ++){
            IERC721Metadata nft = _nftOrWNFTs[index];
            (bool poolExists, uint256 pid) = nftPoolExists(nft);
            if(poolExists){
                _wrappedPoolInfos[index] = getPoolInfo(pid, _user, _withOwnedTokenIds);
            }
        }
    }

    function getPoolsDepositedNFTs(uint256[] memory _pids) external view returns (NFTDepositInfo[][] memory _nftInfos) {
        require(_pids.length > 0, "Batch: error!");
        _nftInfos = new NFTDepositInfo[][](_pids.length);
        for(uint256 index = 0; index < _pids.length; index ++){
            _nftInfos[index] = getPoolDepositedNFTs(_pids[index]);
        }
    }

    function getPoolDepositedNFTs(uint256 _pid) public view returns (NFTDepositInfo[] memory _nftInfos) {
        require(_pid < nftMasterChef.poolLength(), "Batch: error!");
        INFTMasterChef.PoolInfo memory poolInfo = nftMasterChef.poolInfos(_pid);
        if(poolInfo.amount > 0){
            _nftInfos = new NFTDepositInfo[](poolInfo.amount);

            IERC721 nft = poolInfo.wnft.nft();
            (uint256 minTokenId, uint256 maxTokenId) = collectionUtils.tokenIdRangeMay(nft);
            uint256 index = 0;
            for (uint256 tokenId = minTokenId; tokenId <= maxTokenId; tokenId ++) {
                if (collectionUtils.tokenIdExistsMay(nft, tokenId)) {
                    INFTMasterChef.NFTInfo memory nftInfo = nftMasterChef.poolNFTInfos(_pid, tokenId);
                    if(nftInfo.deposited == true){
                        _nftInfos[index].tokenId = tokenId;
                        _nftInfos[index].owner = nft.ownerOf(tokenId);
                        _nftInfos[index].deposited = true;
                        uint256[] memory wnftTokenIds = new uint256[](1);
                        wnftTokenIds[0] = tokenId;
                        (_nftInfos[index].mining, _nftInfos[index].dividend) = pending(_pid, wnftTokenIds);
                        _nftInfos[index].withdrawedInWNFT = (address(_nftInfos[index].owner) != address(poolInfo.wnft));
                        index ++;
                    }
                }
            }
        }
    }
   
    function getPoolsRewards(uint256[] memory _pids) external view returns (INFTMasterChef.RewardInfo[][] memory _rewards) {
        require(_pids.length > 0, "Batch: error!");
        _rewards = new INFTMasterChef.RewardInfo[][](_pids.length);
        for(uint256 index = 0; index < _pids.length; index ++){
            _rewards[index] = getPoolRewards(_pids[index]);
        }
    }
   
    function getPoolRewards(uint256 _pid) public view returns (INFTMasterChef.RewardInfo[] memory _rewards) {
        uint256 rewardLength = nftMasterChef.poolRewardLength(_pid);
        _rewards = new INFTMasterChef.RewardInfo[](rewardLength);
        for(uint256 rewardIndex = 0; rewardIndex < rewardLength; rewardIndex ++){
        	INFTMasterChef.RewardInfo memory reward = nftMasterChef.poolsRewardInfos(_pid, rewardIndex);
            _rewards[rewardIndex] = reward;
        }
    }

    //_nftOrWNFT can be NFT or WNFT
    function getPoolInfoByNFT(IERC721Metadata _nftOrWNFT, address _user, bool _withOwnedTokenIds) external view returns (WrappedPoolInfo memory _wrappedPoolInfo) {
        require(address(_nftOrWNFT) != address(0), "Batch: error!");
        (bool poolExists, uint256 pid) = nftPoolExists(_nftOrWNFT);
        if(poolExists){
            _wrappedPoolInfo = getPoolInfo(pid, _user, _withOwnedTokenIds);
        }
    }

    //_nftOrWNFT can be NFT or WNFT
    function nftPoolId(IERC721Metadata _nftOrWNFT) public view returns (uint256 _pid) {
        require(address(_nftOrWNFT) != address(0), "Batch: error!");
        for(_pid = 0; _pid < nftMasterChef.poolLength(); _pid ++){
            INFTMasterChef.PoolInfo memory poolInfo = nftMasterChef.poolInfos(_pid);
            if(poolInfo.wnft == _nftOrWNFT || poolInfo.wnft.nft() == _nftOrWNFT){
                return _pid;
            }
        }
        return nftMasterChef.poolLength();
    }

    //_nftOrWNFT can be NFT or WNFT
    function nftPoolExists(IERC721Metadata _nftOrWNFT) public view returns (bool _poolExists, uint256 _pid) {
        require(address(_nftOrWNFT) != address(0), "Batch: error!");
        _pid = nftPoolId(_nftOrWNFT);
        _poolExists = _pid < nftMasterChef.poolLength();
    }

    //the total unharvest reward for one pool
    function poolPending(uint256 _pid) external view returns (uint256 _mining, uint256 _dividend, uint256[] memory _wnftTokenIds) {
        require(_pid < nftMasterChef.poolLength(), "Batch: error!");
        INFTMasterChef.PoolInfo memory poolInfo = nftMasterChef.poolInfos(_pid);
        if(poolInfo.amount > 0){
            _wnftTokenIds = collectionUtils.ownedNFTTokenIds(poolInfo.wnft.nft(), address(poolInfo.wnft));
            if(_wnftTokenIds.length > 0){
                (_mining, _dividend) = pending(_pid, _wnftTokenIds);
            }
        }
    }

    //the rewarded STB and dividend for one pool, calculate by the rewards
    function poolRewarded(uint256 _pid) public view returns (uint256 _mining, uint256 _dividend) {
        require(_pid < nftMasterChef.poolLength(), "Batch: error!");
        INFTMasterChef.PoolInfo memory poolInfo = nftMasterChef.poolInfos(_pid);
        INFTMasterChef.RewardInfo[] memory rewards = getPoolRewards(_pid);
        if(poolInfo.startBlock <= block.number && rewards.length > 0){
            uint256 startBlock = poolInfo.startBlock;
            for(uint256 index = 0; index < rewards.length; index ++){
                INFTMasterChef.RewardInfo memory reward = rewards[index];
                uint256 nextStartBlock = startBlock + reward.rewardBlock;
                if(nextStartBlock > block.number){
                    if(poolInfo.currentRewardEndBlock <= block.number){
                        _mining += (poolInfo.currentRewardEndBlock - startBlock) * reward.rewardForEachBlock;
                    }else{
                        _mining += (block.number - startBlock) * reward.rewardForEachBlock;
                    }
                    break;
                }else{
                    if(poolInfo.currentRewardEndBlock <= nextStartBlock){
                        _mining += (poolInfo.currentRewardEndBlock - startBlock) * reward.rewardForEachBlock;
                        if(poolInfo.currentRewardIndex == rewards.length - 1){
                            break;
                        }
                    }else{
                        _mining += reward.rewardBlock * reward.rewardForEachBlock;
                    }
                }
                startBlock = nextStartBlock;
            }
        }

        _dividend = poolDividends[_pid];
    }

    function pendingAll(address _forUser) external view returns (UserInfo memory _userInfo, uint256 _blockNumber, uint256 _blockTime) {
        require(_forUser != address(0), "Batch: error!");
        _blockNumber = block.number;
        _blockTime = block.timestamp;
        _userInfo.ethBalance = _forUser.balance;
        if(address(weth) != address(0)){
            _userInfo.wethBalance = weth.balanceOf(_forUser);
        }
        _userInfo.tokenBalance = nftMasterChef.token().balanceOf(_forUser);
        uint256 maxPid = nftMasterChef.poolLength() - 1;
        for(uint256 pid = 0; pid <= maxPid; pid ++){
            INFTMasterChef.PoolInfo memory poolInfo = nftMasterChef.poolInfos(pid);
            uint256[] memory wnftTokenIds = collectionUtils.ownedNFTTokenIds(poolInfo.wnft, _forUser);
            if (wnftTokenIds.length > 0) {
                UserInfo memory userInfo = getUserInfo(pid, _forUser, false);
                _userInfo.mining += userInfo.mining;
                _userInfo.dividend += userInfo.dividend;
                _userInfo.nftQuantity += userInfo.nftQuantity;
                _userInfo.wnftQuantity += userInfo.wnftQuantity;
            }
        }
    }
    
    function harvestAll(address _forUser) external returns (uint256 _mining, uint256 _dividend) {
        if(_forUser == address(0)){
        	_forUser = msg.sender;
        }
        uint256 maxPid = nftMasterChef.poolLength() - 1;
        for(uint256 pid = 0; pid <= maxPid; pid ++){
            INFTMasterChef.PoolInfo memory poolInfo = nftMasterChef.poolInfos(pid);
            uint256[] memory wnftTokenIds = collectionUtils.ownedNFTTokenIds(poolInfo.wnft, _forUser);
            if (wnftTokenIds.length > 0) {
                (uint256 mining, uint256 dividend) = nftMasterChef.harvest(pid, _forUser, wnftTokenIds);
                _mining += mining;
                _dividend += dividend;
            }
        }
    }

    function pendingByNFTorWNFT(IERC721Metadata _nftOrWNFT, uint256[] memory _poolWNFTTokenIds) external view 
            returns (bool _poolExists, uint256 _pid, uint256 _mining, uint256 _dividend) {
        require(address(_nftOrWNFT) != address(0) && _poolWNFTTokenIds.length > 0, "Batch: error!");
        (_poolExists, _pid) = nftPoolExists(_nftOrWNFT);
        if(_poolExists){
            if (_poolWNFTTokenIds.length > 0) {
                (_mining, _dividend) = pending(_pid, _poolWNFTTokenIds);
            }
        }
    }

    function harvestAllByWNFTTokenIds(address _forUser, uint256[] memory _pids, uint256[][] memory _poolWNFTTokenIds) external returns (uint256 _mining, uint256 _dividend) {
        require(_pids.length > 0 && _pids.length == _poolWNFTTokenIds.length, "Batch: error!");
        if(_forUser == address(0)){
        	_forUser = msg.sender;
        }
        for(uint256 index = 0; index < _pids.length; index ++){
            uint256 pid = _pids[index];
            uint256[] memory wnftTokenIds = _poolWNFTTokenIds[index];
            if (wnftTokenIds.length > 0) {
                (uint256 mining, uint256 dividend) = nftMasterChef.harvest(pid, _forUser, wnftTokenIds);
                _mining += mining;
                _dividend += dividend;
            }
        }
    }
    
    function ownedNFTsTokenIdsByPids(uint256[] memory _pids, address _user) external view returns (uint256[][] memory _ownedTokenIds) {
        require(_pids.length > 0, "Batch: error!");
        _ownedTokenIds = new uint256[][](_pids.length);
        uint256 poolLength = nftMasterChef.poolLength();
        for(uint256 index = 0; index < _pids.length; index ++){
            uint256 pid = _pids[index];
            require(pid < poolLength, "Batch: pid >= poolLength!");
            INFTMasterChef.PoolInfo memory poolInfo = nftMasterChef.poolInfos(pid);
            _ownedTokenIds[index] = ownedNFTTokenIds(poolInfo.wnft.nft(), _user);
        }
    }

    function ownedWNFTsTokenIdsByPids(uint256[] memory _pids, address _user) external view returns (uint256[][] memory _ownedTokenIds) {
        require(_pids.length > 0, "Batch: error!");
        _ownedTokenIds = new uint256[][](_pids.length);
        uint256 poolLength = nftMasterChef.poolLength();
        for(uint256 index = 0; index < _pids.length; index ++){
            uint256 pid = _pids[index];
            require(pid < poolLength, "Batch: pid >= poolLength!");
            INFTMasterChef.PoolInfo memory poolInfo = nftMasterChef.poolInfos(pid);
            _ownedTokenIds[index] = ownedNFTTokenIds(poolInfo.wnft, _user);
        }
    }

    function ownedNFTTokenIds(IERC721 _nft, address _user) public view returns (uint256[] memory _ownedTokenIds) {
        return collectionUtils.ownedNFTTokenIds(_nft, _user);
    }

    function nftShouldSetMaxTokenId(IERC721 _nft) public view returns (bool) {
        return !collectionUtils.canEnumerate(_nft);
    }

    //return the pids that should set maxTokenId
    function poolsShouldSetMaxTokenId() external view returns (uint256[] memory _pids, IERC721[] memory _nfts) {
    	uint256 maxPid = nftMasterChef.poolLength() - 1;
    	uint256 number;
        for(uint256 pid = 0; pid <= maxPid; pid ++){
            INFTMasterChef.PoolInfo memory poolInfo = nftMasterChef.poolInfos(pid);
            if(nftShouldSetMaxTokenId(poolInfo.wnft.nft())){
				number ++;
			}
        }
        if(number > 0){
        	_pids = new uint256[](number);
        	_nfts = new IERC721[](number);
			uint256 index;
			for(uint256 pid = 0; pid <= maxPid; pid ++){
				INFTMasterChef.PoolInfo memory poolInfo = nftMasterChef.poolInfos(pid);
				if(nftShouldSetMaxTokenId(poolInfo.wnft.nft())){
					_pids[index] = pid;
					_nfts[index] = poolInfo.wnft.nft();
					index ++;
				}
			}
        }
    }
}

Address.sol

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

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

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

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

Context.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

ERC165.sol

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

pragma solidity ^0.8.0;

import "./IERC165.sol";

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

ERC2981.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/common/ERC2981.sol)

pragma solidity ^0.8.0;

import "./IERC2981.sol";
import "./ERC165.sol";

/**
 * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
 *
 * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
 * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
 *
 * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
 * fee is specified in basis points by default.
 *
 * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
 * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
 * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
 *
 * _Available since v4.5._
 */
abstract contract ERC2981 is IERC2981, ERC165 {
    struct RoyaltyInfo {
        address receiver;
        uint96 royaltyFraction;
    }

    RoyaltyInfo private _defaultRoyaltyInfo;
    mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;

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

    /**
     * @inheritdoc IERC2981
     */
    function royaltyInfo(uint256 _tokenId, uint256 _salePrice) public view virtual override returns (address, uint256) {
        RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];

        if (royalty.receiver == address(0)) {
            royalty = _defaultRoyaltyInfo;
        }

        uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();

        return (royalty.receiver, royaltyAmount);
    }

    /**
     * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
     * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
     * override.
     */
    function _feeDenominator() internal pure virtual returns (uint96) {
        return 10000;
    }

    /**
     * @dev Sets the royalty information that all ids in this contract will default to.
     *
     * Requirements:
     *
     * - `receiver` cannot be the zero address.
     * - `feeNumerator` cannot be greater than the fee denominator.
     */
    function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
        require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
        require(receiver != address(0), "ERC2981: invalid receiver");

        _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
    }

    /**
     * @dev Removes default royalty information.
     */
    function _deleteDefaultRoyalty() internal virtual {
        delete _defaultRoyaltyInfo;
    }

    /**
     * @dev Sets the royalty information for a specific token id, overriding the global default.
     *
     * Requirements:
     *
     * - `tokenId` must be already minted.
     * - `receiver` cannot be the zero address.
     * - `feeNumerator` cannot be greater than the fee denominator.
     */
    function _setTokenRoyalty(
        uint256 tokenId,
        address receiver,
        uint96 feeNumerator
    ) internal virtual {
        require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
        require(receiver != address(0), "ERC2981: Invalid parameters");

        _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
    }

    /**
     * @dev Resets royalty information for the token id back to the global default.
     */
    function _resetTokenRoyalty(uint256 tokenId) internal virtual {
        delete _tokenRoyaltyInfo[tokenId];
    }
}

IERC165.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

IERC20.sol

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

IERC2981.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Interface for the NFT Royalty Standard.
 *
 * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
 * support for royalty payments across all NFT marketplaces and ecosystem participants.
 *
 * _Available since v4.5._
 */
interface IERC2981 is IERC165 {
    /**
     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
     */
    function royaltyInfo(uint256 tokenId, uint256 salePrice)
        external
        view
        returns (address receiver, uint256 royaltyAmount);
}

IERC721.sol

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

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

IERC721A.sol

// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.1.0
// Creator: Chiru Labs

pragma solidity ^0.8.4;

/**
 * @dev Interface of an ERC721A compliant contract.
 */
interface IERC721A {
    /**
     * The caller must own the token or be an approved operator.
     */
    error ApprovalCallerNotOwnerNorApproved();

    /**
     * The token does not exist.
     */
    error ApprovalQueryForNonexistentToken();

    /**
     * The caller cannot approve to their own address.
     */
    error ApproveToCaller();

    /**
     * Cannot query the balance for the zero address.
     */
    error BalanceQueryForZeroAddress();

    /**
     * Cannot mint to the zero address.
     */
    error MintToZeroAddress();

    /**
     * The quantity of tokens minted must be more than zero.
     */
    error MintZeroQuantity();

    /**
     * The token does not exist.
     */
    error OwnerQueryForNonexistentToken();

    /**
     * The caller must own the token or be an approved operator.
     */
    error TransferCallerNotOwnerNorApproved();

    /**
     * The token must be owned by `from`.
     */
    error TransferFromIncorrectOwner();

    /**
     * Cannot safely transfer to a contract that does not implement the ERC721Receiver interface.
     */
    error TransferToNonERC721ReceiverImplementer();

    /**
     * Cannot transfer to the zero address.
     */
    error TransferToZeroAddress();

    /**
     * The token does not exist.
     */
    error URIQueryForNonexistentToken();

    /**
     * The `quantity` minted with ERC2309 exceeds the safety limit.
     */
    error MintERC2309QuantityExceedsLimit();

    /**
     * The `extraData` cannot be set on an unintialized ownership slot.
     */
    error OwnershipNotInitializedForExtraData();

    struct TokenOwnership {
        // The address of the owner.
        address addr;
        // Keeps track of the start time of ownership with minimal overhead for tokenomics.
        uint64 startTimestamp;
        // Whether the token has been burned.
        bool burned;
        // Arbitrary data similar to `startTimestamp` that can be set through `_extraData`.
        uint24 extraData;
    }

    /**
     * @dev Returns the total amount of tokens stored by the contract.
     *
     * Burned tokens are calculated here, use `_totalMinted()` if you want to count just minted tokens.
     */
    function totalSupply() external view returns (uint256);

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

    // ==============================
    //            IERC721
    // ==============================

    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    // ==============================
    //        IERC721Metadata
    // ==============================

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

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

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

    // ==============================
    //            IERC2309
    // ==============================

    /**
     * @dev Emitted when tokens in `fromTokenId` to `toTokenId` (inclusive) is transferred from `from` to `to`,
     * as defined in the ERC2309 standard. See `_mintERC2309` for more details.
     */
    event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
}

IERC721AQueryable.sol

// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.1.0
// Creator: Chiru Labs

pragma solidity ^0.8.4;

import './IERC721A.sol';

/**
 * @dev Interface of an ERC721AQueryable compliant contract.
 */
interface IERC721AQueryable is IERC721A {
    /**
     * Invalid query range (`start` >= `stop`).
     */
    error InvalidQueryRange();

    /**
     * @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
     *
     * If the `tokenId` is out of bounds:
     *   - `addr` = `address(0)`
     *   - `startTimestamp` = `0`
     *   - `burned` = `false`
     *
     * If the `tokenId` is burned:
     *   - `addr` = `<Address of owner before token was burned>`
     *   - `startTimestamp` = `<Timestamp when token was burned>`
     *   - `burned = `true`
     *
     * Otherwise:
     *   - `addr` = `<Address of owner>`
     *   - `startTimestamp` = `<Timestamp of start of ownership>`
     *   - `burned = `false`
     */
    function explicitOwnershipOf(uint256 tokenId) external view returns (TokenOwnership memory);

    /**
     * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
     * See {ERC721AQueryable-explicitOwnershipOf}
     */
    function explicitOwnershipsOf(uint256[] memory tokenIds) external view returns (TokenOwnership[] memory);

    /**
     * @dev Returns an array of token IDs owned by `owner`,
     * in the range [`start`, `stop`)
     * (i.e. `start <= tokenId < stop`).
     *
     * This function allows for tokens to be queried if the collection
     * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
     *
     * Requirements:
     *
     * - `start` < `stop`
     */
    function tokensOfOwnerIn(
        address owner,
        uint256 start,
        uint256 stop
    ) external view returns (uint256[] memory);

    /**
     * @dev Returns an array of token IDs owned by `owner`.
     *
     * This function scans the ownership mapping and is O(totalSupply) in complexity.
     * It is meant to be called off-chain.
     *
     * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
     * multiple smaller scans if the collection is large enough to cause
     * an out-of-gas error (10K pfp collections should be fine).
     */
    function tokensOfOwner(address owner) external view returns (uint256[] memory);
}

IERC721Enumerable.sol

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

IERC721Metadata.sol

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

pragma solidity ^0.8.0;

import "./IERC721.sol";

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

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

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

IERC721Receiver.sol

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

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

NFTMasterChef_interfaces.sol

// ░██████╗████████╗░█████╗░██████╗░██████╗░██╗░░░░░░█████╗░░█████╗░██╗░░██╗
// ██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗██║░░░░░██╔══██╗██╔══██╗██║░██╔╝
// ╚█████╗░░░░██║░░░███████║██████╔╝██████╦╝██║░░░░░██║░░██║██║░░╚═╝█████═╝░
// ░╚═══██╗░░░██║░░░██╔══██║██╔══██╗██╔══██╗██║░░░░░██║░░██║██║░░██╗██╔═██╗░
// ██████╔╝░░░██║░░░██║░░██║██║░░██║██████╦╝███████╗╚█████╔╝╚█████╔╝██║░╚██╗
// ╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝╚═════╝░╚══════╝░╚════╝░░╚════╝░╚═╝░░╚═╝

// SPDX-License-Identifier: MIT
// StarBlock DAO Contracts, https://www.starblockdao.io/

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./IERC721AQueryable.sol";
import "./ERC2981.sol";

import "./wnft_interfaces.sol";

interface IERC721TotalSupply is IERC721 {
    function totalSupply() external view returns (uint256);
}

interface IStarBlockCollection is IERC721AQueryable, IERC2981 {
    struct SaleConfig {
        uint256 startTime;// 0 for not set
        uint256 endTime;// 0 for will not end
        uint256 price;
        uint256 maxAmountPerAddress;// 0 for not limit the amount per address
    }

    event UpdateWhitelistSaleConfig(SaleConfig _whitelistSaleConfig);
    event UpdateWhitelistSaleEndTime(uint256 _oldEndTime, uint256 _newEndTime);
    event UpdateexternalSaleConfig(SaleConfig _externalSaleConfig);
    event UpdateexternalSaleEndTime(uint256 _oldEndTime, uint256 _newEndTime);
    event UpdateChargeToken(IERC20 _chargeToken);

    function supportsInterface(bytes4 _interfaceId) external view override(IERC165, IERC721A) returns (bool);
    
    function maxSupply() external view returns (uint256);
    function exists(uint256 _tokenId) external view returns (bool);
    
    function maxAmountForArtist() external view returns (uint256);
    function artistMinted() external view returns (uint256);

    function chargeToken() external view returns (IERC20);

    // function whitelistSaleConfig() external view returns (SaleConfig memory);
    function whitelistSaleConfig() external view 
            returns (uint256 _startTime, uint256 _endTime, uint256 _price, uint256 _maxAmountPerAddress);
    function whitelist(address _user) external view returns (bool);
    function whitelistAmount() external view returns (uint256);
    function whitelistSaleMinted(address _user) external view returns (uint256);

    // function externalSaleConfig() external view returns (SaleConfig memory);
    function externalSaleConfig() external view 
            returns (uint256 _startTime, uint256 _endTime, uint256 _price, uint256 _maxAmountPerAddress);
    function externalSaleMinted(address _user) external view returns (uint256);

    function userCanMintTotalAmount() external view returns (uint256);

    function whitelistMint(uint256 _amount) external payable;
    function externalMint(uint256 _amount) external payable;
}

interface IHarvestStrategy {
    function canHarvest(uint256 _pid, address _forUser, uint256[] memory _wnfTokenIds) external view returns (bool);
}

interface INFTMasterChef {
    event AddPoolInfo(IERC721Metadata nft, IWrappedNFT wnft, uint256 startBlock,
                    RewardInfo[] rewards, uint256 depositFee, IERC20 dividendToken, bool withUpdate);
    event SetStartBlock(uint256 pid, uint256 startBlock);
    event UpdatePoolReward(uint256 pid, uint256 rewardIndex, uint256 rewardBlock, uint256 rewardForEachBlock, uint256 rewardPerNFTForEachBlock);
    event SetPoolDepositFee(uint256 pid, uint256 depositFee);
    event SetHarvestStrategy(IHarvestStrategy harvestStrategy);
    event SetPoolDividendToken(uint256 pid, IERC20 dividendToken);

    event AddTokenRewardForPool(uint256 pid, uint256 addTokenPerPool, uint256 addTokenPerBlock, bool withTokenTransfer);
    event AddDividendForPool(uint256 pid, uint256 addDividend);

    event UpdateDevAddress(address payable devAddress);
    event EmergencyStop(address user, address to);
    event ClosePool(uint256 pid, address payable to);

    event Deposit(address indexed user, uint256 indexed pid, uint256[] tokenIds);
    event Withdraw(address indexed user, uint256 indexed pid, uint256[] wnfTokenIds);
    event WithdrawWithoutHarvest(address indexed user, uint256 indexed pid, uint256[] wnfTokenIds);
    event Harvest(address indexed user, uint256 indexed pid, uint256[] wnftTokenIds,
                    uint256 mining, uint256 dividend);

    // Info of each NFT.
    struct NFTInfo {
        bool deposited;     // If the NFT is deposited.
        uint256 rewardDebt; // Reward debt.

        uint256 dividendDebt; // Dividend debt.
    }

    //Info of each Reward
    struct RewardInfo {
        uint256 rewardBlock;
        uint256 rewardForEachBlock;    //Reward for each block, can only be set one with rewardPerNFTForEachBlock
        uint256 rewardPerNFTForEachBlock;    //Reward for each block for every NFT, can only be set one with rewardForEachBlock
    }

    // Info of each pool.
    struct PoolInfo {
        IWrappedNFT wnft;// Address of wnft contract.

        uint256 startBlock; // Reward start block.

        uint256 currentRewardIndex;// the current reward phase index for poolsRewardInfos
        uint256 currentRewardEndBlock;  // the current reward end block.

        uint256 amount;     // How many NFTs the pool has.
       
        uint256 lastRewardBlock;  // Last block number that token distribution occurs.
        uint256 accTokenPerShare; // Accumulated tokens per share, times 1e12.
       
        IERC20 dividendToken;
        uint256 accDividendPerShare;

        uint256 depositFee;// ETH charged when user deposit.
    }
   
    function token() external view returns (IERC20);

    function poolLength() external view returns (uint256);
    function poolRewardLength(uint256 _pid) external view returns (uint256);

    function poolInfos(uint256 _pid) external view returns (PoolInfo memory _poolInfo);
    function poolsRewardInfos(uint256 _pid, uint256 _rewardInfoId) external view returns (RewardInfo memory _rewardInfo);
    function poolNFTInfos(uint256 _pid, uint256 _nftTokenId) external view returns (NFTInfo memory _nftInfo);

    function getPoolCurrentReward(uint256 _pid) external view returns (RewardInfo memory _rewardInfo, uint256 _currentRewardIndex);
    function getPoolEndBlock(uint256 _pid) external view returns (uint256 _poolEndBlock);
    function isPoolEnd(uint256 _pid) external view returns (bool);

    function pending(uint256 _pid, uint256[] memory _wnftTokenIds) external view returns (uint256 _mining, uint256 _dividend);
    function deposit(uint256 _pid, uint256[] memory _tokenIds) external payable;
    function withdraw(uint256 _pid, uint256[] memory _wnftTokenIds) external;
    function withdrawWithoutHarvest(uint256 _pid, uint256[] memory _wnftTokenIds) external;
    function harvest(uint256 _pid, address _forUser, uint256[] memory _wnftTokenIds) external returns (uint256 _mining, uint256 _dividend);

    function massUpdatePools() external;
    function updatePool(uint256 _pid) external;
}

interface ITokenPriceUtils {
    function getTokenPrice(address _token) external view returns (uint256);
}

interface INFTPool {
    function nftMasterChef() external view returns (INFTMasterChef);
    function pending(uint256 _pid, uint256[] memory _wnftTokenIds) external view returns (uint256 _mining, uint256 _dividend);
}

interface ICollectionUtils {
    struct CollectionInfo {
        string name;
        string symbol;
        uint256 totalSupply;
        address owner;
    }

    struct TokenInfo {
        string tokenURI;
        address owner;
    }

    function collectionInfos(IERC721Metadata[] memory _nfts) external view returns (CollectionInfo[] memory _collectionInfos);
    function collectionInfo(IERC721Metadata _nft) external view returns (CollectionInfo memory _collectionInfo);

    function tokenInfos(IERC721Metadata _nft, uint256[] memory _tokenIds) external view returns 
            (CollectionInfo memory _collectionInfo, TokenInfo[] memory _tokenInfos);
    function tokenInfosByNfts(IERC721Metadata[] memory _nfts, uint256[] memory _tokenIds) external view returns 
            (CollectionInfo[] memory _collectionInfos, TokenInfo[] memory _tokenInfos);
    function tokenInfo(IERC721Metadata _nft, uint256 _tokenId) external view returns (CollectionInfo memory _collectionInfo, TokenInfo memory _tokenInfo);
    
    //return the token id range the collection may have
    function tokenIdRangeMay(IERC721 _nft) external view returns (uint256 _minTokenId, uint256 _maxTokenId);
    
    //return all the token ids the collection may have
    function allTokenIdsMay(IERC721 _nft) external view returns (uint256[] memory _tokenIds);

    function ownedNFTTokenIds(IERC721 _nft, address _user) external view returns (uint256[] memory _ownedTokenIds);

    function ownedNFTTokenIdsByIdRange(IERC721 _nft, address _user, uint256 _minTokenId, uint256 _maxTokenId) external view returns (uint256[] memory _ownedTokenIds);

    function totalSupplyMay(IERC721 _nft) external view returns (uint256);

    function tokenIdExistsMay(IERC721 _nft, uint256 _tokenId) external view returns (bool);

    //check if NFT is enumerable by itself
    function canEnumerate(IERC721 _nft) external view returns (bool);

    function areContract(address[] memory _accounts) external view returns (bool[] memory);
    function isContract(address _account) external view returns (bool);

    function supportERC721(IERC721 _nft) external view returns (bool);
}

interface INFTMasterChefBatch {
    function nftPool() external view returns (INFTPool);
    function nftMasterChef() external view returns (INFTMasterChef);
    function ownedNFTTokenIds(IERC721 _nft, address _user) external view returns (uint256[] memory _ownedTokenIds);
    function pending(uint256 _pid, uint256[] memory _wnftTokenIds) external view returns (uint256 _mining, uint256 _dividend);
}

Ownable.sol

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

pragma solidity ^0.8.0;

import "./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 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 {
        _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);
    }
}

ReentrancyGuard.sol

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

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

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

        _;

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

wnft_interfaces.sol

// ░██████╗████████╗░█████╗░██████╗░██████╗░██╗░░░░░░█████╗░░█████╗░██╗░░██╗
// ██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗██║░░░░░██╔══██╗██╔══██╗██║░██╔╝
// ╚█████╗░░░░██║░░░███████║██████╔╝██████╦╝██║░░░░░██║░░██║██║░░╚═╝█████═╝░
// ░╚═══██╗░░░██║░░░██╔══██║██╔══██╗██╔══██╗██║░░░░░██║░░██║██║░░██╗██╔═██╗░
// ██████╔╝░░░██║░░░██║░░██║██║░░██║██████╦╝███████╗╚█████╔╝╚█████╔╝██║░╚██╗
// ╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝╚═════╝░╚══════╝░╚════╝░░╚════╝░╚═╝░░╚═╝

// SPDX-License-Identifier: MIT
// StarBlock DAO Contracts, https://www.starblockdao.io/

pragma solidity ^0.8.0;

import "./IERC2981.sol";
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";

interface IERC2981Mutable is IERC165, IERC2981 {
    function setDefaultRoyalty(address _receiver, uint96 _feeNumerator) external;
    function deleteDefaultRoyalty() external;
}

interface IBaseWrappedNFT is IERC165, IERC2981Mutable, IERC721Receiver, IERC721, IERC721Metadata {
    event DelegatorChanged(address _delegator);
    event Deposit(address _forUser, uint256[] _tokenIds);
    event Withdraw(address _forUser, uint256[] _wnftTokenIds);

    function nft() external view returns (IERC721Metadata);
    function factory() external view returns (IWrappedNFTFactory);

    function deposit(address _forUser, uint256[] memory _tokenIds) external;
    function withdraw(address _forUser, uint256[] memory _wnftTokenIds) external;

    function exists(uint256 _tokenId) external view returns (bool);
    
    function delegator() external view returns (address);
    function setDelegator(address _delegator) external;
    
    function isEnumerable() external view returns (bool);
}

interface IWrappedNFT is IBaseWrappedNFT {
    function totalSupply() external view returns (uint256);
}

interface IWrappedNFTEnumerable is IWrappedNFT, IERC721Enumerable {
    function totalSupply() external view override(IWrappedNFT, IERC721Enumerable) returns (uint256);
}

interface IWrappedNFTFactory {
    event WrappedNFTDeployed(IERC721Metadata _nft, IWrappedNFT _wnft, bool _isEnumerable);
    event WNFTDelegatorChanged(address _wnftDelegator);

    function wnftDelegator() external view returns (address);

    function deployWrappedNFT(IERC721Metadata _nft, bool _isEnumerable) external returns (IWrappedNFT);
    function wnfts(IERC721Metadata _nft) external view returns (IWrappedNFT);
    function wnftsNumber() external view returns (uint);
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.