3

I simulated two contracts that sending balance to another and simply setting value of a variable(var a = 5;). In contrast my expectation, {var a = 5;} contract consumed more gas than the other. In my understanding, balance of accounts are stored in another place(i guess in memory), but general state(such as var a) are stored in disk(storage). Is it right? Or the other factor affected this results?

3

Both account balances and contract storage are stored on disk in the state database.

Sending ether costs at least 21k gas (intrinsic transaction cost), setting a new storage variable costs at least 21k + 20k = 41k gas. In both cases a single 32 byte value is updated.

I think the reason updating balances costs less is the number of Patricia Trie nodes that need to be updated:

  • for balance update at most 64 nodes (32 bytes for address, 2 nibbles each) has to be updated
  • for storage slot update at most 128 nodes (32 bytes for the storage slot key + 32 bytes for the address - the account needs to be updated because its storageRoot would be changed).

There are on average 2 times more Patricia Trie nodes that has to be updated for storage slot write that's why it costs ~2 times more.

  • Thanks a lot! That's what i exactly wanted. It was really helpful. – 송제호 Mar 4 '18 at 8:39
  • I'm sorry but can u explain more detail about number of updating nodes? I've never heard about that exact number of nodes(64 and 128) to be updated. I thought all of nodes should be updated for balance or state change. – 송제호 Mar 4 '18 at 8:53
  • I meant the Patricia Trie nodes github.com/ethereum/wiki/wiki/Patricia-Tree. All state including balances and contract storage is stored there. The maximum depth of the trie is 64 nodes because the keys are 32 bytes. For storage update, 2 tries need to be updated, that's why 128. – medvedev1088 Mar 4 '18 at 11:05

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.