logoAcademy

URIs

Non-Fungible Token Standard

Ignoring the technical side of ERC-721 tokens, perhaps the most famous use case of such tokens is to track digital images. Whenever most people hear the term NFT, they mostly think of JPEGs that can be tracked on the blockchain.

With our current understanding of ERC-721 tokens, it does not really make sense how we can use such a token standard to track pictures, considering NFTs are just mappings from numbers to addresses. In this section, we will look at how we can extend the functionality of ERC-721 tokens to be able to track digital assets such as JPEGs.

URIs

URIs, or uniform resource indicators, can be thought of as a particular format of URLs which allow us to easily build a particular URL using just a base URL and a specific URL. As an example, consider the following base URL: rodrigo.xyz/images . As the URL might suggest, this URL is the base string for all webpages which store images. Some sample specific URLs would be /dog.jpeg, /cat.jpeg, ..., etc. By organizing our URLs in this manner, it makes it easy to organize our collection of images.

NFTs, likewise, use the same principle. In the case of JPEGs, NFTs simply keep track of the URL of the jpeg via the URI format.

Another Mapping

Tying everything together, to track digital assets such as JPEGs which use URIs, we can add the following mapping to our ERC-721 function:

mapping(uint256 tokenId => string) private _tokenURIs;

The mapping above stores the specific token URIs, while the base URI is stored as a separate state variable. To be able to query the full URI of a particular token, we can use the following function (from OpenZeppelin's ERC721URIStorage contract):

function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireOwned(tokenId);

        string memory _tokenURI = _tokenURIs[tokenId];
        string memory base = _baseURI();

        // If there is no base URI, return the token URI.
        if (bytes(base).length == 0) {
            return _tokenURI;
        }
        // If both are set, concatenate the baseURI and tokenURI (via string.concat).
        if (bytes(_tokenURI).length > 0) {
            return string.concat(base, _tokenURI);
        }

        return super.tokenURI(tokenId);
}

Just like that, our NFTs are now able to track digital assets like JPEGs!

On this page