1

i'm studying mastering ethereum with this site. https://github.com/ethereumbook/ethereumbook/blob/develop/09smart-contracts-security.asciidoc

and all of example codes are using uint 256.

for example,

    pragma solidity ^0.4.19

    contract EtherStore {

        //unsigned integer type of 256 bits
        uint256 public withdrawalLimit = 1 ether;

        mapping(address => uint256) public lastWithdrawTime;
        mapping(address => uint256) public balances;

        function depositFunds() public payable {
            balances[msg.sender] += msg.value;
            }

        function withdrawFunds (uint256 _weiToWithdraw) public {

            ...
            ...
        }  
    }

uint256 public withdrawalLimit = 1 ether;

it use 256 bits just allocate 'integer 1' i think this is waste of memory and gas.

if this value treat to wei, these value only needs 60 bits.

i don't know why this book use 256bits to save '1'

thanks for your help :)

1 Answer 1

3

The EVM works natively in 256-bit words. Using smaller ones usually consumes more gas because there's extra work to do: the unneeded bits need to be masked away.

A possible exception is when packing multiple values into the same storage slot. E.g. struct MyStruct { uint128 foo; uint128 bar; }. Here, depending on your access pattern, you may or may not save gas by being able to store both values into the same storage slot.

Note that in this particular code, the best option would be to use a constant. Then the value doesn't have to be persisted in storage at all, which will be a very big gas saving.

4
  • thanks for your help, but i have one more question :) mapping(address => uint256) in this code, the address should be caller's address. but there is no reference how contract get caller's address.
    – sang oh
    Apr 3, 2019 at 1:51
  • how this contract get caller's address? if you can't understand my question, just tell me. thanks :)
    – sang oh
    Apr 3, 2019 at 1:51
  • msg.sender is the caller's address.
    – user19510
    Apr 3, 2019 at 1:55
  • ethereum.stackexchange.com/questions/45734/… - in this link, mapping is hashing 160bits address to 256bits by keccat256. is it related EVM works 256-bits? Would it be use less gas than using 160?
    – sang oh
    Apr 3, 2019 at 2:09

Your Answer

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

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