Solidity Library

Stop paying for resolution you don't need.

A Solidity library for shift-based quantization of unsigned integers, enabling tighter struct packing and lower gas costs.

Solidity EVM Gas Optimization MIT License

Quick Start

Terminal
forge soldeer install uint-quantization-lib
MyContract.sol
import {Quant, UintQuantizationLib} from "uint-quantization-lib/src/UintQuantizationLib.sol"; Quant private immutable SCHEME = UintQuantizationLib.create(32, 24); uint24 stored = uint24(SCHEME.encode(largeValue)); // compress uint256 restored = SCHEME.decode(stored); // decompress

How It Works

Original
1e18 wei
kept: 224 bits discarded: 32 bits
256 bits total (1 token, 18 decimals)
>> 32
encode
Stored
232,830,643 wei
fits in uint224
<< 32
decode
Restored
≈ 1e18 wei
preserved: 224 bits zero-filled: 32 bits
max error < 2^32 wei (~4.3 gwei)

Ask an AI

Explain how the uint-quantization-lib Solidity library (https://github.com/0xferit/uint-quantization-lib) works. How does its shift-based quantization reduce gas costs, and what are the tradeoffs?

API

create(discardedBitWidth, encodedBitWidth)Create a quantization scheme
encode(value)Floor-encode a value (reverts on overflow)
encode(value, true)Strict encode (reverts if not step-aligned)
decode(encoded) / decodeMax(encoded)Restore lower-bound or upper-bound value
fits(value) / fitsEncoded(encoded)Check if value is representable
isAligned(value) / remainder(value)Check step alignment and lost bits
requireAligned(value) / requireMinStep(value)Guard helpers that revert on bad input
floor(value) / ceil(value)Snap to nearest step boundary
stepSize() / max()Query scheme parameters