4

I want to sell an NFT within my smart contract. But first, I want to check with a require statement if the token (NFT) exists or not before moving on to the next steps. I have tried require(ownerOf(tokenId), "Token doesn't exists."); but Remix says:

from solidity:
TypeError: No matching declaration found after argument-dependent lookup.
   --> contracts/charMinter.sol:108:9:
    |
108 |         require(ownerOf(tokenId), "Token doesn't exists.");
    |         ^^^^^^^
Note: Candidate: function require(bool)
Note: Candidate: function require(bool, string memory)

I also tried require(tokenURI(tokenId), "Token doesn't exists."); but I get the same error as above. Is there a way to check if a token exists or not?

2 Answers 2

2

You can use _exists(uint tokenId) function inheritanced from ERC721 smart contract.

You must to change your original condition like this:

require(_exists(tokenId), "Token doesn't exists.");

You can read more about this function here.

Example of smart contract that use this function:

// SDPX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

contract Test is ERC721 {

    constructor() ERC721("TestToken", "TT") {
        _mint(msg.sender, 0);
    }

    function checkIfTokenExist(uint _tokenId) external view returns(address) {
        require(_exists(_tokenId), "Error!");
        return ownerOf(_tokenId);
    }
}
2
  • 3
    This answer is not valid for OpenZeppelin 5.x versions. Can you add this information as well please? 5.x release notes states that: The _exists function was removed. Calls to this function can be replaced by _ownerOf(tokenId) != address(0)
    – MehmedB
    Nov 6, 2023 at 9:13
  • 1
0

Here's an implementation example that is OpenZeppelin 5.x compliant:

function tokenURI(uint256 tokenId) public view override returns (string memory) {
    require(_ownerOf(tokenId) != address(0), "ERC721: URI query for nonexistent token");

    string memory _tokenURI = _tokenURIs[tokenId];
    if (bytes(_tokenURI).length > 0) {
        return _tokenURI;
    }

    return bytes(baseURI).length > 0
        ? string(abi.encodePacked(baseURI, tokenId.toString(), baseExtension))
        : "";
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.