ERC20Capped:在合同创建期间不能读取不可变变量,这意味着它们不能在构造函数OpenZeppelin4中读取



当我试图像一样使用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中进行,由于您使用的是后者,因此省略了检查。

最新更新