Collection of utility functions used in web3.js for Ethereum dApp development
npx @tessl/cli install tessl/npm-web3-utils@4.3.00
# Web3-Utils
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: web3-utils
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install web3-utils`
10
11
## Core Imports
12
13
```typescript
14
import {
15
toHex, fromWei, toWei, keccak256, randomHex,
16
utf8ToBytes, EventEmitter, Web3DeferredPromise
17
} from "web3-utils";
18
```
19
20
For CommonJS:
21
22
```javascript
23
const {
24
toHex, fromWei, toWei, keccak256, randomHex,
25
utf8ToBytes, EventEmitter, Web3DeferredPromise
26
} = require("web3-utils");
27
```
28
29
## Basic Usage
30
31
```typescript
32
import { toHex, fromWei, toWei, keccak256, toChecksumAddress } from "web3-utils";
33
34
// Convert values to hex
35
const hexValue = toHex(1234); // "0x4d2"
36
const hexString = toHex("Hello"); // "0x48656c6c6f"
37
38
// Convert between wei and ether units
39
const ethAmount = fromWei("1000000000000000000", "ether"); // "1"
40
const weiAmount = toWei("1.5", "ether"); // "1500000000000000000"
41
42
// Hash data
43
const hash = keccak256("hello world"); // "0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad"
44
45
// Format address with checksum
46
const checksumAddr = toChecksumAddress("0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed");
47
// "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAeD"
48
```
49
50
## Architecture
51
52
Web3-Utils is organized around several key functional areas:
53
54
- **Data Conversion**: Comprehensive type conversion between hex, bytes, numbers, strings, and Ethereum units
55
- **Cryptographic Hashing**: Keccak-256 and Solidity-style hashing functions for data integrity
56
- **Address Utilities**: Address validation, checksum formatting, and Ethereum address operations
57
- **Event System**: Node.js-compatible EventEmitter implementation for browser environments
58
- **Promise Utilities**: Advanced promise helpers including timeouts, polling, and deferred promises
59
- **JSON-RPC Support**: Complete JSON-RPC protocol utilities and type guards
60
- **Provider Abstractions**: Abstract base classes for EIP-1193 and socket-based providers
61
- **Random Generation**: Secure random value generation for cryptographic applications
62
- **Validation**: Type guards and validation functions (many deprecated in favor of web3-validator)
63
64
## Capabilities
65
66
### Data Type Conversion
67
68
Comprehensive conversion utilities for transforming data between hex, bytes, numbers, strings, and Ethereum units. Essential for handling blockchain data formats.
69
70
```typescript { .api }
71
function toHex(value: Numbers | Bytes | Address | boolean | object, returnType?: boolean): HexString | ValueTypes;
72
function toNumber(value: Numbers): number | bigint;
73
function toBigInt(value: unknown): bigint;
74
function fromWei(number: Numbers, unit: EtherUnits | number): string;
75
function toWei(number: Numbers, unit: EtherUnits | number): string;
76
```
77
78
[Data Conversion](./conversion.md)
79
80
### Cryptographic Hashing
81
82
Keccak-256 hashing functions and Solidity-style packed encoding for data integrity and smart contract interaction.
83
84
```typescript { .api }
85
function keccak256(data: Bytes | Numbers | string | ReadonlyArray<number>): string;
86
function sha3(data: Bytes): string | undefined;
87
function soliditySha3(...values: Sha3Input[]): string | undefined;
88
function encodePacked(...values: Sha3Input[]): string;
89
```
90
91
[Cryptographic Hashing](./hashing.md)
92
93
### Event System
94
95
Node.js-compatible EventEmitter implementation for browser environments with support for max listeners configuration.
96
97
```typescript { .api }
98
class EventEmitter extends EventEmitter3 {
99
setMaxListeners(maxListeners: number): this;
100
getMaxListeners(): number;
101
}
102
```
103
104
[Event System](./events.md)
105
106
### Promise Utilities
107
108
Advanced promise helpers including timeout handling, polling mechanisms, and deferred promise implementation with state tracking.
109
110
```typescript { .api }
111
function waitWithTimeout<T>(
112
awaitable: Promise<T> | AsyncFunction<T>,
113
timeout: number,
114
error?: Error
115
): Promise<T | undefined>;
116
117
class Web3DeferredPromise<T> implements Promise<T> {
118
readonly state: 'pending' | 'fulfilled' | 'rejected';
119
resolve(value: T | PromiseLike<T>): void;
120
reject(reason?: unknown): void;
121
}
122
```
123
124
[Promise Utilities](./promises.md)
125
126
### JSON-RPC Protocol
127
128
Complete JSON-RPC protocol utilities including request/response validation, batch operations, and comprehensive type guards.
129
130
```typescript { .api }
131
function toPayload<ParamType>(request: JsonRpcOptionalRequest<ParamType>): JsonRpcPayload<ParamType>;
132
function validateResponse<Result, Error>(response: JsonRpcResponse<Result, Error>): boolean;
133
function isBatchResponse<Result, Error>(response: JsonRpcResponse<Result, Error>): response is JsonRpcBatchResponse<Result, Error>;
134
```
135
136
[JSON-RPC Protocol](./json-rpc.md)
137
138
### Provider Abstractions
139
140
Abstract base classes for implementing EIP-1193 compatible providers and socket-based connections with automatic reconnection support.
141
142
```typescript { .api }
143
abstract class Eip1193Provider<API extends Web3APISpec = EthExecutionAPI> extends Web3BaseProvider<API> {
144
protected _onConnect(): void;
145
protected _onDisconnect(code: number, data?: unknown): void;
146
}
147
148
abstract class SocketProvider<MessageEvent, CloseEvent, ErrorEvent, API extends Web3APISpec = EthExecutionAPI> extends Eip1193Provider<API> {
149
connect(): void;
150
disconnect(code?: number, data?: string): void;
151
supportsSubscriptions(): boolean;
152
}
153
```
154
155
[Provider Abstractions](./providers.md)
156
157
### String and Data Manipulation
158
159
String padding, two's complement conversion, object merging, and Uint8Array operations for data processing.
160
161
```typescript { .api }
162
function padLeft(value: Numbers, characterAmount: number, sign?: string): string;
163
function padRight(value: Numbers, characterAmount: number, sign?: string): string;
164
function toTwosComplement(value: Numbers, nibbleWidth?: number): string;
165
function mergeDeep(destination: Record<string, unknown>, ...sources: Record<string, unknown>[]): Record<string, unknown>;
166
```
167
168
[String and Data Manipulation](./data-manipulation.md)
169
170
### Random Generation and Validation
171
172
Secure random value generation and validation utilities for cryptographic applications and data validation.
173
174
```typescript { .api }
175
function randomBytes(size: number): Uint8Array;
176
function randomHex(byteSize: number): string;
177
function uuidV4(): string;
178
function isUint8Array(data: unknown | Uint8Array): data is Uint8Array;
179
```
180
181
[Random Generation and Validation](./random-validation.md)
182
183
## Types
184
185
```typescript { .api }
186
type EtherUnits = keyof typeof ethUnitMap;
187
type AsyncFunction<T, K = unknown> = (...args: K[]) => Promise<T>;
188
type Timer = ReturnType<typeof setInterval>;
189
type Timeout = ReturnType<typeof setTimeout>;
190
type ReconnectOptions = {
191
autoReconnect: boolean;
192
delay: number;
193
maxAttempts: number;
194
};
195
```