2

When I try to mint inside of constructor using ERC20Capped from OpenZeppelin 4 like

contract SomeERC20 is ERC20Capped {

    constructor (
        string memory name,
        string memory symbol,
        uint256 cap,
        uint256 initialBalance
    )
        ERC20(name, symbol)
        ERC20Capped(cap)
    {
        _mint(_msgSender(), initialBalance);
    }
}

the error

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

appears.

What should I do?

Pavlo Ostasha
  • 14,527
  • 11
  • 35

1 Answers1

4

cap is immutable in ERC20Capped thus it cannot be read during the mint process in the constructor. It was done on purpose to lower gas costs. You can either mint outside of the constructor or use the _mint function from common ERC20 like this


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);
    }
}

It is advised to add a check for the initialSupply to be lower than the cap The check is originally done in the _mint function of ERC20Capped but not in the ERC20 and since you are using the latter the check is omitted.

Pavlo Ostasha
  • 14,527
  • 11
  • 35
  • 1
    strange this comment is not upwoted yet. Made few contracts in autumn 2020, but today in summer 2021 old approaches does not work anymore. And this answer is very helpful. Saves lots of time. I even have time for a beer because of this and hot weather in the summer – RusAlex Jun 24 '21 at 17:42