or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-web3-providers-http

HTTP provider for Web3 4.x.x that enables JSON-RPC communication with Ethereum nodes over HTTP protocol

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

To install, run

npx @tessl/cli install tessl/npm-web3-providers-http@4.1.0

index.mddocs/

Web3 HTTP Provider

Web3 HTTP Provider is a TypeScript implementation of an HTTP-based JSON-RPC provider for the Web3.js ecosystem. It enables communication with Ethereum nodes over HTTP/HTTPS protocols, providing a reliable transport layer for blockchain interactions with comprehensive error handling and type safety.

Package Information

  • Package Name: web3-providers-http
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install web3 (web3-providers-http is included as part of the Web3.js library)

Core Imports

Recommended - Use with Web3.js library:

import { Web3 } from "web3";

// HttpProvider is used automatically when you provide an HTTP URL
const web3 = new Web3("https://mainnet.infura.io/v3/YOUR_PROJECT_ID");

Direct import (advanced usage):

import HttpProvider from "web3-providers-http";

Named import:

import { HttpProvider } from "web3-providers-http";

With options interface:

import HttpProvider, { HttpProviderOptions } from "web3-providers-http";

For CommonJS:

const HttpProvider = require("web3-providers-http");
// or
const { HttpProvider } = require("web3-providers-http");

Basic Usage

Recommended - Using with Web3.js:

import { Web3 } from "web3";

// HttpProvider is used automatically for HTTP URLs
const web3 = new Web3("https://mainnet.infura.io/v3/YOUR_PROJECT_ID");

// Get account balance using Web3 convenience methods
const balance = await web3.eth.getBalance("0x742d35cc6634c0532925a3b8d404dff86c521890");
console.log(balance); // Account balance

Direct HttpProvider usage:

import HttpProvider from "web3-providers-http";

// Create provider with basic URL
const provider = new HttpProvider("https://mainnet.infura.io/v3/YOUR_PROJECT_ID");

// Create provider with custom options
const providerWithOptions = new HttpProvider(
  "https://mainnet.infura.io/v3/YOUR_PROJECT_ID",
  {
    providerOptions: {
      headers: {
        "Authorization": "Bearer your-token"
      },
      timeout: 10000
    }
  }
);

// Make JSON-RPC request
const response = await provider.request({
  jsonrpc: "2.0",
  id: 1,
  method: "eth_getBalance",
  params: ["0x742d35cc6634c0532925a3b8d404dff86c521890", "latest"]
});

console.log(response.result); // Account balance

Architecture

The Web3 HTTP Provider is built around:

  • HttpProvider Class: Main provider implementation extending Web3BaseProvider
  • Generic Type System: Full TypeScript support with Web3APISpec generics for type-safe method calls
  • URL Validation: Client URL validation ensuring HTTP/HTTPS protocols only
  • Fetch Integration: Uses cross-fetch for Node.js/browser compatibility
  • Error Handling: Comprehensive error handling with specific Web3 error types
  • Request Configuration: Supports all standard Fetch API options through HttpProviderOptions

Capabilities

HTTP Provider Class

Main provider class for HTTP-based JSON-RPC communication with Ethereum nodes.

/**
 * HTTP provider implementation for Web3.js JSON-RPC communication
 * @template API - Web3 API specification type, defaults to EthExecutionAPI
 */
export default class HttpProvider<API extends Web3APISpec = EthExecutionAPI> extends Web3BaseProvider<API> {
  /**
   * Creates a new HTTP provider instance
   * @param clientUrl - HTTP or HTTPS URL of the JSON-RPC endpoint
   * @param httpProviderOptions - Optional configuration for HTTP requests
   * @throws InvalidClientError when clientUrl is invalid
   */
  constructor(clientUrl: string, httpProviderOptions?: HttpProviderOptions);
}

JSON-RPC Request Method

Performs HTTP JSON-RPC requests with full type safety and error handling.

/**
 * Makes an HTTP JSON-RPC request to the configured endpoint
 * @template Method - The JSON-RPC method being called
 * @template ResultType - Expected return type for the method
 * @param payload - JSON-RPC payload containing method and parameters
 * @param requestOptions - Optional Fetch API RequestInit options for this specific request
 * @returns Promise resolving to JSON-RPC response with typed result
 * @throws ResponseError when HTTP response indicates an error
 */
async request<
  Method extends Web3APIMethod<API>,
  ResultType = Web3APIReturnType<API, Method>
>(
  payload: Web3APIPayload<API, Method>,
  requestOptions?: RequestInit
): Promise<JsonRpcResponseWithResult<ResultType>>;

Subscription Support Check

Indicates whether the provider supports real-time subscriptions.

/**
 * Indicates subscription support capability
 * @returns false - HTTP providers do not support subscriptions
 */
supportsSubscriptions(): boolean;

Provider Status (Not Implemented)

Provider status checking method - throws MethodNotImplementedError.

/**
 * Gets the current provider status
 * @throws MethodNotImplementedError - Not implemented for HTTP provider
 */
getStatus(): Web3ProviderStatus;

Event Handling Methods (Not Implemented)

Event handling methods required by Web3BaseProvider interface - all throw MethodNotImplementedError.

/**
 * Registers an event listener
 * @throws MethodNotImplementedError - Event handling not supported over HTTP
 */
on(): void;

/**
 * Removes an event listener
 * @throws MethodNotImplementedError - Event handling not supported over HTTP
 */
removeListener(): void;

/**
 * Registers a one-time event listener
 * @throws MethodNotImplementedError - Event handling not supported over HTTP
 */
once(): void;

/**
 * Removes all event listeners
 * @throws MethodNotImplementedError - Event handling not supported over HTTP
 */
removeAllListeners(): void;

Connection Management Methods (Not Implemented)

Connection lifecycle methods required by Web3BaseProvider interface - all throw MethodNotImplementedError.

/**
 * Establishes provider connection
 * @throws MethodNotImplementedError - Connection management not applicable for HTTP
 */
connect(): void;

/**
 * Closes provider connection
 * @throws MethodNotImplementedError - Connection management not applicable for HTTP
 */
disconnect(): void;

/**
 * Resets provider state
 * @throws MethodNotImplementedError - State management not applicable for HTTP
 */
reset(): void;

/**
 * Reconnects the provider (HttpProvider-specific method)
 * @throws MethodNotImplementedError - Connection management not applicable for HTTP
 */
reconnect(): void;

Inherited Methods from Web3BaseProvider

These methods are inherited from the Web3BaseProvider base class and provide backward compatibility and additional functionality.

/**
 * Sends a JSON-RPC request (deprecated, use request() instead)
 * @deprecated Use request() method instead
 * @param payload - JSON-RPC payload
 * @param callback - Optional callback function
 * @returns Promise resolving to JSON-RPC response
 */
send<Method extends Web3APIMethod<API>, ResultType = Web3APIReturnType<API, Method>>(
  payload: Web3APIPayload<API, Method>,
  callback?: (error: Error | null, result?: JsonRpcResponseWithResult<ResultType>) => void
): Promise<JsonRpcResponseWithResult<ResultType>>;

/**
 * Sends a JSON-RPC request asynchronously (deprecated, use request() instead)
 * @deprecated Use request() method instead
 * @param payload - JSON-RPC payload
 * @param callback - Callback function for handling response
 */
sendAsync<Method extends Web3APIMethod<API>, ResultType = Web3APIReturnType<API, Method>>(
  payload: Web3APIPayload<API, Method>,
  callback: (error: Error | null, result?: JsonRpcResponseWithResult<ResultType>) => void
): void;

/**
 * Returns an EIP-1193 compatible provider interface
 * @returns EIP1193Provider instance wrapping this provider
 */
asEIP1193Provider(): EIP1193Provider<API>;

Types

Core Web3 Types

These types are imported from the web3-types package and used throughout the provider:

/**
 * Base Web3 API specification interface
 */
interface Web3APISpec {
  [method: string]: {
    Parameters: any[];
    ReturnType: any;
  };
}

/**
 * Default Ethereum execution API specification
 */
interface EthExecutionAPI extends Web3APISpec {
  eth_getBalance: {
    Parameters: [string, string];
    ReturnType: string;
  };
  eth_blockNumber: {
    Parameters: [];
    ReturnType: string;
  };
  // ... additional Ethereum JSON-RPC methods
}

/**
 * JSON-RPC method names from API specification
 */
type Web3APIMethod<API extends Web3APISpec> = keyof API;

/**
 * JSON-RPC payload for specific method
 */
interface Web3APIPayload<API extends Web3APISpec, Method extends Web3APIMethod<API>> {
  jsonrpc: "2.0";
  id: number | string;
  method: Method;
  params: API[Method]["Parameters"];
}

/**
 * Return type for specific API method
 */
type Web3APIReturnType<API extends Web3APISpec, Method extends Web3APIMethod<API>> = 
  API[Method]["ReturnType"];

/**
 * JSON-RPC response with typed result
 */
interface JsonRpcResponseWithResult<T> {
  jsonrpc: "2.0";
  id: number | string;
  result: T;
}

/**
 * Base provider class from web3-types
 */
abstract class Web3BaseProvider<API extends Web3APISpec> {
  abstract request<Method extends Web3APIMethod<API>>(
    payload: Web3APIPayload<API, Method>
  ): Promise<JsonRpcResponseWithResult<Web3APIReturnType<API, Method>>>;
  abstract supportsSubscriptions(): boolean;
  abstract getStatus(): Web3ProviderStatus;
  // ... additional provider interface methods
}

/**
 * Provider status enumeration
 */
enum Web3ProviderStatus {
  CONNECTING = "connecting",
  CONNECTED = "connected",
  DISCONNECTED = "disconnected",
  ERROR = "error"
}

/**
 * EIP-1193 compatible provider interface
 */
interface EIP1193Provider<API extends Web3APISpec> {
  request<Method extends Web3APIMethod<API>>(
    args: { method: Method; params?: API[Method]["Parameters"] }
  ): Promise<Web3APIReturnType<API, Method>>;
  on(event: string, listener: (...args: any[]) => void): void;
  removeListener(event: string, listener: (...args: any[]) => void): void;
}

Standard Web API Types

/**
 * Standard Fetch API RequestInit interface for HTTP configuration
 */
interface RequestInit {
  method?: string;
  headers?: HeadersInit;
  body?: BodyInit | null;
  referrer?: string;
  referrerPolicy?: ReferrerPolicy;
  mode?: RequestMode;
  credentials?: RequestCredentials;
  cache?: RequestCache;
  redirect?: RequestRedirect;
  integrity?: string;
  keepalive?: boolean;
  signal?: AbortSignal | null;
  window?: any;
}

Error Types

Error types from the web3-errors package:

/**
 * Error thrown when invalid client URL is provided
 */
class InvalidClientError extends Error {
  constructor(clientUrl: string);
}

/**
 * Error thrown when calling unimplemented provider methods
 */
class MethodNotImplementedError extends Error {
  constructor();
}

/**
 * Error thrown when HTTP response indicates failure
 */
class ResponseError extends Error {
  constructor(response: any);
}

Configuration

HTTP Provider Options

Configuration interface for customizing HTTP requests and provider behavior.

/**
 * Configuration options for HTTP provider
 */
interface HttpProviderOptions {
  /** Standard Fetch API RequestInit options for HTTP requests */
  providerOptions: RequestInit;
}

The providerOptions field accepts all standard Fetch API options:

  • headers: Custom HTTP headers
  • timeout: Request timeout (browser-dependent)
  • credentials: Cookie/authentication credential handling
  • cache: Caching behavior
  • redirect: Redirect handling
  • integrity: Subresource integrity value
  • keepalive: Keep connection alive
  • referrer: Referrer information
  • referrerPolicy: Referrer policy
  • signal: AbortController signal for request cancellation

Error Handling

The provider throws specific error types for different failure scenarios:

InvalidClientError

Thrown when an invalid client URL is provided to the constructor.

try {
  const provider = new HttpProvider("invalid-url");
} catch (error) {
  // error is InvalidClientError
  console.error(`Invalid client URL: ${error.message}`);
}

MethodNotImplementedError

Thrown when calling methods not implemented by the HTTP provider (event handling, connection management).

try {
  provider.getStatus();
} catch (error) {
  // error is MethodNotImplementedError
  console.error("Method not implemented for HTTP provider");
}

ResponseError

Thrown when HTTP requests return non-ok status codes.

try {
  const response = await provider.request(payload);
} catch (error) {
  // error is ResponseError containing the error response
  console.error("HTTP request failed:", error.message);
}

URL Validation

The provider validates client URLs using the following rules:

  • Must be a string
  • Must start with http:// or https:// (case-insensitive)
  • Invalid URLs will throw InvalidClientError during construction

Valid URL examples:

  • https://mainnet.infura.io/v3/PROJECT_ID
  • http://localhost:8545
  • https://rpc.ankr.com/eth

HTTP Request Details

All JSON-RPC requests are made with:

  • Method: POST
  • Content-Type: application/json
  • Body: JSON-stringified RPC payload
  • Custom Options: Merged from constructor options and per-request options
  • Response Parsing: Automatic JSON parsing with error checking

Usage Examples

Basic Ethereum Balance Query

Using Web3.js (recommended):

import { Web3 } from "web3";

const web3 = new Web3("https://mainnet.infura.io/v3/YOUR_PROJECT_ID");
const balance = await web3.eth.getBalance("0x742d35cc6634c0532925a3b8d404dff86c521890");
console.log("Balance:", balance);

Direct HttpProvider usage:

import HttpProvider from "web3-providers-http";

const provider = new HttpProvider("https://mainnet.infura.io/v3/YOUR_PROJECT_ID");

const balance = await provider.request({
  jsonrpc: "2.0",
  id: 1,
  method: "eth_getBalance",
  params: ["0x742d35cc6634c0532925a3b8d404dff86c521890", "latest"]
});

console.log("Balance:", balance.result);

Custom Headers and Timeout

import HttpProvider, { HttpProviderOptions } from "web3-providers-http";

const options: HttpProviderOptions = {
  providerOptions: {
    headers: {
      "Authorization": "Bearer your-api-token",
      "User-Agent": "MyApp/1.0"
    },
    // Note: timeout handling varies by environment
  }
};

const provider = new HttpProvider("https://api.example.com/rpc", options);

Type-Safe Method Calls with Custom API

import HttpProvider from "web3-providers-http";
import { Web3APISpec } from "web3-types";

// Define custom API specification
interface CustomAPI extends Web3APISpec {
  custom_method: {
    Parameters: [string, number];
    ReturnType: { result: string; status: boolean };
  };
}

const provider = new HttpProvider<CustomAPI>("https://custom-node.example.com");

// Type-safe request with custom API
const response = await provider.request({
  jsonrpc: "2.0",
  id: 1,
  method: "custom_method",
  params: ["parameter1", 42]
});

// response.result is typed as { result: string; status: boolean }
console.log(response.result.status);

Request Cancellation

import HttpProvider from "web3-providers-http";

const provider = new HttpProvider("https://mainnet.infura.io/v3/YOUR_PROJECT_ID");
const controller = new AbortController();

// Cancel request after 5 seconds
setTimeout(() => controller.abort(), 5000);

try {
  const response = await provider.request(
    {
      jsonrpc: "2.0",
      id: 1,
      method: "eth_getBalance",
      params: ["0x742d35cc6634c0532925a3b8d404dff86c521890", "latest"]
    },
    { signal: controller.signal }
  );
} catch (error) {
  if (error.name === 'AbortError') {
    console.log("Request was cancelled");
  }
}