当我试图像一样使用OpenZeppelin 4中的ERC20Capped
在构造函数内部进行薄荷时
contract SomeERC20 is ERC20Capped {
constructor (
string memory name,
string memory symbol,
uint256 cap,
uint256 initialBalance
)
ERC20(name, symbol)
ERC20Capped(cap)
{
_mint(_msgSender(), initialBalance);
}
}
错误
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
出现。
我该怎么办?
cap在ERC20Capped
中是不可变的,因此在构造函数的mint过程中无法读取。这样做是为了降低天然气成本。您可以在构造函数之外进行mint,也可以像下面的一样使用公共ERC20
中的_mint
函数
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);
}
}
建议添加一个检查,使initialSupply
低于cap
。该检查最初在ERC20Capped
的_mint
函数中进行,但不在ERC20
中进行,由于您使用的是后者,因此省略了检查。