or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-web3-providers-ipc

IPC provider for Web3 4.x.x that enables secure communication with local Ethereum nodes through IPC sockets

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/web3-providers-ipc@4.0.x

To install, run

npx @tessl/cli install tessl/npm-web3-providers-ipc@4.0.0

index.mddocs/

Web3 IPC Provider

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.

Package Information

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

Core Imports

import { IpcProvider } from "web3-providers-ipc";

Default import is also supported:

import IpcProvider from "web3-providers-ipc";

For CommonJS:

const { IpcProvider } = require("web3-providers-ipc");

Basic Usage

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'

Architecture

The IPC Provider is built on a robust inheritance hierarchy:

  • Web3BaseProvider: Foundation with legacy Web3.js compatibility
  • Eip1193Provider: EIP-1193 compliant provider interface
  • SocketProvider: Abstract socket-based provider with reconnection logic
  • IpcProvider: Concrete IPC implementation using Node.js net sockets

Key features include automatic reconnection, request queuing, comprehensive event handling, and full EIP-1193 compliance for seamless integration with Web3.js ecosystem.

Capabilities

IPC Provider Class

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 module
  • reconnectOptions: Optional reconnection behavior configuration with defaults:
    • autoReconnect: true - Automatically reconnect on connection loss
    • delay: 5000 - Delay in milliseconds between reconnection attempts
    • maxAttempts: 5 - Maximum number of reconnection attempts

Example:

const provider = new IpcProvider(
  "/Users/alice/.ethereum/geth.ipc",
  { writable: false },
  { delay: 500, autoReconnect: true, maxAttempts: 10 }
);

Socket Connection Property

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
}

Connection Management

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 lost

Connection Methods:

  • connect(): Establishes the IPC socket connection
  • disconnect(): Closes the connection with optional close code and reason
  • reset(): Resets the provider, clearing all listeners and pending requests
  • supportsSubscriptions(): Returns true - IPC providers support subscriptions

Example:

// Manual connection management
provider.connect();
await provider.disconnect(1000, "User disconnection");

// Check subscription support
if (provider.supportsSubscriptions()) {
  // Set up event subscriptions
}

JSON-RPC Requests

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 parameters

Returns: 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"]
});

Event Handling

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 established
  • disconnect: Fired when connection is lost
  • message: Fired for incoming JSON-RPC messages
  • chainChanged: Fired when active chain changes
  • accountsChanged: Fired when account list changes

Example:

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

Legacy Methods

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.

Types

ReconnectOptions

Configuration for automatic reconnection behavior.

interface ReconnectOptions {
  autoReconnect: boolean;  // Default: true
  delay: number;          // Default: 5000 (milliseconds)
  maxAttempts: number;    // Default: 5
}

Web3ProviderStatus

Current connection status of the provider.

type Web3ProviderStatus = "connecting" | "connected" | "disconnected";

SocketConstructorOpts

Socket configuration options from Node.js net module.

interface SocketConstructorOpts {
  fd?: number;
  allowHalfOpen?: boolean;
  readable?: boolean;
  writable?: boolean;
  signal?: AbortSignal;
}

ProviderConnectInfo

Information provided when connection is established.

interface ProviderConnectInfo {
  chainId: string;
}

ProviderRpcError

Error information for RPC and connection failures.

interface ProviderRpcError extends Error {
  code: number;
  data?: unknown;
}

Web3APIPayload

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

ProviderMessage

Message structure for provider message events.

interface ProviderMessage {
  type: string;
  data: unknown;
}

JsonRpcId

Identifier type for JSON-RPC requests.

type JsonRpcId = string | number | null;

JsonRpcResponse

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

JsonRpcRequest

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

JsonRpcResult

Generic result type for JSON-RPC responses.

type JsonRpcResult = string | number | boolean | object | null;

Eip1193Provider

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

Platform Requirements

  • Node.js: 14.x or higher
  • Platform: Unix-like systems (Linux, macOS) for Unix domain sockets, Windows for named pipes
  • Local Node Required: Must have a local Ethereum node running with IPC enabled
  • Socket Permissions: Read/write access to the IPC socket file

Security Considerations

IPC provides the most secure connection method because:

  • No network exposure (local socket only)
  • Operating system-level permissions control access
  • No risk of network interception or man-in-the-middle attacks
  • Direct process-to-process communication

Always ensure proper file system permissions on the IPC socket to prevent unauthorized access.