OpenZeppelin Issues – tokenId (uint256) Not Returning Correctly

openzeppelinreturndatauint256

In my tokenURI function, I have it setup to return the tokenId that is being called for, but when I run the method I get a symbol.

function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
    require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
    return string(abi.encodePacked(_baseURI(), "/", _tokenId, ".json"));

Here is the response I get when I call this function in Etherscan.

enter image description here

Is it not possible to return tokenId as a uint256 off chain?

Best Answer

The problem is that abi.encodePacked() encodes uint256 as a raw bytes sequence. In order to make it output /1234.json you have to convert an uint256 to an decimal string.

For example using uint2str from this question Conversion of uint to string it will look like this:

return string(
    abi.encodePacked(_baseURI(), 
        "/",
        uint2str(_tokenId),
        ".json"));
Related Topic