Hi, I was wondering if adding new variables to the last slot used by a contract when doing an Upgrade is safe?
For example I have a contract like this:
contract V1 {
bool var1;
uint256[48] private __gap;
}
And I want to upgrade to:
contract V2 {
bool var1;
bool var2;
uint256[48] private __gap;
}
Can I do this althought I see var2
is being added to the exact same slot as var1
? So gap remains the same.
Is it safe or new variables have to be added to a new slot separate from previous ones?
Thanks!
Julian
Looks safe (i.e., you don't need to add a new slot, since the current one will only utilize 16 out of 256 available bits).
2 Likes
It is worth noting, however, that despite the above being correct for a pair of 8-bit variables (boolean in your example), one should avoid making this conclusion based only on the sum of the sizes of the variables.
For example, if you asked the same question about changing this:
bool var1;
uint128 var2;
To this:
bool var1;
uint128 var2;
bool var3;
Then despite the sum of the sizes of these variables (144 bits) being smaller than 256 bits, it is possible that the compiler would allocate a new storage slot for var3
.
This is because the compiler might add implicit padding between var1
and var2
, in order to place var2
at an address which is aligned to 128 bits (i.e., an address which is divisible by 128).
I am not 100% certain of that, as it really depends on the compiler implementation (or possibly on the EVM itself).
This padding is pretty typical in embedded systems, and I would imagine that the same might apply here as well.
If it is the case here as well, then one way to avoid padding is by ordering the variables from largest to smallest.
For example, in contrast with the previous example, I believe that the following would fit in a single storage slot:
uint128 var1;
bool var2;
bool var3;
Thanks. Yeah but even in that case it is safe to upgrade, its just not packing which is not a big deal.
My main concern was messing up the existing slots.
I did a small POC for my own question and confirmed the upgrade is safe, I did it using the HH Plugins.
OK, in that case, I have totally misinterpreted your question.
Yes, your case doesn't seem to put the storage slot at risk of getting "messed up".