I am studying popular Ethereum smartcontract's source code and there is something i do not understand on ERC20 standard.
Let's took this example:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol
Here is a portion of this smartcontract's solidity source code:
mapping (address => uint256) private _balances;
uint256 private _totalSupply;
As you can see, the total supply is stored on a separate variable. This total supply is the sum of all the balances.
What i've learned about Solidity optimization is we should give priority to storage rather than calculation.
If i had to write an ERC20 contract, i would write a view function which sums _balances in order to provide total supply. Why ? A view function can sum balances for free gas because it does not write anything on blockchain. If we have a _totalSupply variable, we have to update it each time one balance change. So it will cost some gas to write this variable.
My question is: Why everybody puts a _totalSupply variable on ERC20 contracts, rather than a view function which sums balances ?
Thanks
_balancesthat's not possible. You cannot make a loop on a mapping as it is a key/value system with an infinite quantity of keys. For exemple an address which doesn't hold tokens exists in the mapping and will return zero as value. – clement Jan 17 '21 at 14:55transferfunction. – clement Jan 17 '21 at 14:58