1

I have a contract with function

    function addToBalance () payable {
        userBalances[msg.sender] += msg.value ;
    }

Debugged assembly and stumbled on the code that calculates key for store:

Code:
  => SHA3
Stack:
  0x0, 0x40
Memory:
  0x00: 000000000000000000000000ca35b7d9 // msg.sender 
  0x10: 15458ef540ade6068dfe2f44e8fa733c // msg.sender
  0x20: 00000000000000000000000000000000
  0x30: 00000000000000000000000000000000

As far as I understand SHA3 calculatates hash of first 0x40 bytes of memory starting at 0x0. I don't get either the point of hashing 0x40 bytes (when 0x20 bytes would be enough) or what are the arguments of SHA3 instructions.

1

If you have more than one mapping in your contract[*] then the second 32 bytes in the hashed data (from 0x20 to 0x3f) is used to distinguish between this mapping and any of the other ones.

In this case, these bytes are 0x00..00, so this is the first defined mapping. The next defined mapping will concatenate the key value with 0x00..01, and so on. Using the hash of the key alone would cause all the mappings to overwrite each other when using the same key.

There's a detailed exploration in this article. See under the heading "Two Mappings" onwards, and remember that the + symbol means concatenation in the article.

[*] Edit - on further investigation, Solidity does this even if there is only one mapping in tho contract.

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.