Collection of utility functions used in web3.js for Ethereum dApp development
npx @tessl/cli install tessl/npm-web3-utils@4.3.0Web3-Utils is a comprehensive TypeScript utility library that provides essential functions for Ethereum decentralized application (dApp) development. It offers data type converters, cryptographic hashing, address validation, event emission, JSON-RPC helpers, promise utilities, and socket provider abstractions with full type safety and cross-platform compatibility.
npm install web3-utilsimport {
toHex, fromWei, toWei, keccak256, randomHex,
utf8ToBytes, EventEmitter, Web3DeferredPromise
} from "web3-utils";For CommonJS:
const {
toHex, fromWei, toWei, keccak256, randomHex,
utf8ToBytes, EventEmitter, Web3DeferredPromise
} = require("web3-utils");import { toHex, fromWei, toWei, keccak256, toChecksumAddress } from "web3-utils";
// Convert values to hex
const hexValue = toHex(1234); // "0x4d2"
const hexString = toHex("Hello"); // "0x48656c6c6f"
// Convert between wei and ether units
const ethAmount = fromWei("1000000000000000000", "ether"); // "1"
const weiAmount = toWei("1.5", "ether"); // "1500000000000000000"
// Hash data
const hash = keccak256("hello world"); // "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad"
// Format address with checksum
const checksumAddr = toChecksumAddress("0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed");
// "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAeD"Web3-Utils is organized around several key functional areas:
Comprehensive conversion utilities for transforming data between hex, bytes, numbers, strings, and Ethereum units. Essential for handling blockchain data formats.
function toHex(value: Numbers | Bytes | Address | boolean | object, returnType?: boolean): HexString | ValueTypes;
function toNumber(value: Numbers): number | bigint;
function toBigInt(value: unknown): bigint;
function fromWei(number: Numbers, unit: EtherUnits | number): string;
function toWei(number: Numbers, unit: EtherUnits | number): string;Keccak-256 hashing functions and Solidity-style packed encoding for data integrity and smart contract interaction.
function keccak256(data: Bytes | Numbers | string | ReadonlyArray<number>): string;
function sha3(data: Bytes): string | undefined;
function soliditySha3(...values: Sha3Input[]): string | undefined;
function encodePacked(...values: Sha3Input[]): string;Node.js-compatible EventEmitter implementation for browser environments with support for max listeners configuration.
class EventEmitter extends EventEmitter3 {
setMaxListeners(maxListeners: number): this;
getMaxListeners(): number;
}Advanced promise helpers including timeout handling, polling mechanisms, and deferred promise implementation with state tracking.
function waitWithTimeout<T>(
awaitable: Promise<T> | AsyncFunction<T>,
timeout: number,
error?: Error
): Promise<T | undefined>;
class Web3DeferredPromise<T> implements Promise<T> {
readonly state: 'pending' | 'fulfilled' | 'rejected';
resolve(value: T | PromiseLike<T>): void;
reject(reason?: unknown): void;
}Complete JSON-RPC protocol utilities including request/response validation, batch operations, and comprehensive type guards.
function toPayload<ParamType>(request: JsonRpcOptionalRequest<ParamType>): JsonRpcPayload<ParamType>;
function validateResponse<Result, Error>(response: JsonRpcResponse<Result, Error>): boolean;
function isBatchResponse<Result, Error>(response: JsonRpcResponse<Result, Error>): response is JsonRpcBatchResponse<Result, Error>;Abstract base classes for implementing EIP-1193 compatible providers and socket-based connections with automatic reconnection support.
abstract class Eip1193Provider<API extends Web3APISpec = EthExecutionAPI> extends Web3BaseProvider<API> {
protected _onConnect(): void;
protected _onDisconnect(code: number, data?: unknown): void;
}
abstract class SocketProvider<MessageEvent, CloseEvent, ErrorEvent, API extends Web3APISpec = EthExecutionAPI> extends Eip1193Provider<API> {
connect(): void;
disconnect(code?: number, data?: string): void;
supportsSubscriptions(): boolean;
}String padding, two's complement conversion, object merging, and Uint8Array operations for data processing.
function padLeft(value: Numbers, characterAmount: number, sign?: string): string;
function padRight(value: Numbers, characterAmount: number, sign?: string): string;
function toTwosComplement(value: Numbers, nibbleWidth?: number): string;
function mergeDeep(destination: Record<string, unknown>, ...sources: Record<string, unknown>[]): Record<string, unknown>;Secure random value generation and validation utilities for cryptographic applications and data validation.
function randomBytes(size: number): Uint8Array;
function randomHex(byteSize: number): string;
function uuidV4(): string;
function isUint8Array(data: unknown | Uint8Array): data is Uint8Array;Random Generation and Validation
type EtherUnits = keyof typeof ethUnitMap;
type AsyncFunction<T, K = unknown> = (...args: K[]) => Promise<T>;
type Timer = ReturnType<typeof setInterval>;
type Timeout = ReturnType<typeof setTimeout>;
type ReconnectOptions = {
autoReconnect: boolean;
delay: number;
maxAttempts: number;
};