没有销毁NFT之前可以正常获取所有者名下所有的NFT数组,如果销毁了名下的一个NFT ,就无法获取到数组
怎样才能正常获取销毁后所有者名下的所有NFT数组。
完整的代码
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
contract Yinka is AccessControl, ERC721URIStorage {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
event OpenBox(uint256 leixing,uint256 create);
struct Prop{
uint16 power;
}
mapping(uint=>Prop) public props;
constructor() ERC721("Yinka", "Yinka") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
}
function tokenIds() public view returns(uint256){
return _tokenIds.current();
}
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
function mintYinka(address player, string memory tokenURI)public onlyRole(MINTER_ROLE) returns(uint256){
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
Prop memory i;
i.power=uint16(rand(100,0));
props[newItemId]=i;
_mint(player, newItemId);
_setTokenURI(newItemId, tokenURI);
return newItemId;
}
function getByOwner(address _owner) external view returns(uint256[] memory) {
uint256[] memory result = new uint256[](balanceOf(_owner));
uint256 counter = 0;
for (uint256 i = 1; i <= _tokenIds.current(); i++) {
if (ownerOf(i) == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
function setRole(address addr) public onlyRole(DEFAULT_ADMIN_ROLE){
_grantRole(MINTER_ROLE,addr);
}
function supportsInterface(bytes4 interfaceId)public view override(ERC721, AccessControl)returns (bool){
return super.supportsInterface(interfaceId);
}
function rand(uint256 _length,uint256 _nonce) public view returns(uint256) {
uint256 random = uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp,_nonce)));
return random%_length+1;
}
}
function getByOwner(address _owner) external view returns(uint[] memory) {
uint[] memory result = new uint[](balanceOf(_owner));
uint counter = 0;
for (uint i = 1; i <= _tokenIds.current(); i++) {
if (ownerOf(i) == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
开始可以正常获取
销毁了一个NFT后,就不能正常获取了提示:
The transaction has been reverted to the initial state.
Reason provided by the contract: "ERC721: owner query for nonexistent token".
Debug the transaction to get more information.