Search code examples
ethereumsoliditysmartcontractsnfterc721

set token URI function


I understood that setTokenURI function isn't in use anymore. How can I change the token URI of the NFT token I want to create? for now my function createCollectible inside the smart contract looks like this:

function createCollectible(string memory tokenURI)
    public
    returns (uint256)
{
    uint256 newItemId = tokenId;
    _safeMint(msg.sender, newItemId);
    _setTokenURI(newItemId, tokenURI);
    tokenId = tokenId + 1;
    return newItemId;
}

Solution

  • _setTokenURI is still used but it is moved to the ERC721URIStorage. Here is the openzeppelin link

    When you create your contract, you should inherit:

    contract NFT is ERC721URIStorage { }
    

    Since calling it an expensive operation, team wants you to use tokenUri function in ERC721:

    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
            require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
    
            string memory baseURI = _baseURI();
            return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
        }
    

    this is _baseUri() which is inherited from ERC721. It is virtual so that you can override it inside ERC721URIStorage and change it from "" to anything you want.

    function _baseURI() internal view virtual returns (string memory) {
            return "";
        }
    

    this time you need to inherit from ERC721

     contract NFT is ERC721{
        function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
           require(_exists(tokenId), "...");
           _tokenURIs[tokenId] = _tokenURI;
               }
       }
    

    They both have different use cases: Discussed Here