Essential utilities for data manipulation, unit conversion, address validation, ENS name resolution, error handling, and other common operations in Ethereum development.
Common constants used throughout Ethereum development.
/**
* The zero address (0x0000000000000000000000000000000000000000)
*/
const ZeroAddress: string;
/**
* The zero hash (0x0000000000000000000000000000000000000000000000000000000000000000)
*/
const ZeroHash: string;
/**
* Number of wei in one ether (1000000000000000000n)
*/
const WeiPerEther: bigint;
/**
* Maximum value for uint256 (2^256 - 1)
*/
const MaxUint256: bigint;
/**
* Minimum value for int256 (-2^255)
*/
const MinInt256: bigint;
/**
* Maximum value for int256 (2^255 - 1)
*/
const MaxInt256: bigint;
/**
* The secp256k1 curve order N
*/
const N: bigint;
/**
* The ether symbol (Ξ) in NFKC normalized form
*/
const EtherSymbol: string;
/**
* EIP-191 personal message prefix ("\x19Ethereum Signed Message:\n")
*/
const MessagePrefix: string;Usage Examples:
import {
ZeroAddress,
ZeroHash,
WeiPerEther,
MaxUint256,
MinInt256,
MaxInt256,
EtherSymbol,
MessagePrefix
} from "ethers";
// Check for zero address
if (address === ZeroAddress) {
console.log("Invalid address");
}
// Work with wei amounts
const oneEther = WeiPerEther;
const halfEther = WeiPerEther / 2n;
// Check bounds for uint256
if (value > MaxUint256) {
throw new Error("Value exceeds uint256 maximum");
}
// Personal message signing
const message = MessagePrefix + data.length + data;Convert between different Ethereum units (wei, gwei, ether) and arbitrary decimal units.
/**
* Parse ether string to wei (as bigint)
* @param ether - Ether amount as string (e.g., "1.5")
* @returns Wei amount as bigint
*/
function parseEther(ether: string): bigint;
/**
* Format wei amount to ether string
* @param wei - Wei amount as BigNumberish
* @returns Ether amount as string
*/
function formatEther(wei: BigNumberish): string;
/**
* Parse value with specified units to smallest unit
* @param value - Value as string
* @param unit - Unit name or decimal places (default: 18)
* @returns Value in smallest unit as bigint
*/
function parseUnits(value: string, unit?: string | number): bigint;
/**
* Format value from smallest unit to specified units
* @param value - Value in smallest unit
* @param unit - Unit name or decimal places (default: 18)
* @returns Formatted value as string
*/
function formatUnits(value: BigNumberish, unit?: string | number): string;Usage Examples:
import { parseEther, formatEther, parseUnits, formatUnits } from "ethers";
// Ether conversions
const weiAmount = parseEther("1.5"); // 1500000000000000000n
const etherAmount = formatEther(weiAmount); // "1.5"
// Custom unit conversions
const gweiAmount = parseUnits("20", "gwei"); // 20000000000n
const formattedGwei = formatUnits(gweiAmount, "gwei"); // "20.0"
// Decimal place conversions
const usdcAmount = parseUnits("100.50", 6); // 100500000n (USDC has 6 decimals)
const formattedUsdc = formatUnits(usdcAmount, 6); // "100.5"Utilities for working with large numbers and converting between different numeric types.
/**
* Convert value to BigInt safely
* @param value - Value to convert
* @returns BigInt representation
*/
function getBigInt(value: BigNumberish, name?: string): bigint;
/**
* Convert value to number safely (throws if too large)
* @param value - Value to convert
* @param name - Parameter name for error messages
* @returns Number representation
*/
function getNumber(value: BigNumberish, name?: string): number;
/**
* Convert value to unsigned integer (throws if negative)
* @param value - Value to convert
* @param name - Parameter name for error messages
* @returns Unsigned integer as number
*/
function getUint(value: BigNumberish, name?: string): number;
/**
* Convert value to BigInt
* @param value - Value to convert
* @returns BigInt representation
*/
function toBigInt(value: any): bigint;
/**
* Convert value to number
* @param value - Value to convert
* @returns Number representation
*/
function toNumber(value: any): number;
/**
* Convert value to big-endian hex string
* @param value - Value to convert
* @param width - Optional byte width for padding
* @returns Hex string
*/
function toBeHex(value: BigNumberish, width?: number): string;
/**
* Convert value to big-endian byte array
* @param value - Value to convert
* @returns Uint8Array representation
*/
function toBeArray(value: BigNumberish): Uint8Array;
/**
* Convert value to JSON-RPC quantity format
* @param value - Value to convert
* @returns Hex string without leading zeros
*/
function toQuantity(value: BigNumberish): string;
type BigNumberish = string | number | bigint;
type Numeric = number | bigint;Utilities for working with signed integer representations.
/**
* Convert from two's complement representation
* @param value - Two's complement value
* @param width - Bit width
* @returns Signed value as bigint
*/
function fromTwos(value: BigNumberish, width: number): bigint;
/**
* Convert to two's complement representation
* @param value - Signed value
* @param width - Bit width
* @returns Two's complement value as bigint
*/
function toTwos(value: BigNumberish, width: number): bigint;
/**
* Apply bit mask to value
* @param value - Value to mask
* @param bits - Number of bits in mask
* @returns Masked value as bigint
*/
function mask(value: BigNumberish, bits: number): bigint;Utilities for working with byte data, hex strings, and binary operations.
/**
* Convert value to bytes (Uint8Array)
* @param value - Value to convert
* @param name - Parameter name for error messages
* @returns Bytes as Uint8Array
*/
function getBytes(value: BytesLike, name?: string): Uint8Array;
/**
* Get a copy of bytes
* @param value - Bytes to copy
* @param name - Parameter name for error messages
* @returns Copy of bytes as Uint8Array
*/
function getBytesCopy(value: BytesLike, name?: string): Uint8Array;
/**
* Check if value is a hex string
* @param value - Value to check
* @param length - Optional expected length
* @returns True if valid hex string
*/
function isHexString(value: any, length?: number): value is string;
/**
* Check if value is bytes-like
* @param value - Value to check
* @returns True if bytes-like
*/
function isBytesLike(value: any): value is BytesLike;
/**
* Convert value to hex string
* @param data - Data to convert
* @returns Hex string with 0x prefix
*/
function hexlify(data: BytesLike): string;
/**
* Concatenate multiple byte arrays
* @param values - Arrays to concatenate
* @returns Concatenated result as Uint8Array
*/
function concat(values: ReadonlyArray<BytesLike>): Uint8Array;
/**
* Get length of data in bytes
* @param data - Data to measure
* @returns Length in bytes
*/
function dataLength(data: BytesLike): number;
/**
* Slice data bytes
* @param data - Data to slice
* @param offset - Start offset
* @param endOffset - End offset
* @returns Sliced data as Uint8Array
*/
function dataSlice(data: BytesLike, offset?: number, endOffset?: number): Uint8Array;
/**
* Strip leading zero bytes
* @param data - Data to strip
* @returns Data without leading zeros
*/
function stripZerosLeft(data: BytesLike): Uint8Array;
/**
* Zero-pad value to specified length
* @param value - Value to pad
* @param length - Target length in bytes
* @returns Padded value as string
*/
function zeroPadValue(value: BytesLike, length: number): string;
/**
* Zero-pad bytes to specified length
* @param data - Data to pad
* @param length - Target length in bytes
* @returns Padded data as Uint8Array
*/
function zeroPadBytes(data: BytesLike, length: number): Uint8Array;
type BytesLike = string | Uint8Array;Utilities for Base58 and Base64 encoding/decoding.
/**
* Decode Base58 string to bytes
* @param value - Base58 string to decode
* @returns Decoded bytes
*/
function decodeBase58(value: string): Uint8Array;
/**
* Encode bytes to Base58 string
* @param data - Bytes to encode
* @returns Base58 string
*/
function encodeBase58(data: BytesLike): string;
/**
* Decode Base64 string to bytes
* @param value - Base64 string to decode
* @returns Decoded bytes
*/
function decodeBase64(value: string): Uint8Array;
/**
* Encode bytes to Base64 string
* @param data - Bytes to encode
* @returns Base64 string
*/
function encodeBase64(data: BytesLike): string;Utilities for validating and working with Ethereum addresses.
/**
* Check if value is a valid Ethereum address
* @param value - Value to check
* @returns True if valid address
*/
function isAddress(value: any): value is string;
/**
* Get checksummed Ethereum address
* @param address - Address to checksum
* @returns Checksummed address
*/
function getAddress(address: string): string;
/**
* Get ICAP address format
* @param address - Ethereum address
* @returns ICAP formatted address
*/
function getIcapAddress(address: string): string;
/**
* Check if value has an address (implements Addressable)
* @param value - Value to check
* @returns True if has getAddress method
*/
function isAddressable(value: any): value is Addressable;
/**
* Resolve address from AddressLike value
* @param target - Address-like value
* @param resolver - Optional name resolver
* @returns Promise resolving to address
*/
function resolveAddress(target: AddressLike, resolver?: NameResolver): Promise<string>;
interface Addressable {
getAddress(): Promise<string>;
}
type AddressLike = string | Promise<string> | Addressable;
interface NameResolver {
resolveName(name: string): Promise<null | string>;
}Utilities for working with Ethereum Name Service including name normalization, validation, and hashing.
/**
* Normalize ENS name according to UTS-46 normalization
* @param name - ENS name to normalize
* @returns Normalized ENS name
*/
function ensNormalize(name: string): string;
/**
* Check if string is a valid ENS name
* @param name - Name to validate
* @returns True if valid ENS name
*/
function isValidName(name: string): name is string;
/**
* Compute namehash for ENS name
* @param name - ENS name
* @returns Namehash as hex string
*/
function namehash(name: string): string;
/**
* DNS encode an ENS name for wildcard resolution
* @param name - ENS name to encode
* @param maxLength - Maximum label length (default: 63)
* @returns DNS encoded name as hex string
*/
function dnsEncode(name: string, maxLength?: number): string;
/**
* Compute keccak256 hash of UTF-8 string (used for function selectors)
* @param value - String to hash
* @returns Keccak256 hash as hex string
*/
function id(value: string): string;Usage Examples:
import { ensNormalize, isValidName, namehash, dnsEncode, id } from "ethers";
// Normalize ENS names
const normalized = ensNormalize("Vitalik.eth"); // "vitalik.eth"
// Validate ENS names
if (isValidName("vitalik.eth")) {
console.log("Valid ENS name");
}
// Compute namehash for ENS resolution
const hash = namehash("vitalik.eth");
// "0xee6c4522aab0003e8d14cd40a6af439055fd2577951148c14b6cea9a53475835"
// DNS encoding for wildcard resolution
const encoded = dnsEncode("vitalik.eth");
// Function selector computation
const selector = id("transfer(address,uint256)").slice(0, 10); // "0xa9059cbb"Functions for computing contract addresses and additional address utilities.
/**
* Compute contract address from deployer and nonce (CREATE opcode)
* @param from - Deployer address
* @param nonce - Transaction nonce
* @returns Contract address
*/
function getCreateAddress(from: string, nonce: BigNumberish): string;
/**
* Compute contract address from deployer, salt, and bytecode (CREATE2 opcode)
* @param from - Deployer address
* @param salt - Salt value
* @param initCodeHash - Hash of contract creation bytecode
* @returns Contract address
*/
function getCreate2Address(from: string, salt: BytesLike, initCodeHash: BytesLike): string;
/**
* Convert address to ICAP (International Bank Account Number) format
* @param address - Ethereum address
* @returns ICAP formatted address
*/
function getIcapAddress(address: string): string;Usage Examples:
import { getCreateAddress, getCreate2Address, getIcapAddress } from "ethers";
// Predict contract address from CREATE
const contractAddress = getCreateAddress("0x8ba1f109551bD432803012645Hac136c5a0D0D80", 42);
// Predict contract address from CREATE2
const create2Address = getCreate2Address(
"0x8ba1f109551bD432803012645Hac136c5a0D0D80",
"0x1234567890abcdef", // salt
keccak256(contractBytecode) // initCodeHash
);
// Convert to ICAP format
const icapAddress = getIcapAddress("0x8ba1f109551bD432803012645Hac136c5a0D0D80");Utilities for working with UTF-8 string encoding and decoding.
/**
* Convert string to UTF-8 bytes
* @param str - String to convert
* @param form - Unicode normalization form
* @returns UTF-8 bytes
*/
function toUtf8Bytes(str: string, form?: UnicodeNormalizationForm): Uint8Array;
/**
* Convert string to UTF-8 code points
* @param str - String to convert
* @param form - Unicode normalization form
* @returns Array of code points
*/
function toUtf8CodePoints(str: string, form?: UnicodeNormalizationForm): Array<number>;
/**
* Convert UTF-8 bytes to string
* @param bytes - UTF-8 bytes to convert
* @param onError - Error handling function
* @returns Decoded string
*/
function toUtf8String(bytes: BytesLike, onError?: Utf8ErrorFunc): string;
/**
* Built-in UTF-8 error handling functions
*/
class Utf8ErrorFuncs {
static error: Utf8ErrorFunc;
static ignore: Utf8ErrorFunc;
static replace: Utf8ErrorFunc;
}
type UnicodeNormalizationForm = "NFC" | "NFD" | "NFKC" | "NFKD";
type Utf8ErrorReason = "UNEXPECTED_CONTINUE" | "BAD_PREFIX" | "OVERRUN" | "MISSING_CONTINUE" | "OUT_OF_RANGE" | "UTF16_SURROGATE" | "OVERLONG";
type Utf8ErrorFunc = (reason: Utf8ErrorReason, offset: number, bytes: Uint8Array, output: Array<number>) => number;Recursive Length Prefix encoding/decoding for Ethereum data structures.
/**
* Encode data using RLP encoding
* @param object - Data to encode
* @returns RLP encoded bytes as hex string
*/
function encodeRlp(object: RlpStructuredDataish): string;
/**
* Decode RLP encoded data
* @param data - RLP encoded data
* @returns Decoded data structure
*/
function decodeRlp(data: BytesLike): RlpStructuredData;
type RlpStructuredData = string | Array<RlpStructuredData>;
type RlpStructuredDataish = string | Array<RlpStructuredDataish> | Uint8Array;Utilities for object property management and async property resolution.
/**
* Define properties on an object with proper descriptors
* @param target - Target object
* @param values - Properties to define
*/
function defineProperties<T>(target: T, values: { [K in keyof T]?: T[K] }): void;
/**
* Resolve all promise properties in an object
* @param object - Object with potential promise properties
* @returns Promise resolving to object with resolved properties
*/
function resolveProperties<T>(object: { [K in keyof T]: T[K] | Promise<T[K]> }): Promise<T>;Comprehensive error handling utilities for Ethereum operations.
/**
* Assert condition is true, throw if false
* @param condition - Condition to check
* @param message - Error message
* @param code - Error code
* @param info - Additional error info
*/
function assert(condition: any, message?: string, code?: string, info?: any): asserts condition;
/**
* Assert function argument is valid
* @param condition - Condition to check
* @param message - Error message
* @param name - Argument name
* @param value - Argument value
*/
function assertArgument(condition: any, message: string, name: string, value: any): asserts condition;
/**
* Assert correct number of arguments
* @param count - Actual argument count
* @param expectedCount - Expected argument count
* @param message - Error message
*/
function assertArgumentCount(count: number, expectedCount: number, message?: string): void;
/**
* Assert private constructor access
* @param givenGuard - Provided guard
* @param guard - Expected guard
* @param className - Class name
*/
function assertPrivate(givenGuard: any, guard: any, className?: string): void;
/**
* Assert valid Unicode normalization form
* @param form - Normalization form to validate
*/
function assertNormalize(form: string): void;
/**
* Create standardized error
* @param message - Error message
* @param code - Error code
* @param info - Additional error info
* @returns EthersError instance
*/
function makeError(message: string, code: ErrorCode, info?: any): EthersError;
/**
* Check if error is a call exception
* @param error - Error to check
* @returns True if call exception
*/
function isCallException(error: any): error is CallExceptionError;
/**
* Check if error matches specific code
* @param error - Error to check
* @param code - Error code to match
* @returns True if error matches code
*/
function isError(error: any, code: ErrorCode): boolean;
type ErrorCode = string;High-precision fixed-point arithmetic for financial calculations.
/**
* Fixed-point number with configurable precision
*/
class FixedNumber {
constructor(guard: any, value: bigint, format: FixedFormat);
readonly format: FixedFormat;
readonly value: bigint;
// Arithmetic operations
add(other: FixedNumber): FixedNumber;
sub(other: FixedNumber): FixedNumber;
mul(other: FixedNumber): FixedNumber;
div(other: FixedNumber): FixedNumber;
// Comparison
eq(other: FixedNumber): boolean;
lt(other: FixedNumber): boolean;
lte(other: FixedNumber): boolean;
gt(other: FixedNumber): boolean;
gte(other: FixedNumber): boolean;
// Conversion
toString(): string;
toUnsafeFloat(): number;
// Static constructors
static fromString(value: string, format?: FixedFormat): FixedNumber;
static fromValue(value: BigNumberish, decimals?: number, format?: FixedFormat): FixedNumber;
}
interface FixedFormat {
readonly signed: boolean;
readonly width: number;
readonly decimals: number;
readonly name: string;
}HTTP request utilities for blockchain API interactions.
/**
* HTTP fetch request builder
*/
class FetchRequest {
constructor(url: string);
readonly url: string;
body?: Uint8Array;
headers: Map<string, string>;
method: string;
timeout: number;
// Request configuration
setHeader(key: string, value: string): void;
setThrottleParams(params: { slotInterval?: number; maxAttempts?: number }): void;
// Request execution
send(): Promise<FetchResponse>;
// Static utilities
static lockConfig(): void;
static getGateway(url: string): null | FetchGatewayFunc;
static registerGateway(matcher: RegExp, gateway: FetchGatewayFunc): void;
}
/**
* HTTP fetch response
*/
class FetchResponse {
constructor(statusCode: number, statusMessage: string, headers: Readonly<Record<string, string>>, body: Readonly<Uint8Array>, request?: FetchRequest);
readonly statusCode: number;
readonly statusMessage: string;
readonly headers: Readonly<Record<string, string>>;
readonly body: Readonly<Uint8Array>;
// Response parsing
bodyText(): string;
bodyJson(): any;
// Status checking
ok(): boolean;
// Error handling
throwThrottleError(message: string, stall?: number): never;
}
/**
* Fetch cancellation signal
*/
class FetchCancelSignal {
constructor(request: FetchRequest);
readonly cancelled: boolean;
readonly reason?: string;
cancel(reason?: string): void;
checkSignal(): void;
}UUID v4 generation for unique identifiers.
/**
* Generate a random UUID v4 string
* @returns UUID v4 string
*/
function uuidV4(): string;Event payload system for blockchain event handling.
/**
* Event payload for blockchain events
*/
class EventPayload<T = any> {
constructor(emitter: EventEmitterable<T>, listener: null | Listener, filter: T);
readonly emitter: EventEmitterable<T>;
readonly listener: null | Listener;
readonly filter: T;
// Event control
removeListener(): void;
}
type EventEmitterable<T = any> = {
on(event: T, listener: Listener): any;
off(event: T, listener?: Listener): any;
emit(event: T, ...args: any[]): boolean;
};
type Listener = (...args: Array<any>) => void;type GetUrlResponse = { statusCode: number; statusMessage: string; headers: Record<string, string>; body: Uint8Array };
type FetchPreflightFunc = (req: FetchRequest) => Promise<FetchRequest>;
type FetchProcessFunc = (req: FetchRequest, resp: FetchResponse) => Promise<FetchResponse>;
type FetchRetryFunc = (req: FetchRequest, resp: FetchResponse, attempt: number) => Promise<boolean>;
type FetchGatewayFunc = (url: string, signal?: FetchCancelSignal) => Promise<FetchRequest | FetchResponse>;
type FetchGetUrlFunc = (req: FetchRequest, signal?: FetchCancelSignal) => Promise<GetUrlResponse>;