2

I found some contract that looks like this:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
contract IceCream {
    address a;
    address b;
    bool public c = false;
    uint256 public d;

constructor(...){...}
}

I would now expect to get the following values when calling the following on my geth console:

await web3.eth.getStorageAt(address, 0) --> a
await web3.eth.getStorageAt(address, 1) --> b
await web3.eth.getStorageAt(address, 2) --> c
await web3.eth.getStorageAt(address, 3) --> d

Position 0: I find a (Which I also suspect to be there).

Position 1: I find b (Which I also suspect to be there).

Position 2: I find some value 0x0000000000000000000000000000000000000000000000000000000000000a36 which i suppose is the value of the uint256 d. WHY?

Position 3: I find: 0x0000000000000000000000000000000000000000000000000000000000000000. WHY?

I thought the variables in storage are stored in order.

What am I missing here?

Probably it is something really easy and stupid but I just can`t make any sense of this.

0

Each storage slot has a size of 256 bits (or 32 bytes). If several elementary types can be packed into 32 bytes they will use the same slot.

Let's see what we have here :

  • address a : 20 bytes.

It is stored on slot 0 and web3.eth.getStorageAt(address, 0) returns the value of a (0 in your case as it was not instantiated).

  • address b : 20 bytes

Since slot 0 has only 12 bytes left, b is stored on slot 1.

  • bool public c = false : 1 byte

Booleans only occupy 1 byte. Hence c can be packed with b on slot 1. web3.eth.getStorageAt(address, 1) therefore returns 0x00 + b.

This example is not very instructive as 0x00 + b = b (on 32 bytes), that's why I advise you to deploy the same contract on whatever testnet setting c to true. You will then get 0x01 + b on slot 1.

  • uint256 public d : 32 bytes

It uses slot 2 and web3.eth.getStorageAt(address, 2) returns d

  • Slot 3 is not used and therefore web3.eth.getStorageAt(address, 3) gives 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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