IPC provider for Web3 4.x.x that enables secure communication with local Ethereum nodes through IPC sockets
npx @tessl/cli install tessl/npm-web3-providers-ipc@4.0.0Web3 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.
npm install web3-providers-ipcimport { IpcProvider } from "web3-providers-ipc";Default import is also supported:
import IpcProvider from "web3-providers-ipc";For CommonJS:
const { IpcProvider } = require("web3-providers-ipc");import { IpcProvider } from "web3-providers-ipc";
// Basic IPC provider setup
const provider = new IpcProvider("/path/to/geth.ipc");
// Make JSON-RPC requests
const result = await provider.request({
method: "eth_getBlockByNumber",
params: ["latest", false]
});
// Check connection status
console.log(provider.getStatus()); // 'connected' | 'connecting' | 'disconnected'The IPC Provider is built on a robust inheritance hierarchy:
Key features include automatic reconnection, request queuing, comprehensive event handling, and full EIP-1193 compliance for seamless integration with Web3.js ecosystem.
The main provider class for establishing IPC connections to local Ethereum nodes.
class IpcProvider<API extends Web3APISpec = EthExecutionAPI> extends SocketProvider<
Uint8Array | string,
CloseEvent,
Error,
API
> {
constructor(
socketPath: string,
socketOptions?: SocketConstructorOpts,
reconnectOptions?: Partial<ReconnectOptions>
);
getStatus(): Web3ProviderStatus;
get SocketConnection(): Socket | undefined;
}Parameters:
socketPath: Path to the IPC socket file (e.g., /tmp/geth.ipc)socketOptions: Optional Node.js socket configuration options from the net modulereconnectOptions: Optional reconnection behavior configuration with defaults:
autoReconnect: true - Automatically reconnect on connection lossdelay: 5000 - Delay in milliseconds between reconnection attemptsmaxAttempts: 5 - Maximum number of reconnection attemptsExample:
const provider = new IpcProvider(
"/Users/alice/.ethereum/geth.ipc",
{ writable: false },
{ delay: 500, autoReconnect: true, maxAttempts: 10 }
);Access to the underlying Node.js socket connection.
get SocketConnection(): Socket | undefined;Returns: The underlying Node.js Socket instance, or undefined if not connected.
Example:
if (provider.SocketConnection) {
console.log("Socket is connected");
// Access socket properties if needed
}Methods for managing the IPC socket connection lifecycle.
connect(): void;
disconnect(code?: number, data?: string): void;
reset(): void;
supportsSubscriptions(): boolean;
getStatus(): Web3ProviderStatus;Status Values:
'connecting': Connection attempt in progress'connected': Successfully connected and ready for requests'disconnected': Not connected or connection lostConnection Methods:
connect(): Establishes the IPC socket connectiondisconnect(): Closes the connection with optional close code and reasonreset(): Resets the provider, clearing all listeners and pending requestssupportsSubscriptions(): Returns true - IPC providers support subscriptionsExample:
// Manual connection management
provider.connect();
await provider.disconnect(1000, "User disconnection");
// Check subscription support
if (provider.supportsSubscriptions()) {
// Set up event subscriptions
}EIP-1193 compliant request method for interacting with Ethereum nodes.
request<Method extends Web3APIMethod<API>, ResultType = Web3APIReturnType<API, Method>>(
request: Web3APIPayload<API, Method>
): Promise<JsonRpcResponseWithResult<ResultType>>;Parameters:
request: JSON-RPC request payload with method and parametersReturns: Promise resolving to JSON-RPC response with result
Example:
// Get latest block
const latestBlock = await provider.request({
method: "eth_getBlockByNumber",
params: ["latest", false]
});
// Get account balance
const balance = await provider.request({
method: "eth_getBalance",
params: ["0x742d35Cc6634C0532925a3b8D404fddE5f9b87A5", "latest"]
});EIP-1193 compliant event system for monitoring provider and blockchain events.
on(type: "connect", listener: (info: ProviderConnectInfo) => void): void;
on(type: "disconnect", listener: (error: ProviderRpcError) => void): void;
on(type: "message", listener: (message: ProviderMessage) => void): void;
on(type: "chainChanged", listener: (chainId: string) => void): void;
on(type: "accountsChanged", listener: (accounts: string[]) => void): void;
once(type: "connect", listener: (info: ProviderConnectInfo) => void): void;
once(type: "disconnect", listener: (error: ProviderRpcError) => void): void;
once(type: "message", listener: (message: ProviderMessage) => void): void;
once(type: "chainChanged", listener: (chainId: string) => void): void;
once(type: "accountsChanged", listener: (accounts: string[]) => void): void;
removeListener(
type: "connect" | "disconnect" | "message" | "chainChanged" | "accountsChanged",
listener: Function
): void;
removeAllListeners(type: string): void;Event Types:
connect: Fired when connection is establisheddisconnect: Fired when connection is lostmessage: Fired for incoming JSON-RPC messageschainChanged: Fired when active chain changesaccountsChanged: Fired when account list changesExample:
// Connection events
provider.on("connect", (info) => {
console.log("Connected to chain:", info.chainId);
});
provider.on("disconnect", (error) => {
console.log("Disconnected:", error.message);
});
// Blockchain events
provider.on("chainChanged", (chainId) => {
console.log("Chain changed to:", chainId);
});Deprecated methods maintained for backward compatibility with older Web3.js versions.
send<ResultType = JsonRpcResult, P = unknown>(
payload: JsonRpcRequest<P> | JsonRpcBatchRequest<P>,
callback: (error: Error | null, result?: JsonRpcResponse<ResultType>) => void
): void;
sendAsync<ResultType = JsonRpcResult, P = unknown>(
payload: JsonRpcRequest<P> | JsonRpcBatchRequest<P>
): Promise<JsonRpcResponse<ResultType> | JsonRpcBatchResponse<ResultType>>;
asEIP1193Provider(): Eip1193Provider<API>;Note: These methods are deprecated. Use request() method for new implementations.
Configuration for automatic reconnection behavior.
interface ReconnectOptions {
autoReconnect: boolean; // Default: true
delay: number; // Default: 5000 (milliseconds)
maxAttempts: number; // Default: 5
}Current connection status of the provider.
type Web3ProviderStatus = "connecting" | "connected" | "disconnected";Socket configuration options from Node.js net module.
interface SocketConstructorOpts {
fd?: number;
allowHalfOpen?: boolean;
readable?: boolean;
writable?: boolean;
signal?: AbortSignal;
}Information provided when connection is established.
interface ProviderConnectInfo {
chainId: string;
}Error information for RPC and connection failures.
interface ProviderRpcError extends Error {
code: number;
data?: unknown;
}JSON-RPC request payload structure.
interface Web3APIPayload<API extends Web3APISpec, Method extends Web3APIMethod<API>> {
method: Method;
params?: Web3APIParams<API, Method>;
id?: JsonRpcId;
jsonrpc?: "2.0";
}Message structure for provider message events.
interface ProviderMessage {
type: string;
data: unknown;
}Identifier type for JSON-RPC requests.
type JsonRpcId = string | number | null;Standard JSON-RPC response structure.
interface JsonRpcResponse<T = JsonRpcResult> {
jsonrpc: "2.0";
id: JsonRpcId;
result?: T;
error?: JsonRpcError;
}
interface JsonRpcResponseWithResult<T = JsonRpcResult> {
jsonrpc: "2.0";
id: JsonRpcId;
result: T;
}
interface JsonRpcError {
code: number;
message: string;
data?: unknown;
}Standard JSON-RPC request structure.
interface JsonRpcRequest<T = unknown> {
jsonrpc: "2.0";
id: JsonRpcId;
method: string;
params?: T;
}
interface JsonRpcBatchRequest<T = unknown> extends Array<JsonRpcRequest<T>> {}
interface JsonRpcBatchResponse<T = JsonRpcResult> extends Array<JsonRpcResponse<T>> {}Generic result type for JSON-RPC responses.
type JsonRpcResult = string | number | boolean | object | null;EIP-1193 compliant provider interface returned by asEIP1193Provider().
interface Eip1193Provider<API extends Web3APISpec = EthExecutionAPI> {
request<Method extends Web3APIMethod<API>, ResultType = Web3APIReturnType<API, Method>>(
request: Web3APIPayload<API, Method>
): Promise<JsonRpcResponseWithResult<ResultType>>;
on(eventName: string, listener: Function): void;
removeListener(eventName: string, listener: Function): void;
}
## Error Handling
The provider throws specific error types for different failure scenarios:
- **ConnectionNotOpenError**: Thrown when attempting to send requests on a disconnected provider
- **InvalidClientError**: Thrown when the IPC socket path doesn't exist or is inaccessible
- **MaxAttemptsReachedOnReconnectingError**: Thrown when reconnection attempts exceed the configured maximum
- **PendingRequestsOnReconnectingError**: Thrown when there are pending requests during reconnection
```typescript
try {
const result = await provider.request({
method: "eth_getBlockByNumber",
params: ["latest", false]
});
} catch (error) {
if (error instanceof ConnectionNotOpenError) {
console.log("Provider is not connected");
} else if (error instanceof InvalidClientError) {
console.log("Invalid IPC socket path");
}
}IPC provides the most secure connection method because:
Always ensure proper file system permissions on the IPC socket to prevent unauthorized access.