1

当我尝试使用ERC20Capped来自 OpenZeppelin 4的构造函数内部进行铸造时

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

出现。

我应该怎么办?

4

1 回答 1

3

cap 是不可变的,ERC20Capped因此在构造函数的 mint 过程中无法读取它。这样做是为了降低天然气成本。您可以在构造函数之外创建,也可以像这样使用_mintcommon 中的函数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函数中完成的,ERC20Capped但不是在函数中完成ERC20,因为您使用的是后者,所以省略了检查。

于 2021-04-03T11:41:54.963 回答