0
# Web3 IPC Provider
1
2
Web3 IPC Provider enables secure communication with local Ethereum nodes through Inter Process Communication (IPC) sockets. It provides the most secure connection method for Node.js applications by establishing Unix domain socket or named pipe connections to local blockchain nodes.
3
4
## Package Information
5
6
- **Package Name**: web3-providers-ipc
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install web3-providers-ipc`
10
11
## Core Imports
12
13
```typescript
14
import { IpcProvider } from "web3-providers-ipc";
15
```
16
17
Default import is also supported:
18
19
```typescript
20
import IpcProvider from "web3-providers-ipc";
21
```
22
23
For CommonJS:
24
25
```javascript
26
const { IpcProvider } = require("web3-providers-ipc");
27
```
28
29
## Basic Usage
30
31
```typescript
32
import { IpcProvider } from "web3-providers-ipc";
33
34
// Basic IPC provider setup
35
const provider = new IpcProvider("/path/to/geth.ipc");
36
37
// Make JSON-RPC requests
38
const result = await provider.request({
39
method: "eth_getBlockByNumber",
40
params: ["latest", false]
41
});
42
43
// Check connection status
44
console.log(provider.getStatus()); // 'connected' | 'connecting' | 'disconnected'
45
```
46
47
## Architecture
48
49
The IPC Provider is built on a robust inheritance hierarchy:
50
51
- **Web3BaseProvider**: Foundation with legacy Web3.js compatibility
52
- **Eip1193Provider**: EIP-1193 compliant provider interface
53
- **SocketProvider**: Abstract socket-based provider with reconnection logic
54
- **IpcProvider**: Concrete IPC implementation using Node.js net sockets
55
56
Key features include automatic reconnection, request queuing, comprehensive event handling, and full EIP-1193 compliance for seamless integration with Web3.js ecosystem.
57
58
## Capabilities
59
60
### IPC Provider Class
61
62
The main provider class for establishing IPC connections to local Ethereum nodes.
63
64
```typescript { .api }
65
class IpcProvider<API extends Web3APISpec = EthExecutionAPI> extends SocketProvider<
66
Uint8Array | string,
67
CloseEvent,
68
Error,
69
API
70
> {
71
constructor(
72
socketPath: string,
73
socketOptions?: SocketConstructorOpts,
74
reconnectOptions?: Partial<ReconnectOptions>
75
);
76
77
getStatus(): Web3ProviderStatus;
78
get SocketConnection(): Socket | undefined;
79
}
80
```
81
82
**Parameters:**
83
- `socketPath`: Path to the IPC socket file (e.g., `/tmp/geth.ipc`)
84
- `socketOptions`: Optional Node.js socket configuration options from the `net` module
85
- `reconnectOptions`: Optional reconnection behavior configuration with defaults:
86
- `autoReconnect: true` - Automatically reconnect on connection loss
87
- `delay: 5000` - Delay in milliseconds between reconnection attempts
88
- `maxAttempts: 5` - Maximum number of reconnection attempts
89
90
**Example:**
91
```typescript
92
const provider = new IpcProvider(
93
"/Users/alice/.ethereum/geth.ipc",
94
{ writable: false },
95
{ delay: 500, autoReconnect: true, maxAttempts: 10 }
96
);
97
```
98
99
### Socket Connection Property
100
101
Access to the underlying Node.js socket connection.
102
103
```typescript { .api }
104
get SocketConnection(): Socket | undefined;
105
```
106
107
**Returns:** The underlying Node.js `Socket` instance, or `undefined` if not connected.
108
109
**Example:**
110
```typescript
111
if (provider.SocketConnection) {
112
console.log("Socket is connected");
113
// Access socket properties if needed
114
}
115
```
116
117
### Connection Management
118
119
Methods for managing the IPC socket connection lifecycle.
120
121
```typescript { .api }
122
connect(): void;
123
disconnect(code?: number, data?: string): void;
124
reset(): void;
125
supportsSubscriptions(): boolean;
126
getStatus(): Web3ProviderStatus;
127
```
128
129
**Status Values:**
130
- `'connecting'`: Connection attempt in progress
131
- `'connected'`: Successfully connected and ready for requests
132
- `'disconnected'`: Not connected or connection lost
133
134
**Connection Methods:**
135
- `connect()`: Establishes the IPC socket connection
136
- `disconnect()`: Closes the connection with optional close code and reason
137
- `reset()`: Resets the provider, clearing all listeners and pending requests
138
- `supportsSubscriptions()`: Returns `true` - IPC providers support subscriptions
139
140
**Example:**
141
```typescript
142
// Manual connection management
143
provider.connect();
144
await provider.disconnect(1000, "User disconnection");
145
146
// Check subscription support
147
if (provider.supportsSubscriptions()) {
148
// Set up event subscriptions
149
}
150
```
151
152
### JSON-RPC Requests
153
154
EIP-1193 compliant request method for interacting with Ethereum nodes.
155
156
```typescript { .api }
157
request<Method extends Web3APIMethod<API>, ResultType = Web3APIReturnType<API, Method>>(
158
request: Web3APIPayload<API, Method>
159
): Promise<JsonRpcResponseWithResult<ResultType>>;
160
```
161
162
**Parameters:**
163
- `request`: JSON-RPC request payload with method and parameters
164
165
**Returns:** Promise resolving to JSON-RPC response with result
166
167
**Example:**
168
```typescript
169
// Get latest block
170
const latestBlock = await provider.request({
171
method: "eth_getBlockByNumber",
172
params: ["latest", false]
173
});
174
175
// Get account balance
176
const balance = await provider.request({
177
method: "eth_getBalance",
178
params: ["0x742d35Cc6634C0532925a3b8D404fddE5f9b87A5", "latest"]
179
});
180
```
181
182
### Event Handling
183
184
EIP-1193 compliant event system for monitoring provider and blockchain events.
185
186
```typescript { .api }
187
on(type: "connect", listener: (info: ProviderConnectInfo) => void): void;
188
on(type: "disconnect", listener: (error: ProviderRpcError) => void): void;
189
on(type: "message", listener: (message: ProviderMessage) => void): void;
190
on(type: "chainChanged", listener: (chainId: string) => void): void;
191
on(type: "accountsChanged", listener: (accounts: string[]) => void): void;
192
193
once(type: "connect", listener: (info: ProviderConnectInfo) => void): void;
194
once(type: "disconnect", listener: (error: ProviderRpcError) => void): void;
195
once(type: "message", listener: (message: ProviderMessage) => void): void;
196
once(type: "chainChanged", listener: (chainId: string) => void): void;
197
once(type: "accountsChanged", listener: (accounts: string[]) => void): void;
198
199
removeListener(
200
type: "connect" | "disconnect" | "message" | "chainChanged" | "accountsChanged",
201
listener: Function
202
): void;
203
204
removeAllListeners(type: string): void;
205
```
206
207
**Event Types:**
208
- `connect`: Fired when connection is established
209
- `disconnect`: Fired when connection is lost
210
- `message`: Fired for incoming JSON-RPC messages
211
- `chainChanged`: Fired when active chain changes
212
- `accountsChanged`: Fired when account list changes
213
214
**Example:**
215
```typescript
216
// Connection events
217
provider.on("connect", (info) => {
218
console.log("Connected to chain:", info.chainId);
219
});
220
221
provider.on("disconnect", (error) => {
222
console.log("Disconnected:", error.message);
223
});
224
225
// Blockchain events
226
provider.on("chainChanged", (chainId) => {
227
console.log("Chain changed to:", chainId);
228
});
229
```
230
231
### Legacy Methods
232
233
Deprecated methods maintained for backward compatibility with older Web3.js versions.
234
235
```typescript { .api }
236
send<ResultType = JsonRpcResult, P = unknown>(
237
payload: JsonRpcRequest<P> | JsonRpcBatchRequest<P>,
238
callback: (error: Error | null, result?: JsonRpcResponse<ResultType>) => void
239
): void;
240
241
sendAsync<ResultType = JsonRpcResult, P = unknown>(
242
payload: JsonRpcRequest<P> | JsonRpcBatchRequest<P>
243
): Promise<JsonRpcResponse<ResultType> | JsonRpcBatchResponse<ResultType>>;
244
245
asEIP1193Provider(): Eip1193Provider<API>;
246
```
247
248
**Note:** These methods are deprecated. Use `request()` method for new implementations.
249
250
## Types
251
252
### ReconnectOptions
253
254
Configuration for automatic reconnection behavior.
255
256
```typescript { .api }
257
interface ReconnectOptions {
258
autoReconnect: boolean; // Default: true
259
delay: number; // Default: 5000 (milliseconds)
260
maxAttempts: number; // Default: 5
261
}
262
```
263
264
### Web3ProviderStatus
265
266
Current connection status of the provider.
267
268
```typescript { .api }
269
type Web3ProviderStatus = "connecting" | "connected" | "disconnected";
270
```
271
272
### SocketConstructorOpts
273
274
Socket configuration options from Node.js `net` module.
275
276
```typescript { .api }
277
interface SocketConstructorOpts {
278
fd?: number;
279
allowHalfOpen?: boolean;
280
readable?: boolean;
281
writable?: boolean;
282
signal?: AbortSignal;
283
}
284
```
285
286
### ProviderConnectInfo
287
288
Information provided when connection is established.
289
290
```typescript { .api }
291
interface ProviderConnectInfo {
292
chainId: string;
293
}
294
```
295
296
### ProviderRpcError
297
298
Error information for RPC and connection failures.
299
300
```typescript { .api }
301
interface ProviderRpcError extends Error {
302
code: number;
303
data?: unknown;
304
}
305
```
306
307
### Web3APIPayload
308
309
JSON-RPC request payload structure.
310
311
```typescript { .api }
312
interface Web3APIPayload<API extends Web3APISpec, Method extends Web3APIMethod<API>> {
313
method: Method;
314
params?: Web3APIParams<API, Method>;
315
id?: JsonRpcId;
316
jsonrpc?: "2.0";
317
}
318
```
319
320
### ProviderMessage
321
322
Message structure for provider message events.
323
324
```typescript { .api }
325
interface ProviderMessage {
326
type: string;
327
data: unknown;
328
}
329
```
330
331
### JsonRpcId
332
333
Identifier type for JSON-RPC requests.
334
335
```typescript { .api }
336
type JsonRpcId = string | number | null;
337
```
338
339
### JsonRpcResponse
340
341
Standard JSON-RPC response structure.
342
343
```typescript { .api }
344
interface JsonRpcResponse<T = JsonRpcResult> {
345
jsonrpc: "2.0";
346
id: JsonRpcId;
347
result?: T;
348
error?: JsonRpcError;
349
}
350
351
interface JsonRpcResponseWithResult<T = JsonRpcResult> {
352
jsonrpc: "2.0";
353
id: JsonRpcId;
354
result: T;
355
}
356
357
interface JsonRpcError {
358
code: number;
359
message: string;
360
data?: unknown;
361
}
362
```
363
364
### JsonRpcRequest
365
366
Standard JSON-RPC request structure.
367
368
```typescript { .api }
369
interface JsonRpcRequest<T = unknown> {
370
jsonrpc: "2.0";
371
id: JsonRpcId;
372
method: string;
373
params?: T;
374
}
375
376
interface JsonRpcBatchRequest<T = unknown> extends Array<JsonRpcRequest<T>> {}
377
interface JsonRpcBatchResponse<T = JsonRpcResult> extends Array<JsonRpcResponse<T>> {}
378
```
379
380
### JsonRpcResult
381
382
Generic result type for JSON-RPC responses.
383
384
```typescript { .api }
385
type JsonRpcResult = string | number | boolean | object | null;
386
```
387
388
### Eip1193Provider
389
390
EIP-1193 compliant provider interface returned by asEIP1193Provider().
391
392
```typescript { .api }
393
interface Eip1193Provider<API extends Web3APISpec = EthExecutionAPI> {
394
request<Method extends Web3APIMethod<API>, ResultType = Web3APIReturnType<API, Method>>(
395
request: Web3APIPayload<API, Method>
396
): Promise<JsonRpcResponseWithResult<ResultType>>;
397
398
on(eventName: string, listener: Function): void;
399
removeListener(eventName: string, listener: Function): void;
400
}
401
402
## Error Handling
403
404
The provider throws specific error types for different failure scenarios:
405
406
- **ConnectionNotOpenError**: Thrown when attempting to send requests on a disconnected provider
407
- **InvalidClientError**: Thrown when the IPC socket path doesn't exist or is inaccessible
408
- **MaxAttemptsReachedOnReconnectingError**: Thrown when reconnection attempts exceed the configured maximum
409
- **PendingRequestsOnReconnectingError**: Thrown when there are pending requests during reconnection
410
411
```typescript
412
try {
413
const result = await provider.request({
414
method: "eth_getBlockByNumber",
415
params: ["latest", false]
416
});
417
} catch (error) {
418
if (error instanceof ConnectionNotOpenError) {
419
console.log("Provider is not connected");
420
} else if (error instanceof InvalidClientError) {
421
console.log("Invalid IPC socket path");
422
}
423
}
424
```
425
426
## Platform Requirements
427
428
- **Node.js**: 14.x or higher
429
- **Platform**: Unix-like systems (Linux, macOS) for Unix domain sockets, Windows for named pipes
430
- **Local Node Required**: Must have a local Ethereum node running with IPC enabled
431
- **Socket Permissions**: Read/write access to the IPC socket file
432
433
## Security Considerations
434
435
IPC provides the most secure connection method because:
436
- No network exposure (local socket only)
437
- Operating system-level permissions control access
438
- No risk of network interception or man-in-the-middle attacks
439
- Direct process-to-process communication
440
441
Always ensure proper file system permissions on the IPC socket to prevent unauthorized access.