128 Bit Integers Gas Savings – Is It Safe and Effective to Use 128 Bit Integers to Track Wei in a Contract?

contract-designcontract-developmentgassolidity

The default type for Wei in Solidity is the 256 bit unsigned integer. (e.g. msg.value)

However, to track 1.7e38 wei (1.7e20 ether) you only need a 127 bit integer. That's a gigantic number not likely to be exceeded in any real world application.

As long as you are not multiplying two Wei values together, is it considered reasonably safe to track Wei in signed 128 bit integers so that two values can be packed into one 256 bit word in order save storage costs on gas?

Are there additional computational costs on half word arithmetic that might significantly eat up the gas savings?

Best Answer

In my opinion, yes uint128 is safe to track wei values, and can save half of the storage costs of uint (when Solidity is able to optimize). Internally, there is probably masking being done to access the upper and lower 128bits from the 256bit word, but I don't think it's going to consume much gas: so the storage gas savings will be more.

Related Topic