0

I assume it would need assembly and potentially a delegatecall function, but I have been stuck trying to get anything that could work. The idea is that we would input the contract address and the storage slot to output the contents of that storage in bytes.

1 Answer 1

1

You can only read the storage slot of your own contract, not arbitrary address. If you want to read your own contract storage at arbitrary slot number, you can use the below code:

contract Test{
    uint slot0 = 111;
    uint slot1 = 222;
    function read_slot(uint slot_num) public view returns (uint res) {
        assembly{
            res := sload(slot_num)
        }
    }
}
  • read_slot(0) -> 111
  • read_slot(1) -> 222

To read other contracts' storage slots, the other contract must implement the above function or other equivalent read/getter functions. Otherwise, it's impossible.

--- Update: the question asked for returning bytes, so the function can be changed a little bit to return bytes32: function read_slot(uint slot_num) public view returns (bytes32 res)

3
  • What about from the bytecode? If you have the full contract code, can you read a private variable from bytecode? Commented Jan 11, 2023 at 22:28
  • No there is no way because code as in bytecode and data in storage (the data you want to read) are two separate things(store separately on different read/write model). The only way you can read is that the contract implement the equivalence of the above function either in solidity/assembly or bytecode.
    – minhhn2910
    Commented Jan 12, 2023 at 2:35
  • 1
    This one explains the evm in a simple way: ethereum.org/static/e8aca8381c7b3b40c44bf8882d4ab930/302a4/…
    – minhhn2910
    Commented Jan 12, 2023 at 2:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.