Upgradable Contracts instantiating an `immutable` value

I am trying to use an upgradable contract with the configuration of an immutable variable in the contract at constructor time, but the upgradability of a contract prevents it being setup in the initializer and needs to be set in the constructor...

Would using the following setup work for the initialization of the immutable variable in the constructor () initialize {} ?

Or are constructors forbidden from being used in upgradable contracts and the line constructor () initialize {} will not execute ? or is a breach of security ?

1 Like

Hey migbash,
So, according to the documentation on open zeppelin documentation, because immutable variables are stored in the bytecode, a variable instantiated as immutable would result in all proxies pointing to the same value stored in byte code, rather than the proxy pointing to the variable in in it's own storage.

So immutables look like a nono

From the docs:

Why can’t I use immutable variables?

Solidity 0.6.5 introduced the immutable keyword to declare a variable that can be assigned only once during construction and can be read only after construction. It does so by calculating its value during contract creation and storing its value directly into the bytecode.

Notice that this behavior is incompatible with the way upgradeable contracts work for two reasons:

  1. Upgradeable contracts have no constructors but initializers, therefore they can’t handle immutable variables.
  2. Since the immutable variable value is stored in the bytecode its value would be shared among all proxies pointing to a given contract instead of each proxy’s storage.

In some cases immutable variables are upgrade safe. The plugins cannot currently detect these cases automatically so they will point it out as an error anyway. You can manually disable the check using the option unsafeAllow: ['state-variable-immutable'], or in Solidity >=0.8.2 placing the comment/// @custom:oz-upgrades-unsafe-allow state-variable-immutable before the variable declaration.

1 Like