Solidity Tutorial — How to Store NFT Metadata and SVG’s on the Blockchain
Recently I took a deep dive into the Crypto World. Especially on DeFi and Smart Contracts. So I did what probably every other developer has done that started working on the Block Chain. I minted my own NFT. Particularly an ERC-721 Token. This is an article I really wish I had a few weeks ago.
OpenSea Requirements For NFT’s
If you want your token to be available on Opensea you’ll need to follow the ERC721 standard. You can read full instructions on creating NFT’s to this standard on OpenSea’s Website . But the main requirement for these NFT’s is that your smart contract contains a
tokenURI() method which returns the url containing your metadata.
Why Store On Chain
One of the biggest issues I’ve thought of when it comes to NFT’s is their immutability and permanence.
The immutability problem.
The smart contract on the chain always has the same tokenURI but there’s no guarantee that endpoint will always return the same thing. For example, say I have a webserver and I set up the webserver to return meta data based on the token number. Ex:
What happens when I decide to change what that endpoint does? There’s no guarantee to the owner of the token that the results from that API call will always be the exact same.
This problem has been mostly solved by IPFS services.(What is IPFS?) Which allow users to “Pin” files on the server. The files are stored with a hash that will never change. The uploader of the file cannot change what’s stored under that hash. This guarantees immutability but there’s another problem.
The Permanence Problem
Even if you use an IPFS, the file will only exist as long as it is “pinned”. And you still may need a dedicated gateway to serve your files with a decent speed, which may lead to your metadata requests timing out in the future.
The ONLY WAY to ensure your data is there forever is to store it directly on the blockchain. So how do we do that.
How to store Metadata on Chain
Take this example:
All tokenURI() does is return a Data Url that contains the JSON. The SVG is stored as a string and returned along with the rest of the metadata. In this example we are retrieving the Svg via it’s own method. Obviously you’ll need to do the generation of the SVG string on chain as well, but that’s outside of the scope of this article
The beauty is, once this has been deployed on the blockchain it will remain immutable and permanent forever.