Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article examines ERC-3772, which proposes a mechanism for optimizing the storage cost of unsigned integers.

This article translates, summarizes, and supplements the material linked below.

I have also covered other EIPs.

Overview

ERC-3772 proposes compressing uint256 values into smaller representations, such as uint64, uint96, and uint128, to optimize storage costs.

A compressed integer, referred to as cintx, consists of two components.

  • Significant bits
    • The portion retaining information about the value.
  • Left shift count
    • The number of positions by which the significant bits must be shifted left.

The compression can be lossy because some precision may be discarded. The proposal therefore defines two decompression methods to handle the resulting approximation.

Motivation

Storage operations on Ethereum can be expensive. The original article estimates a cost of approximately $0.20 for updating one storage slot at a gas price of 20 gwei. The actual cost depends on the storage operation and the ETH price.

Storing every token amount as a separate uint256 can consequently be inefficient.

For example, the article considers practical DAI amounts ranging from 0.001 DAI to one trillion DAI (10¹²), and ETH amounts ranging from 0.000001 ETH to one billion ETH. These illustrative ranges each span a factor of approximately 10¹⁵.

By contrast, a uint256 representing an asset with 18 decimals covers positive amounts from approximately 10⁻¹⁸ to 10⁵⁹ tokens. The original article describes the upper order of magnitude as 10⁵⁸. Many applications use only a small portion of this range.

Representing a ratio of 10¹⁵ requires approximately log₂(10¹⁵) ≈ 50 bits. The proposal therefore explores using around 50 significant bits while retaining a shift count to represent larger values, enabling more compact storage.

Specification

Compressed Integer Format

ERC-3772 refers to a representation of a compressed uint256 as cintx.

The value of x denotes the compressed bit width, implemented using the corresponding Solidity uintx type.

Compression

Compression retains the most significant bits of the original uint256, starting at its highest set bit, and records the left shift required to reconstruct an approximate value.

Formats from cint64 to cint120

The least significant eight bits store the shift value. The remaining bits store the significant portion.

js
struct cint64 { uint56 significant; uint8 shift; }
struct cint120 { uint112 significant; uint8 shift; }

Formats from cint128 to cint248

The least significant seven bits store the shift count, with the remaining bits used for significant data.

Solidity does not provide a uint7 type, so an implementation can use uint8 to hold the seven-bit shift count.

js
struct cint128 { uint121 significant; uint7 shift; }
struct cint248 { uint241 significant; uint7 shift; }

Compression Examples

  • For value = 2**100, the binary representation contains a leading 1 followed by 100 zeros.
    • cint64 { significant: 1 << 55, shift: 45 }
  • For value = 2**100 - 1, the binary representation contains 100 consecutive ones.
    • cint64 { significant: maximum 56-bit value, shift: 44 }

Decompression

Two decompression methods are defined.

Ordinary Decompression

Place the significant bits in a uint256 and shift them left by the recorded shift count to recover the lower-bound approximation.

Examples:

text
cint16 { significant: 11010111, shift: 3 }
⇒ 復元値: 11010111000
text
cint64 { significant: 56個の1, shift: 44 }
⇒ 復元値: 56個の1 + 44個の0(合計100ビット)

Rounding-Up Decompression

After shifting the significant bits left, set all discarded low-order bits to 1. This reconstructs an upper-bound approximation for cases where conservative rounding is required.

Examples:

text
cint16 { significant: 11011110, shift: 3 }
⇒ 復元値: 11011110111
text
cint64 { significant: 56個の1, shift: 44 }
⇒ 復元値: 合計100個の1(末尾が全て1になっている)

Use Within Contracts

ERC-3772 is intended to optimize internal smart contract state.

Compressed values should be used internally rather than exposed directly to other contracts or frontends. When a value is exposed externally, the contract should return its decompressed representation.

Additional Notes

The compressed value cintx uses the following layout.

  • High-order bits
    • Significant bits.
  • Low-order bits
    • Shift count.

This layout helps developers avoid common implementation mistakes.

For example, if the shift count occupied the high-order bits and the significant portion occupied the low-order bits, compressing a relatively small number such as `256 - 1) could produce an encoded value identical to the original number.

A developer who accidentally omitted decompression might then fail to notice the bug. Placing the significant bits above the shift count makes such mistakes easier to detect.

Gas Savings Are Conditional

Using cint64 does not automatically reduce gas costs.

Savings depend on the compiler being able to pack multiple values into the same storage slot, for example within a suitably arranged struct.

Compression and decompression also introduce additional computation. Developers should evaluate the trade-off against the access frequency and storage layout of the relevant data structure.

Differences from Floating-Point Numbers

The representation resembles binary floating-point numbers, but its purpose is different.

  • Floating-point numbers
    • Represent a wide numerical range using a limited number of bits.
  • This compression method
    • Reduces storage size while preserving as much precision as practical within the expected range of values.

The number of bits allocated to the shift count is therefore kept small: eight bits through cint120, and seven bits for cint128 through cint248.

Examples of Storage Slot Savings

The following structs illustrate how compressed integer representations affect storage layout.

js
// 3スロット消費
struct UserData1 {
    uint64 amountCompressed;
    bytes32 hash;
    address beneficiary;
}
js
// 2スロットで収まる(圧縮+レイアウト工夫による効果)
struct UserData2 {
    uint64 amountCompressed;
    address beneficiary;
    bytes32 hash;
}

Choosing suitable field sizes and ordering can reduce the number of storage slots occupied by a struct, potentially reducing gas costs.

Reference Implementation

js
function compress(uint256 full) public pure returns (uint64 cint) {
    uint8 bits = mostSignificantBitPosition(full);
    if (bits <= 55) {
        cint = uint64(full) << 8;
    } else {
        bits -= 55;
        cint = (uint64(full >> bits) << 8) + bits;
    }
}

function decompress(uint64 cint) public pure returns (uint256 full) {
    uint8 bits = uint8(cint % (1 << 9));
    full = uint256(cint >> 8) << bits;
}

function decompressRoundingUp(uint64 cint) public pure returns (uint256 full) {
    uint8 bits = uint8(cint % (1 << 9));
    full = uint256(cint >> 8) << bits + ((1 << bits) - 1);
}

Security

Value Reduction During Compression

Because the number of significant bits is limited, compression can discard low-order bits. Ordinary decompression may therefore return a value smaller than the original uint256.

For example, compressing 2**100 - 1 into cint64 produces the following decompressed value.

js
a = 2**100 - 1;
c = compress(a).decompress();
a > c; // true

The result is an approximation rather than an exact reconstruction.

Estimating the Error of cint64

For an original integer with bit length m greater than 56, the maximum absolute rounding error is 2**(m-56) - 1 in the integer's base units.

The original article estimates an error of approximately 0.0001 (10⁻⁴) for a token amount of 10¹² using cint64. The error in whole-token units depends on the token's decimal precision and the original integer's bit length.

Whether this error is acceptable depends on the application.

Handling Rounding Errors

Ordinary decompression tends to round downward, similar to integer division in many DeFi implementations.

The proposal discusses the following conservative rounding conventions.

  • When sending tokens to a user, use decompress() to obtain the lower-bound approximation.
  • When collecting tokens from a user, use decompressRoundingUp() to obtain the upper-bound approximation.

These conventions can avoid rounding-related losses for a protocol, although they may slightly affect the user's payment or receipt amount.

Similar directional rounding principles are used in financial smart contracts, including Uniswap V3. Implementations should ensure the rounding policy is appropriate, disclosed, and bounded for their particular accounting model.

Precision Loss from Incorrect Usage

Performing arithmetic directly on compressed representations can result in incorrect calculations and substantial precision loss.

For example, multiplying compressed values and compressing the result again is not equivalent to multiplying their decoded numerical values.

Incorrect example:

js
uint64 sharesC = // 圧縮済み
uint64 price = // 通常の値
uint64 amountC = sharesC.cmuldiv(price, PRICE_UNIT);
user.transfer(amountC.uncompress());

Correct approach:

js
uint64 sharesC = shares.compress();
uint64 priceC = price.compress();
uint256 amount = sharesC.uncompress() * price / PRICE_UNIT;
user.transfer(amount);

Perform arithmetic on decompressed values. Use compression primarily to optimize storage writes.

Do Not Compress Arbitrary uint256 Values

This representation is designed with token and currency amounts in mind.

A uint256 has approximately 10⁷⁷ possible values. The original article assumes that many practical token amounts, expressed in base units, concentrate around 10¹⁵ to 10³⁰. This assumption motivates the use of 56 significant bits.

Applying the same lossy representation to arbitrary values, such as random numbers or values requiring an exact representation across the full integer range, can cause unacceptable precision loss or unexpected behavior.

If the precision requirements are unclear, retain the full integer representation.

Compressing Stable and Volatile Assets

A cint64 has 56 significant bits. The original article uses amounts of 1,000,000 SHIBA INU and 0.0002 WBTC, each valued at approximately $10 at the time of the example, to illustrate its intended precision.

Exact representation depends on the corresponding integer amounts and whether discarded low-order bits are zero. The prices are illustrative historical values, not current market quotations.

For highly volatile assets, such as an example in which the price increases by a factor of 256, even a small rounding error in token units may become economically significant. Larger representations such as cint96 or cint128 may be appropriate.

The original design assumes that approximately 50 significant bits suffice for many practical ranges and allocates six additional bits in cint64, corresponding to a factor of about 64 in precision headroom under those assumptions.

A price decrease may reduce the economic impact of an absolute token-unit rounding error. Neither this assumption nor the headroom estimate constitutes a universal guarantee: each application must evaluate its own amount ranges and error bounds.

Citation

Soham Zemse (@zemse), "ERC-3772: Compressed Integers [DRAFT]," Ethereum Improvement Proposals, no. 3772, August 2021. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-3772.

Conclusion

ERC-3772 proposes compressed integer representations for optimizing the storage of unsigned numerical values in Ethereum smart contracts.

If you have questions, feel free to contact me on Twitter.

Twitter @cardene777

I also publish articles on the following platforms.

https://chaldene.net/