or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

conversion.mddata-manipulation.mdevents.mdhashing.mdindex.mdjson-rpc.mdpromises.mdproviders.mdrandom-validation.md
tile.json

tessl/npm-web3-utils

Collection of utility functions used in web3.js for Ethereum dApp development

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/web3-utils@4.3.x

To install, run

npx @tessl/cli install tessl/npm-web3-utils@4.3.0

index.mddocs/

Web3-Utils

Web3-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.

Package Information

  • Package Name: web3-utils
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install web3-utils

Core Imports

import { 
  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");

Basic Usage

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"

Architecture

Web3-Utils is organized around several key functional areas:

  • Data Conversion: Comprehensive type conversion between hex, bytes, numbers, strings, and Ethereum units
  • Cryptographic Hashing: Keccak-256 and Solidity-style hashing functions for data integrity
  • Address Utilities: Address validation, checksum formatting, and Ethereum address operations
  • Event System: Node.js-compatible EventEmitter implementation for browser environments
  • Promise Utilities: Advanced promise helpers including timeouts, polling, and deferred promises
  • JSON-RPC Support: Complete JSON-RPC protocol utilities and type guards
  • Provider Abstractions: Abstract base classes for EIP-1193 and socket-based providers
  • Random Generation: Secure random value generation for cryptographic applications
  • Validation: Type guards and validation functions (many deprecated in favor of web3-validator)

Capabilities

Data Type Conversion

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;

Data Conversion

Cryptographic Hashing

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;

Cryptographic Hashing

Event System

Node.js-compatible EventEmitter implementation for browser environments with support for max listeners configuration.

class EventEmitter extends EventEmitter3 {
  setMaxListeners(maxListeners: number): this;
  getMaxListeners(): number;
}

Event System

Promise Utilities

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;
}

Promise Utilities

JSON-RPC Protocol

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>;

JSON-RPC Protocol

Provider Abstractions

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;
}

Provider Abstractions

String and Data Manipulation

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>;

String and Data Manipulation

Random Generation and Validation

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

Types

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;
};