How to write a gas efficient NFT smart contract?

Solidity

Blockchain

09/25/2021


A simple workaround that can save tons of gas!

nft banner

Now-a-days, a lot of NFT projects are being launched every single day. During the public sale, the gas fee is going crazy.

Have a look at the picture below 👇

eth gas

The screenshot was taken during a public sale of a NFT project on Ethereum— no it was not edited. 🤯

The project had more than 50,000 members trying to mint around 5000 NFTs which resulted in a gas war, taking the gas prices to sky high. Once the sale ended after 5 minutes, the gas price started to reduce gradually.

Because of these kind of terrible gas wars, a lot of people endup paying higher gas fee more than the actual value of the NFT itself. And there is no guarantee that all the users will get a NFT, as the supply is limited.

A simple workaround:

We can implement a simple work around in the flow to reduce the gas fee spike. Rather than allowing users to mint directly during the time of sale, we can just allow the users to reserve the NFTs. Later, the users can mint the NFTs whenever they want to — ofcourse there should be a window like 1 week or so, for minting their reserved tokens. By doing so we can avoid throttling the Ethereum network.

Traditional Mint flow:

SOL
function mintItems(uint256 amount) public payable {
// Safety checks...
require(msg.value >= amount * _unitPrice);
for (uint256 i = 0; i < amount; i++) {
_mintItem(msg.sender);
}
}

Optimized Mint flow:

SOL
// Keeps track of reserved tokens for each user
mapping (address => uint256) public _mintableCount;
// This method reserves the tokens for the user during sale.
function reserveTokens(uint256 amount) public payable{
require(msg.value >= amount * _unitPrice);
_mintableCount[msg.sender] += amount;
}
// the user can mint the reserved tokens when required
function mintItems(uint256 amount) public payable {
require(_mintableCount[msg.sender] >= amount);
for (uint256 i = 0; i < amount; i++) {
_mintItem(msg.sender);
}
}

It doesn’t mean that implementing this optimization doesn’t result in gas war. But it will not throttle the network as like the traditional method.

Happy coding 🥳