Skip to main content

TokenBalance

TokenBalance is a branded bigint type representing ERC-20 token balances with decimal handling utilities.

Overview

ERC-20 tokens are fungible tokens where each token is identical and interchangeable. Balances are stored as unsigned 256-bit integers (uint256) on-chain, with decimals used for display formatting.

Key Features

  • Type-safe: Branded bigint prevents mixing with raw numbers
  • Decimal handling: Convert between raw values and human-readable amounts
  • Range validation: 0 to 2^256-1
  • ERC-20 interface selectors: Built-in function selectors

Installation

Basic Usage

API Reference

Constructor

from(value: bigint | number | string): TokenBalance

Create TokenBalance from bigint, number, or hex/decimal string.
Throws:
  • InvalidTokenBalanceError if value is negative, exceeds max, or invalid

Conversions

toNumber(balance: TokenBalance): number

Convert to number (unsafe for large values).
Throws:
  • RangeError if value exceeds Number.MAX_SAFE_INTEGER

toBigInt(balance: TokenBalance): bigint

Convert to bigint.

toHex(balance: TokenBalance): string

Convert to hex string with 0x prefix.

Decimal Handling

format(balance: TokenBalance, decimals: number, maxDecimals?: number): string

Format balance for display with decimal places.

fromBaseUnit(amount: string, decimals: number): TokenBalance

Convert from human-readable amount to raw balance.
Throws:
  • Error if amount format is invalid (e.g., “1.2.3”)

toBaseUnit(balance: TokenBalance): bigint

Get raw bigint value.

Comparison

equals(a: TokenBalance, b: TokenBalance): boolean

Check if two balances are equal.

compare(a: TokenBalance, b: TokenBalance): number

Compare two balances. Returns -1 if a < b, 0 if equal, 1 if a > b.

Constants

constants.MAX

Maximum TokenBalance value (2^256 - 1).

constants.MIN

Minimum TokenBalance value (0).

constants.DECIMALS

Common decimal counts for popular tokens.

ERC-20 Interface

ERC20_SELECTORS

ERC-20 function selectors for ABI encoding.

ERC-20 Standard

ERC-20 defines a standard API for fungible tokens. Key functions:
  • balanceOf(address): Returns token balance
  • transfer(address, uint256): Transfers tokens
  • approve(address, uint256): Approves spending allowance
  • transferFrom(address, address, uint256): Transfers from approved account
  • totalSupply(): Returns total supply
  • allowance(address, address): Returns approved allowance
Specification: EIP-20

Common Decimal Counts

Different tokens use different decimal counts:
  • 18 decimals: ETH, WETH, DAI, most ERC-20 tokens
  • 6 decimals: USDC, USDT (stablecoins)
  • 8 decimals: WBTC (Bitcoin-based)
Always check the token’s decimals() function before formatting.

Examples

Query Balance

Transfer Tokens

Check Sufficient Balance

Error Handling

Type Safety

TokenBalance is a branded type that prevents accidental mixing with raw bigints:

See Also