What happens with contract storage on contract inheritance

When A contract inherits B contract, base contract’s code (B code) is copied on A, deploying only one contract.
The point is, what happens with the storage? All the storage variables of base contract will be on A at the same slot positions? What is the preference, A’s variables or B’s variables?

These questions arise from this proxy article. Inheriting is a way to preserve storage slot structure? I read somewhere in the article that while upgrading contracts it is a good idea to make the new contract inherits the old one, to preserve the same storage slot structure and not overwrite slots… how can be this possible? If the new contract has any variable, will change the whole storage structure right?

2 Likes

I bet that after reading this you will still have many questions, so check out this guide from the ZeppelinOS docs. It covers a lot from your question.

First, you should understand the need for such complications. Which is to be able to upgrade deployed contracts. This is done through a proxy, that is an intermediary contract between your most recent contract and the user. So the user is interacting with the logic contract through the proxy, like a relay, and not directly.
What the proxy is doing is passing your calls to the logic contract and serving back the response to the user.

Storage from the proxy and the logic contract are kept in the proxy. So when you upgrade it, it won’t be necessary to redeploy the information again. The problem that arises is, how do we avoid the collision of storage between these two contracts. Inheritance is one of the ways to ensure that the logic contract does not overwrite state variables that are used in the proxy for upgradeability.

Hope it helps. Feel free to do a follow-up.

4 Likes

For laying out the variables in storage, Solidity will first linearize the contract hierarchy, and then start laying out the variables starting from the most base contract, onto the most derived one.

Have a look at the following for more details:


2 Likes