Skip to content

Validate Smart Contract Storage Gaps With OpenZeppelin Upgrades Plugins

The Contracts team is pleased to announce that the OpenZeppelin Upgrades plugins now secure the use of storage gaps. These plugins allow developers to validate that the storage variables for their upgradeable contracts are upgrade-safe.

Storage gaps have been a common recommendation to allow for additional storage variables to be safely added when using inheritance. One strategy for writing an upgradeable contract involves declaring individual variables in the base contract which are not used but that the developer might want to have available in the future. That way, the storage area for these variables can be reserved. This approach works — and it’s worth mentioning that simply declaring unused variables of a given size and type does not cost additional gas when deploying a contract. Still, it does require that the developer can predict to a certain extent the storage that will be needed in the future. Put plainly, it can be hard to know precisely the sizes, types, and amounts of data you’ll need to store before the time comes. 

A more elegant solution, which OpenZeppelin Upgrades plugins now provide support for, is to declare a fixed-size array in the base contract with a given number of slots, assigned to the variable name __gap so that OpenZeppelin Upgrades will recognize it as a reserved storage gap. The purpose of such a gap is to allow storage areas to be available if needed in the future.

At a later point, if the base contract is modified to add additional variables, simply reduce the appropriate number of slots from the storage gap, paying particular attention to Solidity’s rules on how variables are packed in storage.

The plugins, available for both Hardhat and Truffle, include the validateUpgrade method which will report any errors in the reduction of storage gaps as well as the expected size of the gap. Calling upgradeProxy when using the plugin will run the storage gap validation checks as well, ensuring that developers using the OpenZeppelin Upgrades plugins can verify their contracts are upgrade-safe.

This feature has been highly sought after by developers working in the space. The OpenZeppelin Upgrades plugins support this pattern to help teams stay safe with smart contract upgrades.

Read more: