问题描述
当我尝试使用 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
函数
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
添加一个检查该检查最初是在_mint
的{{1}}函数中完成的,而不是在ERC20Capped
ERC20
并且由于您使用的是后者,因此省略了检查。