ERC20Capped:在合约创建期间无法读取不可变变量,这意味着它们无法在构造函数 OpenZeppelin 4 中读取

问题描述

当我尝试使用 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 并且由于您使用的是后者,因此省略了检查。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...