When I try to mint inside of constructor using ERC20Capped
from OpenZeppelin 4 like
contract SomeERC20 is ERC20Capped {
constructor (
string memory name,
string memory symbol,
uint256 cap,
uint256 initialBalance
)
ERC20(name, symbol)
ERC20Capped(cap)
{
_mint(_msgSender(), initialBalance);
}
}
the error
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
appears.
What should I do?
cap is immutable in ERC20Capped
thus it cannot be read during the mint process in the constructor. It was done on purpose to lower gas costs. You can either mint outside of the constructor or use the _mint
function from common ERC20
like this
contract SomeERC20 is ERC20Capped {
constructor (
string memory name,
string memory symbol,
uint256 cap,
uint256 initialBalance
)
ERC20(name, symbol)
ERC20Capped(cap)
{
require(initialBalance <= cap, "CommonERC20: cap exceeded"); // this is needed to know for sure the cap is not exceded.
ERC20._mint(_msgSender(), initialBalance);
}
}
It is advised to add a check for the initialSupply
to be lower than the cap
The check is originally done in the _mint
function of ERC20Capped
but not in the ERC20
and since you are using the latter the check is omitted.