Solidity – Counters.Counter vs totalSupply in OpenZeppelin Contracts

openzeppelinopenzeppelin-contractssolidity

Creating my first contract and was taking a look at the Open Zeppelin wizard. I notice that it includes a Counters.Counter private _tokenIdCounter;, which tracks the amount of tokens minted. When I add the enumerable library it still seems to include that snippet within the code when there is now a totalSupply variable that seems to track the same value.

Question: Why is _tokenIdCounter included, and is there any difference between that and the totalSupply variable? Seems as though totalSupply would work fine and I should remove the _tokenIdCounter.

Best Answer

On the surface they may sound the same.

Each NFT typically has an unique ID, and the Counters are used to assign the next available ID to a new NFT. This goes hand in hand with totalSupply as long as NFTs are minted.

However, if there is functionality to burn an NFT, the Counter doesn't decrease (since the IDs shouldn't typically be reused), but the totalSupply goes down.

Furthermore, I'm unsure if such functionality is ever desired, but at least in theory you can have two NFTs with the same ID - in which case the Counter is not in sync with totalSupply also.