4

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;
}
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
OmerS
  • 153
  • 2
  • 9

1 Answers1

5

_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

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • So I need to use in my smart contract tokenURI function from ERC721 or setTokenURI from the ERC721URIstorage? – OmerS Feb 26 '22 at 13:37
  • either of them. each has its own use case and discussed here: https://forum.openzeppelin.com/t/why-doesnt-openzeppelin-erc721-contain-settokenuri/6373/34 – Yilmaz Feb 26 '22 at 15:21
  • Thanks. Another question is why _setTokenURI is more expensive that tokenURI as you mentioned above? – OmerS Feb 27 '22 at 07:35
  • ERC721URIstorage stores data for tokenURI on-chain @OmerS , this might be one of the reason. – spetsnaz Jul 25 '22 at 10:52