I read the documentation and tried some other approaches but it's not working for me. I'm not sure what I'm missing.
Let's say I have a contract with a mapping and I would like to know the storage slot location for a particular key and be able to access it directly from something like web3.eth.getStorageAt(contractAddress, mappingKeyIndexInStorage)
:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
contract MappingStorage {
mapping(address => uint) public balances;
constructor() {
balances[0x6827b8f6cc60497d9bf5210d602C0EcaFDF7C405] = 678;
balances[0x66B0b1d2930059407DcC30F1A2305435fc37315E] = 501;
}
function getStorageLocationForKey(address _key, uint256 p) public pure returns(bytes32) {
// There is no straight foward way in solidity to concatenate 2 values, so I'm trying encoding here.
bytes memory encoded = abi.encode(_key, p);
return keccak256(encoded);
}
}
The getStorageLocationForKey
function is just an utility that I would like to use to derive this storage slot index from using Solidity.
Since the key is an address, I left padded the address to have a 32 bytes value:
0x000000000000000000000006827b8f6cc60497d9bf5210d602C0EcaFDF7C4050
Since the mapping, in this case, is declared at storage slot position 0
, I padded it to 32 bytes:
0x0000000000000000000000000000000000000000000000000000000000000000
Concatenating them without the 0x
prefix:
0000000000000000000000006827b8f6cc60497d9bf5210d602C0EcaFDF7C4050000000000000000000000000000000000000000000000000000000000000000
And its keccak256
hash:
6ccfcacc19c8d102cc5880b825323e63defac7b2ba969c7dc33950b298248835
You can try the keccak256
here: https://emn178.github.io/online-tools/keccak_256.html
I try:
web3.eth.getStorageAt(contractAddress, "0x6ccfcacc19c8d102cc5880b825323e63defac7b2ba969c7dc33950b298248835")
And it returns 0x
bytes. I'm expecting to get the 678
value which is what it's saved at that address key.
I'm I missing something?
I would like to see a solution implemented in Solidity.
Here is an instance of this contract deployed in Rinkeby testnet:
0xC216FdC8fb87A151d69313e18a80a58bebBA7267