When using ERC20Capped, in a contract, and compiling with truffle. Threw an error saying that immutable variables cant be used in constructors, inside ERC20Capped.
Details
Tried compiling a contract using ERC20Capped with Truffle, to get an error about immutable variables, not being able to be used in a constructor.
I can reproduce using OpenZeppelin Contracts 4 Release Candidate when attempting to mint in the constructor. This would only happen when minting in the constructor.
$ npx truffle compile
Compiling your contracts...
===========================
> Compiling ./contracts/GLDToken.sol
TypeError: Immutable variables cannot be read during contract creation time, which means they cannot be read in the constructor or any function or modifier called from it.
--> @openzeppelin/contracts/token/ERC20/extensions/ERC20Capped.sol:26:16:
|
26 | return _cap;
| ^^^^
Compilation failed. See above.
Truffle v5.2.3 (core: 5.2.3)
Node v10.23.2
We should have anticipated this issue
The thing is, ERC20Capped adds an extra check in the _mint function that verifies you are not exceeding the cap. For efficiency reasons, we made the cap immutable. This removes a load operation when doing the check, and thus reduces the gas cost of minting. The downside, as you show, is that this immutable variable cannot be read from during construction, which means you cannot use ERC20Capped’s _mint protection during the construction.
The good news is that the “non protected” ERC20._mint remains available!