1

I understand that for OpenSea to read our metadata JSON file, we need the function below.

function uri(uint256 _tokenid) override public pure returns (string memory) {
    return string(
        abi.encodePacked(
            "https://ipfs.io/ipfs/bafybeihjjkwdrxxjnuwevlqtqmh3iegcadc32sio4wmo7bv2gbf34qs34a/",
            Strings.toString(_tokenid),".json"
        )
    );
}

But what if my contract gives the option of setting a new URI for each token id like below?

   function setTokenURI(uint256 tokenId, string memory tokenURI) public onlyOwner {
        ERC1155URIStorage._setURI(tokenId, tokenURI);
    }

The IPFS URL would have been changed. Thus, how do I change the uri function so that I can accommodate the update of the token URI?

1 Answer 1

0

You can use Openzeppelin's ERC1155URIStorage.sol extension for this.

If you don't want to use the extension and want to code by yourself then you can just replicate the same mechanism in your contract from this extension.

Here is the link : https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/extensions/ERC1155URIStorage.sol

I have also implemented the same logic in one of my contracts but without the extension.

    function getUri(uint256 _tokenId) internal view returns (string memory) {
    return
        string(
            abi.encodePacked(baseUri, Strings.toString(_tokenId), ".json")
        );
}

function uri(uint256 _tokenId) external view returns (string memory) {
    string memory mappedUri = Uri[_tokenId];
    if (bytes(mappedUri).length > 0) {
        return mappedUri;
    } else {
        return getUri(_tokenId);
    }
}

Here is the link to full code - https://github.com/Zartaj0/ERC1155/blob/c1f8ef450630b30065f876889288469d72ac539f/contracts/Joker.sol#L54C1-L68C6

2
  • I'm actually using ERC1155URIStorage.sol extension. But how could I replace the hardcoded https://ipfs.io/ipfs/bafybeihjjkwdrxxjnuwevlqtqmh3iegcadc32sio4wmo7bv2gbf34qs34a/ in the abi.encodePacked?
    – ratib90486
    Jul 5, 2023 at 13:54
  • Why are you hardcoding the value? This string should be stored in a state variable and will be only accessed when needed. Look at my code it is self-explanatory. Jul 5, 2023 at 15:00

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.