Skip to main content

TokenId

TokenId is a branded bigint type representing ERC-721 non-fungible token (NFT) identifiers.

Overview

ERC-721 defines a standard for non-fungible tokens (NFTs) where each token is unique. Token IDs uniquely identify each NFT within a collection and are stored as uint256 values on-chain.

Key Features

  • Type-safe: Branded bigint prevents mixing with raw numbers
  • Unique identifiers: Each token ID represents a single NFT
  • Range validation: 0 to 2^256-1
  • ERC-721 interface selectors: Built-in function selectors

Installation

Basic Usage

API Reference

Constructor

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

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

Conversions

toNumber(tokenId: TokenId): number

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

toBigInt(tokenId: TokenId): bigint

Convert to bigint.

toHex(tokenId: TokenId): string

Convert to hex string with 0x prefix.

Validation

isValid(tokenId: TokenId): boolean

Check if token ID is valid (non-zero). Some implementations consider zero invalid.

Comparison

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

Check if two token IDs are equal.

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

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

Constants

constants.MAX

Maximum TokenId value (2^256 - 1).

constants.MIN

Minimum TokenId value (0).

ERC-721 Interface

ERC721_SELECTORS

ERC-721 function selectors for ABI encoding.

ERC-721 Standard

ERC-721 defines a standard API for non-fungible tokens. Key functions:
  • balanceOf(address): Returns NFT count owned by address
  • ownerOf(uint256): Returns owner of specific token ID
  • transferFrom(address, address, uint256): Transfers NFT
  • safeTransferFrom(address, address, uint256): Safe transfer with callback
  • approve(address, uint256): Approves address to transfer token
  • setApprovalForAll(address, bool): Approves operator for all tokens
  • getApproved(uint256): Returns approved address for token
  • isApprovedForAll(address, address): Checks if operator is approved
Specification: EIP-721

Token ID Patterns

Sequential IDs

Most NFT collections use sequential IDs starting from 0 or 1:

Computed IDs

Some collections compute IDs from attributes:

Large IDs

Token IDs can be very large (up to 2^256-1):

Examples

Query Owner

Transfer NFT

Check Ownership

List Collection

Error Handling

Type Safety

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

See Also