0
# Web3.js
1
2
Web3.js is a comprehensive TypeScript library for interacting with the Ethereum blockchain. It provides a complete JavaScript API implementation of Ethereum JSON RPC specifications with modular architecture, tree-shaking support, and plugin extensibility. The library offers abstractions over JSON-RPC calls, dynamic contract type generation, and utilities for account management, transaction handling, smart contract interaction, ENS resolution, and various Ethereum-specific data types and encoding functions.
3
4
## Package Information
5
6
- **Package Name**: web3
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install web3`
10
11
## Core Imports
12
13
```typescript
14
import Web3 from 'web3';
15
```
16
17
For specific modules:
18
19
```typescript
20
import {
21
Web3,
22
Web3Eth,
23
Contract,
24
ContractDeploySend,
25
ContractMethodSend,
26
Web3Validator,
27
utils
28
} from 'web3';
29
```
30
31
For namespace imports:
32
33
```typescript
34
import { Web3, errors, rpcMethods, validator } from 'web3';
35
```
36
37
CommonJS:
38
39
```javascript
40
const Web3 = require('web3');
41
```
42
43
## Basic Usage
44
45
```typescript
46
import Web3 from 'web3';
47
48
// Initialize with provider
49
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');
50
51
// Get account balance
52
const balance = await web3.eth.getBalance('0x742C1382...1F8E');
53
console.log(web3.utils.fromWei(balance, 'ether')); // Convert to ether
54
55
// Create an account
56
const account = web3.eth.accounts.create();
57
console.log(account.address, account.privateKey);
58
59
// Interact with a contract
60
const contract = new web3.eth.Contract(abi, contractAddress);
61
const result = await contract.methods.someMethod().call();
62
```
63
64
## Architecture
65
66
Web3.js is built around several key components:
67
68
- **Web3 Class**: Main umbrella class providing access to all modules
69
- **Provider System**: Flexible provider architecture supporting HTTP, WebSocket, and IPC connections
70
- **Module System**: Modular design with separate packages for different functionality areas
71
- **Plugin Architecture**: Extensible system allowing custom functionality integration
72
- **Type Safety**: Full TypeScript support with comprehensive type definitions
73
- **Context System**: Shared configuration and provider management across modules
74
75
## Capabilities
76
77
### Core Web3 Instance
78
79
The main Web3 class that provides access to all Ethereum-related functionality through a unified interface.
80
81
```typescript { .api }
82
class Web3<CustomRegisteredSubscription = RegisteredSubscription> {
83
constructor(
84
providerOrContext?:
85
| string
86
| SupportedProviders<EthExecutionAPI>
87
| Web3ContextInitOptions<EthExecutionAPI, CustomRegisteredSubscription>
88
);
89
90
static version: string;
91
static utils: typeof utils;
92
static modules: {
93
Web3Eth: typeof Web3Eth;
94
Iban: typeof Iban;
95
Net: typeof Net;
96
ENS: typeof ENS;
97
Personal: typeof Personal;
98
};
99
}
100
```
101
102
[Core Web3 Instance](./core-web3.md)
103
104
### Ethereum Interaction
105
106
Complete Ethereum blockchain interaction capabilities including account management, transaction handling, and blockchain queries.
107
108
```typescript { .api }
109
interface Web3EthInterface {
110
// Account management
111
getBalance(address: Address, blockNumber?: BlockNumberOrTag): Promise<bigint>;
112
getTransactionCount(address: Address, blockNumber?: BlockNumberOrTag): Promise<bigint>;
113
114
// Transaction handling
115
sendTransaction(transaction: Transaction): PromiEvent<TransactionReceipt>;
116
estimateGas(transaction: Transaction, blockNumber?: BlockNumberOrTag): Promise<bigint>;
117
118
// Contract interaction
119
Contract: typeof Contract;
120
121
// Sub-modules
122
accounts: AccountsInterface;
123
abi: AbiInterface;
124
ens: ENS;
125
personal: Personal;
126
net: Net;
127
}
128
```
129
130
[Ethereum Interaction](./ethereum-interaction.md)
131
132
### Smart Contract Interaction
133
134
Comprehensive smart contract deployment, interaction, and event handling with full TypeScript support.
135
136
```typescript { .api }
137
class Contract<Abi extends ContractAbi> {
138
constructor(jsonInterface: Abi, address?: Address, options?: ContractInitOptions);
139
140
methods: ContractMethods<Abi>;
141
events: ContractEvents<Abi>;
142
143
deploy(options: ContractDeployOptions): ContractDeploySend<Abi>;
144
getPastEvents(eventName: string, options?: EventOptions): Promise<EventLog[]>;
145
}
146
```
147
148
[Smart Contract Interaction](./smart-contracts.md)
149
150
### Account Management
151
152
Complete account creation, management, and cryptographic operations including wallet functionality and transaction signing.
153
154
```typescript { .api }
155
interface AccountsInterface {
156
create(): Web3Account;
157
privateKeyToAccount(privateKey: Uint8Array | string): Web3Account;
158
signTransaction(transaction: Transaction, privateKey: Bytes): Promise<SignedTransactionInfoAPI>;
159
sign(data: string, privateKey: Bytes): SignResult;
160
recover(signatureObject: SignatureObject): string;
161
encrypt(privateKey: Bytes, password: string): Promise<KeyStore>;
162
decrypt(keystore: KeyStore | string, password: string): Promise<Web3Account>;
163
wallet: Wallet;
164
privateKeyToAddress(privateKey: Bytes): string;
165
privateKeyToPublicKey(privateKey: Bytes, isCompressed: boolean): string;
166
parseAndValidatePrivateKey(data: Bytes, ignoreLength?: boolean): Uint8Array;
167
}
168
```
169
170
[Account Management](./account-management.md)
171
172
### Utilities and Encoding
173
174
Extensive utility functions for data conversion, validation, hashing, and Ethereum-specific operations.
175
176
```typescript { .api }
177
interface UtilsInterface {
178
// Data conversion
179
toWei(value: NumberLike, unit?: EtherUnits): string;
180
fromWei(value: NumberLike, unit?: EtherUnits): string;
181
toHex(value: Numbers | Bytes | Address | boolean): HexString;
182
183
// Hashing
184
keccak256(data: Bytes): string;
185
sha3(data: Bytes): string;
186
187
// Validation
188
isAddress(address: string): boolean;
189
checkAddressChecksum(address: string): boolean;
190
191
// Random
192
randomHex(bytesSize: number): HexString;
193
}
194
```
195
196
[Utilities and Encoding](./utilities.md)
197
198
### Provider Management
199
200
Flexible provider system supporting multiple connection types with automatic provider detection and EIP-6963 support.
201
202
```typescript { .api }
203
class HttpProvider implements EthExecutionAPI {
204
constructor(url: string, options?: HttpProviderOptions);
205
}
206
207
class WebSocketProvider implements EthExecutionAPI {
208
constructor(url: string, clientOptions?: ClientOptions, reconnectOptions?: ReconnectOptions);
209
}
210
211
// EIP-6963 Provider Discovery
212
function requestEIP6963Providers(): Promise<EIP6963ProviderResponse>;
213
function onNewProviderDiscovered(callback: (providerEvent: EIP6963ProvidersMapUpdateEvent) => void): void;
214
```
215
216
[Provider Management](./providers.md)
217
218
### ENS Integration
219
220
Complete Ethereum Name Service integration for domain resolution, reverse lookups, and registry interactions.
221
222
```typescript { .api }
223
class ENS {
224
getAddress(name: string): Promise<string>;
225
getName(address: string): Promise<string>;
226
getResolver(name: string): Promise<string>;
227
getTTL(name: string): Promise<string>;
228
}
229
```
230
231
[ENS Integration](./ens.md)
232
233
### Contract Deployment and Method Execution
234
235
Helper types for advanced contract operations and transaction sending.
236
237
```typescript { .api }
238
class ContractDeploySend<Abi extends ContractAbi> {
239
send(options?: PayableTxOptions): PromiEvent<Contract<Abi>>;
240
estimateGas(options?: PayableTxOptions): Promise<bigint>;
241
encodeABI(): string;
242
}
243
244
class ContractMethodSend<Inputs, Outputs> {
245
send(options?: PayableTxOptions): PromiEvent<TransactionReceipt>;
246
call(options?: NonPayableTxOptions, block?: BlockNumberOrTag): Promise<Outputs>;
247
estimateGas(options?: PayableTxOptions): Promise<bigint>;
248
encodeABI(): string;
249
}
250
```
251
252
### Validation Utilities
253
254
Comprehensive validation utilities for Web3 data types and structures.
255
256
```typescript { .api }
257
class Web3Validator {
258
static validate(schema: JsonSchema, data: unknown, options?: ValidatorOptions): void;
259
static validateAndResolve(schema: JsonSchema, data: unknown, options?: ValidatorOptions): any;
260
}
261
```
262
263
### Error Handling
264
265
Complete error classes and utilities for Web3 operations (available as `errors` namespace).
266
267
```typescript { .api }
268
// Error namespace exports
269
namespace errors {
270
class Web3Error extends Error;
271
class ConnectionError extends Web3Error;
272
class InvalidMethodParamsError extends Web3Error;
273
class TransactionRevertError extends Web3Error;
274
// ... and many more error classes
275
}
276
```
277
278
### RPC Methods
279
280
Low-level RPC method utilities (available as `rpcMethods` namespace).
281
282
```typescript { .api }
283
// RPC methods namespace exports
284
namespace rpcMethods {
285
function ethBlockNumber(): JsonRpcCall;
286
function ethGetBalance(address: Address, block?: BlockNumberOrTag): JsonRpcCall;
287
function ethGetTransactionByHash(hash: Bytes): JsonRpcCall;
288
// ... and many more RPC method builders
289
}
290
```
291
292
### Validation Namespace
293
294
Additional validation utilities (available as `validator` namespace).
295
296
```typescript { .api }
297
// Validator namespace exports
298
namespace validator {
299
function isAddress(value: unknown): boolean;
300
function isHexStrict(value: unknown): boolean;
301
function isBloom(value: unknown): boolean;
302
// ... and many more validation functions
303
}
304
```
305
306
## Types
307
308
```typescript { .api }
309
interface Web3Account {
310
address: string;
311
privateKey: string;
312
signTransaction(transaction: Transaction): Promise<SignedTransactionInfoAPI>;
313
sign(data: string): SignResult;
314
encrypt(password: string): Promise<KeyStore>;
315
}
316
317
interface Transaction {
318
to?: Address;
319
from?: Address;
320
value?: Numbers;
321
gas?: Numbers;
322
gasPrice?: Numbers;
323
maxFeePerGas?: Numbers;
324
maxPriorityFeePerGas?: Numbers;
325
data?: Bytes;
326
nonce?: Numbers;
327
type?: Numbers;
328
accessList?: AccessList;
329
}
330
331
interface TransactionReceipt {
332
transactionHash: string;
333
transactionIndex: bigint;
334
blockNumber: bigint;
335
blockHash: string;
336
from: string;
337
to: string;
338
gasUsed: bigint;
339
cumulativeGasUsed: bigint;
340
logs: Log[];
341
status: bigint;
342
}
343
344
type Address = string;
345
type Bytes = string | Uint8Array;
346
type Numbers = number | bigint | string;
347
type HexString = string;
348
```