or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# Web3 HTTP Provider

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: web3-providers-http

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install web3` (web3-providers-http is included as part of the Web3.js library)

10

11

## Core Imports

12

13

**Recommended - Use with Web3.js library:**

14

15

```typescript

16

import { Web3 } from "web3";

17

18

// HttpProvider is used automatically when you provide an HTTP URL

19

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

20

```

21

22

**Direct import (advanced usage):**

23

24

```typescript

25

import HttpProvider from "web3-providers-http";

26

```

27

28

Named import:

29

30

```typescript

31

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

32

```

33

34

With options interface:

35

36

```typescript

37

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

38

```

39

40

For CommonJS:

41

42

```javascript

43

const HttpProvider = require("web3-providers-http");

44

// or

45

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

46

```

47

48

## Basic Usage

49

50

**Recommended - Using with Web3.js:**

51

52

```typescript

53

import { Web3 } from "web3";

54

55

// HttpProvider is used automatically for HTTP URLs

56

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

57

58

// Get account balance using Web3 convenience methods

59

const balance = await web3.eth.getBalance("0x742d35cc6634c0532925a3b8d404dff86c521890");

60

console.log(balance); // Account balance

61

```

62

63

**Direct HttpProvider usage:**

64

65

```typescript

66

import HttpProvider from "web3-providers-http";

67

68

// Create provider with basic URL

69

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

70

71

// Create provider with custom options

72

const providerWithOptions = new HttpProvider(

73

"https://mainnet.infura.io/v3/YOUR_PROJECT_ID",

74

{

75

providerOptions: {

76

headers: {

77

"Authorization": "Bearer your-token"

78

},

79

timeout: 10000

80

}

81

}

82

);

83

84

// Make JSON-RPC request

85

const response = await provider.request({

86

jsonrpc: "2.0",

87

id: 1,

88

method: "eth_getBalance",

89

params: ["0x742d35cc6634c0532925a3b8d404dff86c521890", "latest"]

90

});

91

92

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

93

```

94

95

## Architecture

96

97

The Web3 HTTP Provider is built around:

98

99

- **HttpProvider Class**: Main provider implementation extending Web3BaseProvider

100

- **Generic Type System**: Full TypeScript support with Web3APISpec generics for type-safe method calls

101

- **URL Validation**: Client URL validation ensuring HTTP/HTTPS protocols only

102

- **Fetch Integration**: Uses cross-fetch for Node.js/browser compatibility

103

- **Error Handling**: Comprehensive error handling with specific Web3 error types

104

- **Request Configuration**: Supports all standard Fetch API options through HttpProviderOptions

105

106

## Capabilities

107

108

### HTTP Provider Class

109

110

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

111

112

```typescript { .api }

113

/**

114

* HTTP provider implementation for Web3.js JSON-RPC communication

115

* @template API - Web3 API specification type, defaults to EthExecutionAPI

116

*/

117

export default class HttpProvider<API extends Web3APISpec = EthExecutionAPI> extends Web3BaseProvider<API> {

118

/**

119

* Creates a new HTTP provider instance

120

* @param clientUrl - HTTP or HTTPS URL of the JSON-RPC endpoint

121

* @param httpProviderOptions - Optional configuration for HTTP requests

122

* @throws InvalidClientError when clientUrl is invalid

123

*/

124

constructor(clientUrl: string, httpProviderOptions?: HttpProviderOptions);

125

}

126

```

127

128

### JSON-RPC Request Method

129

130

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

131

132

```typescript { .api }

133

/**

134

* Makes an HTTP JSON-RPC request to the configured endpoint

135

* @template Method - The JSON-RPC method being called

136

* @template ResultType - Expected return type for the method

137

* @param payload - JSON-RPC payload containing method and parameters

138

* @param requestOptions - Optional Fetch API RequestInit options for this specific request

139

* @returns Promise resolving to JSON-RPC response with typed result

140

* @throws ResponseError when HTTP response indicates an error

141

*/

142

async request<

143

Method extends Web3APIMethod<API>,

144

ResultType = Web3APIReturnType<API, Method>

145

>(

146

payload: Web3APIPayload<API, Method>,

147

requestOptions?: RequestInit

148

): Promise<JsonRpcResponseWithResult<ResultType>>;

149

```

150

151

### Subscription Support Check

152

153

Indicates whether the provider supports real-time subscriptions.

154

155

```typescript { .api }

156

/**

157

* Indicates subscription support capability

158

* @returns false - HTTP providers do not support subscriptions

159

*/

160

supportsSubscriptions(): boolean;

161

```

162

163

### Provider Status (Not Implemented)

164

165

Provider status checking method - throws MethodNotImplementedError.

166

167

```typescript { .api }

168

/**

169

* Gets the current provider status

170

* @throws MethodNotImplementedError - Not implemented for HTTP provider

171

*/

172

getStatus(): Web3ProviderStatus;

173

```

174

175

### Event Handling Methods (Not Implemented)

176

177

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

178

179

```typescript { .api }

180

/**

181

* Registers an event listener

182

* @throws MethodNotImplementedError - Event handling not supported over HTTP

183

*/

184

on(): void;

185

186

/**

187

* Removes an event listener

188

* @throws MethodNotImplementedError - Event handling not supported over HTTP

189

*/

190

removeListener(): void;

191

192

/**

193

* Registers a one-time event listener

194

* @throws MethodNotImplementedError - Event handling not supported over HTTP

195

*/

196

once(): void;

197

198

/**

199

* Removes all event listeners

200

* @throws MethodNotImplementedError - Event handling not supported over HTTP

201

*/

202

removeAllListeners(): void;

203

```

204

205

### Connection Management Methods (Not Implemented)

206

207

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

208

209

```typescript { .api }

210

/**

211

* Establishes provider connection

212

* @throws MethodNotImplementedError - Connection management not applicable for HTTP

213

*/

214

connect(): void;

215

216

/**

217

* Closes provider connection

218

* @throws MethodNotImplementedError - Connection management not applicable for HTTP

219

*/

220

disconnect(): void;

221

222

/**

223

* Resets provider state

224

* @throws MethodNotImplementedError - State management not applicable for HTTP

225

*/

226

reset(): void;

227

228

/**

229

* Reconnects the provider (HttpProvider-specific method)

230

* @throws MethodNotImplementedError - Connection management not applicable for HTTP

231

*/

232

reconnect(): void;

233

```

234

235

### Inherited Methods from Web3BaseProvider

236

237

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

238

239

```typescript { .api }

240

/**

241

* Sends a JSON-RPC request (deprecated, use request() instead)

242

* @deprecated Use request() method instead

243

* @param payload - JSON-RPC payload

244

* @param callback - Optional callback function

245

* @returns Promise resolving to JSON-RPC response

246

*/

247

send<Method extends Web3APIMethod<API>, ResultType = Web3APIReturnType<API, Method>>(

248

payload: Web3APIPayload<API, Method>,

249

callback?: (error: Error | null, result?: JsonRpcResponseWithResult<ResultType>) => void

250

): Promise<JsonRpcResponseWithResult<ResultType>>;

251

252

/**

253

* Sends a JSON-RPC request asynchronously (deprecated, use request() instead)

254

* @deprecated Use request() method instead

255

* @param payload - JSON-RPC payload

256

* @param callback - Callback function for handling response

257

*/

258

sendAsync<Method extends Web3APIMethod<API>, ResultType = Web3APIReturnType<API, Method>>(

259

payload: Web3APIPayload<API, Method>,

260

callback: (error: Error | null, result?: JsonRpcResponseWithResult<ResultType>) => void

261

): void;

262

263

/**

264

* Returns an EIP-1193 compatible provider interface

265

* @returns EIP1193Provider instance wrapping this provider

266

*/

267

asEIP1193Provider(): EIP1193Provider<API>;

268

```

269

270

## Types

271

272

### Core Web3 Types

273

274

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

275

276

```typescript { .api }

277

/**

278

* Base Web3 API specification interface

279

*/

280

interface Web3APISpec {

281

[method: string]: {

282

Parameters: any[];

283

ReturnType: any;

284

};

285

}

286

287

/**

288

* Default Ethereum execution API specification

289

*/

290

interface EthExecutionAPI extends Web3APISpec {

291

eth_getBalance: {

292

Parameters: [string, string];

293

ReturnType: string;

294

};

295

eth_blockNumber: {

296

Parameters: [];

297

ReturnType: string;

298

};

299

// ... additional Ethereum JSON-RPC methods

300

}

301

302

/**

303

* JSON-RPC method names from API specification

304

*/

305

type Web3APIMethod<API extends Web3APISpec> = keyof API;

306

307

/**

308

* JSON-RPC payload for specific method

309

*/

310

interface Web3APIPayload<API extends Web3APISpec, Method extends Web3APIMethod<API>> {

311

jsonrpc: "2.0";

312

id: number | string;

313

method: Method;

314

params: API[Method]["Parameters"];

315

}

316

317

/**

318

* Return type for specific API method

319

*/

320

type Web3APIReturnType<API extends Web3APISpec, Method extends Web3APIMethod<API>> =

321

API[Method]["ReturnType"];

322

323

/**

324

* JSON-RPC response with typed result

325

*/

326

interface JsonRpcResponseWithResult<T> {

327

jsonrpc: "2.0";

328

id: number | string;

329

result: T;

330

}

331

332

/**

333

* Base provider class from web3-types

334

*/

335

abstract class Web3BaseProvider<API extends Web3APISpec> {

336

abstract request<Method extends Web3APIMethod<API>>(

337

payload: Web3APIPayload<API, Method>

338

): Promise<JsonRpcResponseWithResult<Web3APIReturnType<API, Method>>>;

339

abstract supportsSubscriptions(): boolean;

340

abstract getStatus(): Web3ProviderStatus;

341

// ... additional provider interface methods

342

}

343

344

/**

345

* Provider status enumeration

346

*/

347

enum Web3ProviderStatus {

348

CONNECTING = "connecting",

349

CONNECTED = "connected",

350

DISCONNECTED = "disconnected",

351

ERROR = "error"

352

}

353

354

/**

355

* EIP-1193 compatible provider interface

356

*/

357

interface EIP1193Provider<API extends Web3APISpec> {

358

request<Method extends Web3APIMethod<API>>(

359

args: { method: Method; params?: API[Method]["Parameters"] }

360

): Promise<Web3APIReturnType<API, Method>>;

361

on(event: string, listener: (...args: any[]) => void): void;

362

removeListener(event: string, listener: (...args: any[]) => void): void;

363

}

364

```

365

366

### Standard Web API Types

367

368

```typescript { .api }

369

/**

370

* Standard Fetch API RequestInit interface for HTTP configuration

371

*/

372

interface RequestInit {

373

method?: string;

374

headers?: HeadersInit;

375

body?: BodyInit | null;

376

referrer?: string;

377

referrerPolicy?: ReferrerPolicy;

378

mode?: RequestMode;

379

credentials?: RequestCredentials;

380

cache?: RequestCache;

381

redirect?: RequestRedirect;

382

integrity?: string;

383

keepalive?: boolean;

384

signal?: AbortSignal | null;

385

window?: any;

386

}

387

```

388

389

### Error Types

390

391

Error types from the web3-errors package:

392

393

```typescript { .api }

394

/**

395

* Error thrown when invalid client URL is provided

396

*/

397

class InvalidClientError extends Error {

398

constructor(clientUrl: string);

399

}

400

401

/**

402

* Error thrown when calling unimplemented provider methods

403

*/

404

class MethodNotImplementedError extends Error {

405

constructor();

406

}

407

408

/**

409

* Error thrown when HTTP response indicates failure

410

*/

411

class ResponseError extends Error {

412

constructor(response: any);

413

}

414

```

415

416

## Configuration

417

418

### HTTP Provider Options

419

420

Configuration interface for customizing HTTP requests and provider behavior.

421

422

```typescript { .api }

423

/**

424

* Configuration options for HTTP provider

425

*/

426

interface HttpProviderOptions {

427

/** Standard Fetch API RequestInit options for HTTP requests */

428

providerOptions: RequestInit;

429

}

430

```

431

432

The `providerOptions` field accepts all standard Fetch API options:

433

434

- `headers`: Custom HTTP headers

435

- `timeout`: Request timeout (browser-dependent)

436

- `credentials`: Cookie/authentication credential handling

437

- `cache`: Caching behavior

438

- `redirect`: Redirect handling

439

- `integrity`: Subresource integrity value

440

- `keepalive`: Keep connection alive

441

- `referrer`: Referrer information

442

- `referrerPolicy`: Referrer policy

443

- `signal`: AbortController signal for request cancellation

444

445

## Error Handling

446

447

The provider throws specific error types for different failure scenarios:

448

449

### InvalidClientError

450

451

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

452

453

```typescript

454

try {

455

const provider = new HttpProvider("invalid-url");

456

} catch (error) {

457

// error is InvalidClientError

458

console.error(`Invalid client URL: ${error.message}`);

459

}

460

```

461

462

### MethodNotImplementedError

463

464

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

465

466

```typescript

467

try {

468

provider.getStatus();

469

} catch (error) {

470

// error is MethodNotImplementedError

471

console.error("Method not implemented for HTTP provider");

472

}

473

```

474

475

### ResponseError

476

477

Thrown when HTTP requests return non-ok status codes.

478

479

```typescript

480

try {

481

const response = await provider.request(payload);

482

} catch (error) {

483

// error is ResponseError containing the error response

484

console.error("HTTP request failed:", error.message);

485

}

486

```

487

488

## URL Validation

489

490

The provider validates client URLs using the following rules:

491

492

- Must be a string

493

- Must start with `http://` or `https://` (case-insensitive)

494

- Invalid URLs will throw `InvalidClientError` during construction

495

496

Valid URL examples:

497

- `https://mainnet.infura.io/v3/PROJECT_ID`

498

- `http://localhost:8545`

499

- `https://rpc.ankr.com/eth`

500

501

## HTTP Request Details

502

503

All JSON-RPC requests are made with:

504

505

- **Method**: POST

506

- **Content-Type**: application/json

507

- **Body**: JSON-stringified RPC payload

508

- **Custom Options**: Merged from constructor options and per-request options

509

- **Response Parsing**: Automatic JSON parsing with error checking

510

511

## Usage Examples

512

513

### Basic Ethereum Balance Query

514

515

**Using Web3.js (recommended):**

516

517

```typescript

518

import { Web3 } from "web3";

519

520

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

521

const balance = await web3.eth.getBalance("0x742d35cc6634c0532925a3b8d404dff86c521890");

522

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

523

```

524

525

**Direct HttpProvider usage:**

526

527

```typescript

528

import HttpProvider from "web3-providers-http";

529

530

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

531

532

const balance = await provider.request({

533

jsonrpc: "2.0",

534

id: 1,

535

method: "eth_getBalance",

536

params: ["0x742d35cc6634c0532925a3b8d404dff86c521890", "latest"]

537

});

538

539

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

540

```

541

542

### Custom Headers and Timeout

543

544

```typescript

545

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

546

547

const options: HttpProviderOptions = {

548

providerOptions: {

549

headers: {

550

"Authorization": "Bearer your-api-token",

551

"User-Agent": "MyApp/1.0"

552

},

553

// Note: timeout handling varies by environment

554

}

555

};

556

557

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

558

```

559

560

### Type-Safe Method Calls with Custom API

561

562

```typescript

563

import HttpProvider from "web3-providers-http";

564

import { Web3APISpec } from "web3-types";

565

566

// Define custom API specification

567

interface CustomAPI extends Web3APISpec {

568

custom_method: {

569

Parameters: [string, number];

570

ReturnType: { result: string; status: boolean };

571

};

572

}

573

574

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

575

576

// Type-safe request with custom API

577

const response = await provider.request({

578

jsonrpc: "2.0",

579

id: 1,

580

method: "custom_method",

581

params: ["parameter1", 42]

582

});

583

584

// response.result is typed as { result: string; status: boolean }

585

console.log(response.result.status);

586

```

587

588

### Request Cancellation

589

590

```typescript

591

import HttpProvider from "web3-providers-http";

592

593

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

594

const controller = new AbortController();

595

596

// Cancel request after 5 seconds

597

setTimeout(() => controller.abort(), 5000);

598

599

try {

600

const response = await provider.request(

601

{

602

jsonrpc: "2.0",

603

id: 1,

604

method: "eth_getBalance",

605

params: ["0x742d35cc6634c0532925a3b8d404dff86c521890", "latest"]

606

},

607

{ signal: controller.signal }

608

);

609

} catch (error) {

610

if (error.name === 'AbortError') {

611

console.log("Request was cancelled");

612

}

613

}

614

```