1

I have the following code and want to initialize a constant in constructor.

 import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
    contract IToken is ERC20 { 
        uint256 private constant _Total;// = 1000 * 10**9;
        

constructor(string memory Name, string memory Symbol) public ERC20(Name, Symbol) {
            _Total = 1000 * 10**9;
            _mint(msg.sender, _Total);
        }
     }

However I get an errors that the constant are

TypeError: Uninitialized "constant" variable. TypeError: Cannot assign to a constant variable.

I want to initialize the constant in the constructor argument so that when I deploy the token I can deploy it with following statement in truffle by specifying _Total in deploy script.

1

uint256 private constant _Total;// = 1000 * 10**9;

If you declare something as constant you must initialise it at the same time. You can't set its value at a later date. (Its value must be known at compile time, so you can't set it during execution.)

In your constructor you are not passing in the value that you want to set _Total to, so there's no real need to set it in the constructor - you can just hard-code it as a global variable in the contract.

So, two options:

  1. Change uint256 private constant _Total; to uint256 private _Total;, and then pass a value into the constructor, and set _Total.
  2. Just set uint256 private constant _Total = 1000 * 10**9; as a global variable.

want to initialize the constant in the constructor argument so that when I deploy the token I can deploy it with following statement in truffle by specifying _Total in deploy script.

In that case you want option #1.

2
  • I want to pass the value from deploy script thats why I am not assigning value. But anyway the answer you suggested is what I have already implemented in my code. May 5 at 9:38
  • My point #1 removes the constant keyword, which is what you'll need to do. May 5 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.