I am trying to better understand smart contract storage and the way the variable values are stored into it. And after some testing, I noticed that values for dynamic sized arrays are stored differently
Take, for example this dynamic array:
uint[] newArray = [5,6,7];
// slot0 = 3;
If I read storage slot0
I will get value 3 (the size of the newArray)
However, with a statically defined array, the values are sorted per slots:
uint[3] newArray = [5,6,7];
// slot0 = 5;
// slot1 = 6;
// slot2 = 7;
My question is this: Where are the values of dynamic arrays stored in solidity? Which are their storage slots? After all, the data has to be stored somewhere. So which slot should I read to get a value from a dynamic array?
NOTE: Below is the code I used to test/experiment with contract storage.
//SPDX-License-Identifier: UNLICENCED
pragma solidity 0.8.3;
contract ReadArrayStorage {
uint[] newArray = [5,6,7];
///////////////// Main Functionality /////////////////////
function updateArray(uint[] calldata recievedArray)public {
newArray = recievedArray;
}
function readArray() public view returns (uint[] memory) {
return newArray;
}
///////////////// Assembly Functions for Reading Storage /////////////////////
function updateSlot(uint256 slotNumber, uint256 newValue) public {
assembly {
sstore(slotNumber, newValue)
}
}
function readSlot(uint slotNumber) public view returns (uint value) {
assembly{
value := sload(slotNumber)
}
}
}