I need to know storage address of solidity smart contract variables before its deployment. how can I get this?
1 Answer
Which storage slots are allocated for which contract variable depends on the language and/or compiler. The Solidity compiler has an option to output the storage layout as a JSON structure:
https://solidity.readthedocs.io/en/latest/internals/layout_in_storage.html#json-output
In the Solidity language you can use .slot
in assembly to get the storage slot of a variable:
pragma solidity 0.7.4;
contract StorageSlotFetch
{
struct ThreeSlots
{
uint256 a;
uint256 b;
uint256 c;
}
address var0;
uint256 var1;
bytes32 var2;
ThreeSlots var3;
uint256 var4;
function getStorageSlots() external pure returns (uint256[5] memory ret)
{
assembly {
mstore(add(ret, 0), var0.slot)
mstore(add(ret, 32), var1.slot)
mstore(add(ret, 64), var2.slot)
mstore(add(ret, 96), var3.slot)
mstore(add(ret, 128), var4.slot)
}
}
}