0

https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps

1: https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps explains why the __gap variable is needed, but https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#modifying-your-contracts says "If you need to introduce a new variable, make sure you always do so at the end". So if I can just add a variable to the end, why is the __gap variable needed?

2 Answers 2

4

__gap is used in base contracts to avoid storage clashes while using inheritance.

You cannot add new variables to base contracts if the child has any variables of its own. Given the following scenario:
contract Base { uint256 base1; }

contract Child is Base { uint256 child; }

If Base is modified to add an extra variable:

contract Base { uint256 base1; uint256 base2; }

Then the variable base2 would be assigned the slot that child had in the previous version. A workaround for this is to declare unused variables on base contracts that you may want to extend in the future, as a means of "reserving" those slots. Note that this trick does not involve increased gas usage.

You can implement it like this:

contract Base { uint256 base1; uint256[50] private __gap; }

contract Child is Base { uint256 child; }

If Base is modified to add an extra variable:

contract Base { uint256 base1; uint256 base2; uint256[49] private __gap; }

0

Check this out - https://github.com/OpenZeppelin/openzeppelin-sdk/issues/912#issuecomment-496522759

In short, you should add variables before or after the __gap, and need to adjust the gap size in the mean time.

2
  • Not sure how it answers the question. May 20, 2022 at 13:29
  • 2
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    May 21, 2022 at 12:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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