Simple On-chain NFT Metadata Gas Optimization

Liron Navon
2 min readOct 14, 2022

How to optimize on-chain NFT metadata in a single simple step.

I have recently read the post by Parham Alimardanian where there is a mention of generating metadata for NFTs on the chain, his conclusion was that “You can see that the on-chain method gas usage is a lot higher than the off-chain method.” while it is true, his results were exaggerated by bad use of on-chain Metadata.

In solidity there are 2 costly things, saving data, and computation, but in solidity, there are also free things, such as static calls which do not require any gas usage — moving the computation side of things to a statically called function can have a great impact on gas optimization.

This was the contract Parham used to showcase his results:

There are two issues with this approach:

  1. The “mintOnChain” function is calling “makeURI”, it calculates the data URL using base64 on the same computation space where the transaction takes place, and this increases the gas price.
  2. The second issue is the use of Open Zepplin's “ERC721URIStorage” which is needed only for static URIs, it serves no purpose when we define on-chain metadata.

Mitigating these issues, we can create a more optimized contract:

How does it translate to gas savings? by simply moving the calculation of the base64 from a place where it would cost gas, to a place where it can be called statically, and removing extra functionality that is only needed for static URIs, we can reduce almost all the gas overhead from saving on-chain metadata.

As you can see, the contract that is optimized for on-chain metadata costs almost the same amount of gas as the normal off-chain NFT, yet it allows us to create a dynamic NFT.

Conclusion

When writing smart contracts, we sometimes have to think of optimizations that are not valid for normal, web2 operations, doing this change on a normal backend written in Go or Node would change nothing, and would probably increase the overhead since it will not allow caching — but with smart contracts, that is a completely valid way to achieve gas optimization.

--

--