or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

account-management.mdcore-web3.mdens.mdethereum-interaction.mdindex.mdproviders.mdsmart-contracts.mdutilities.md

providers.mddocs/

0

# Provider Management

1

2

The provider system in Web3.js offers flexible connection management for interacting with Ethereum networks. It supports multiple transport protocols (HTTP, WebSocket, IPC), automatic provider detection, and EIP-6963 browser provider discovery with robust connection handling and configuration options.

3

4

## Capabilities

5

6

### HTTP Provider

7

8

HTTP provider for standard JSON-RPC connections over HTTP/HTTPS.

9

10

```typescript { .api }

11

/**

12

* HTTP provider for Ethereum RPC connections

13

*/

14

class HttpProvider implements EthExecutionAPI {

15

/**

16

* Create HTTP provider instance

17

* @param url - RPC endpoint URL

18

* @param options - Provider configuration options

19

*/

20

constructor(url: string, options?: HttpProviderOptions);

21

22

/**

23

* Send RPC request

24

* @param request - JSON-RPC request

25

* @returns Promise with RPC response

26

*/

27

request<T>(request: JsonRpcRequest): Promise<JsonRpcResponse<T>>;

28

29

/**

30

* Get provider configuration

31

*/

32

get config(): HttpProviderOptions;

33

34

/**

35

* Get provider URL

36

*/

37

get url(): string;

38

}

39

40

interface HttpProviderOptions {

41

/** HTTP keep-alive setting */

42

keepAlive?: boolean;

43

/** Request timeout in milliseconds */

44

timeout?: number;

45

/** Custom headers */

46

headers?: Record<string, string>;

47

/** Request credentials mode */

48

credentials?: RequestCredentials;

49

/** Custom HTTP agent */

50

agent?: any;

51

/** Provider-specific configuration */

52

providerOptions?: RequestInit;

53

}

54

```

55

56

**Usage Examples:**

57

58

```typescript

59

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

60

61

// Basic HTTP provider

62

const provider = new HttpProvider('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');

63

64

// HTTP provider with options

65

const providerWithOptions = new HttpProvider('https://localhost:8545', {

66

timeout: 10000,

67

headers: {

68

'Authorization': 'Bearer token123'

69

},

70

keepAlive: true,

71

providerOptions: {

72

credentials: 'include'

73

}

74

});

75

76

// Use with Web3

77

const web3 = new Web3(provider);

78

```

79

80

### WebSocket Provider

81

82

WebSocket provider for real-time connections with subscription support.

83

84

```typescript { .api }

85

/**

86

* WebSocket provider for real-time Ethereum connections

87

*/

88

class WebSocketProvider implements EthExecutionAPI {

89

/**

90

* Create WebSocket provider instance

91

* @param url - WebSocket endpoint URL

92

* @param clientOptions - WebSocket client options

93

* @param reconnectOptions - Reconnection configuration

94

*/

95

constructor(

96

url: string,

97

clientOptions?: ClientOptions,

98

reconnectOptions?: ReconnectOptions

99

);

100

101

/**

102

* Send RPC request

103

* @param request - JSON-RPC request

104

* @returns Promise with RPC response

105

*/

106

request<T>(request: JsonRpcRequest): Promise<JsonRpcResponse<T>>;

107

108

/**

109

* Connect to WebSocket endpoint

110

*/

111

connect(): Promise<void>;

112

113

/**

114

* Disconnect from WebSocket

115

*/

116

disconnect(): Promise<void>;

117

118

/**

119

* Check connection status

120

*/

121

get connected(): boolean;

122

123

/**

124

* Subscribe to events

125

*/

126

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

127

128

/**

129

* Remove event listener

130

*/

131

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

132

}

133

134

interface ClientOptions {

135

/** Custom headers for connection */

136

headers?: Record<string, string>;

137

/** Authentication protocols */

138

protocols?: string[];

139

/** Connection timeout */

140

timeout?: number;

141

/** Maximum payload size */

142

maxPayload?: number;

143

}

144

145

interface ReconnectOptions {

146

/** Enable automatic reconnection */

147

autoReconnect?: boolean;

148

/** Delay between reconnection attempts */

149

delay?: number;

150

/** Maximum reconnection attempts */

151

maxAttempts?: number;

152

}

153

```

154

155

**Usage Examples:**

156

157

```typescript

158

import { WebSocketProvider } from 'web3-providers-ws';

159

160

// Basic WebSocket provider

161

const wsProvider = new WebSocketProvider('wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID');

162

163

// WebSocket provider with options

164

const wsProviderWithOptions = new WebSocketProvider(

165

'wss://localhost:8546',

166

{

167

headers: { 'Authorization': 'Bearer token123' },

168

timeout: 30000

169

},

170

{

171

autoReconnect: true,

172

delay: 5000,

173

maxAttempts: 5

174

}

175

);

176

177

// Connection management

178

await wsProvider.connect();

179

console.log('Connected:', wsProvider.connected);

180

181

// Event handling

182

wsProvider.on('connect', () => console.log('Connected'));

183

wsProvider.on('disconnect', () => console.log('Disconnected'));

184

wsProvider.on('error', console.error);

185

186

// Use with Web3

187

const web3 = new Web3(wsProvider);

188

```

189

190

### EIP-6963 Provider Discovery

191

192

Browser provider discovery following EIP-6963 standard for wallet integration.

193

194

```typescript { .api }

195

/**

196

* Request available EIP-6963 providers

197

* @returns Promise with discovered providers map

198

*/

199

function requestEIP6963Providers(): Promise<EIP6963ProviderResponse>;

200

201

/**

202

* Listen for new provider discoveries

203

* @param callback - Function called when new provider is discovered

204

*/

205

function onNewProviderDiscovered(

206

callback: (providerEvent: EIP6963ProvidersMapUpdateEvent) => void

207

): void;

208

209

interface EIP6963ProviderInfo {

210

/** Unique provider identifier */

211

uuid: string;

212

/** Human-readable provider name */

213

name: string;

214

/** Provider icon URL */

215

icon: string;

216

/** Reverse domain name */

217

rdns: string;

218

}

219

220

interface EIP6963ProviderDetail<API = Web3APISpec> {

221

/** Provider information */

222

info: EIP6963ProviderInfo;

223

/** EIP-1193 provider instance */

224

provider: EIP1193Provider<API>;

225

}

226

227

type EIP6963ProviderResponse = Map<string, EIP6963ProviderDetail>;

228

229

interface EIP6963ProvidersMapUpdateEvent extends CustomEvent {

230

type: string;

231

detail: EIP6963ProviderResponse;

232

}

233

234

/** Global providers map */

235

const eip6963ProvidersMap: EIP6963ProviderResponse;

236

237

enum Eip6963EventName {

238

eip6963announceProvider = 'eip6963:announceProvider',

239

eip6963requestProvider = 'eip6963:requestProvider'

240

}

241

```

242

243

**Usage Examples:**

244

245

```typescript

246

// Request available providers

247

const providers = await Web3.requestEIP6963Providers();

248

console.log('Available providers:', providers.size);

249

250

providers.forEach((providerDetail, uuid) => {

251

console.log('Provider:', providerDetail.info.name);

252

console.log('UUID:', uuid);

253

});

254

255

// Listen for new providers

256

Web3.onNewProviderDiscovered((event) => {

257

console.log('New providers available:', event.detail.size);

258

259

event.detail.forEach((providerDetail) => {

260

console.log('New provider:', providerDetail.info.name);

261

});

262

});

263

264

// Use discovered provider

265

const firstProvider = providers.values().next().value;

266

if (firstProvider) {

267

const web3 = new Web3(firstProvider.provider);

268

}

269

```

270

271

### Provider Configuration

272

273

Common provider configuration and management utilities.

274

275

```typescript { .api }

276

/**

277

* Check if value is supported provider

278

* @param provider - Provider to check

279

* @returns Boolean indicating support

280

*/

281

function isSupportedProvider<T>(provider: unknown): provider is SupportedProviders<T>;

282

283

/**

284

* Set provider for Web3 instance

285

* @param provider - New provider

286

* @returns Boolean indicating success

287

*/

288

setProvider(provider: string | SupportedProviders<EthExecutionAPI>): boolean;

289

290

/**

291

* Get current provider

292

* @returns Current provider or undefined

293

*/

294

get currentProvider(): SupportedProviders<EthExecutionAPI> | undefined;

295

296

/**

297

* Get given provider (from browser)

298

* @returns Browser-injected provider or undefined

299

*/

300

static get givenProvider(): SupportedProviders<EthExecutionAPI> | undefined;

301

302

type SupportedProviders<API = unknown> =

303

| EIP1193Provider<API>

304

| Web3BaseProvider<API>

305

| HttpProvider

306

| WebSocketProvider;

307

```

308

309

**Usage Examples:**

310

311

```typescript

312

// Check provider support

313

const provider = new HttpProvider('https://localhost:8545');

314

console.log('Supported:', isSupportedProvider(provider)); // true

315

316

// Provider switching

317

const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');

318

319

// Switch to WebSocket

320

web3.setProvider('wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID');

321

322

// Check current provider

323

console.log('Current provider:', web3.currentProvider);

324

325

// Check for browser-injected provider

326

if (Web3.givenProvider) {

327

console.log('Browser provider available');

328

web3.setProvider(Web3.givenProvider);

329

}

330

```

331

332

### Provider Events

333

334

Event handling for provider lifecycle and connection state.

335

336

```typescript { .api }

337

interface ProviderEvents {

338

/** Connection established */

339

connect: (connectInfo: { chainId: string }) => void;

340

341

/** Connection lost */

342

disconnect: (error: { code: number; message: string }) => void;

343

344

/** Chain changed */

345

chainChanged: (chainId: string) => void;

346

347

/** Accounts changed */

348

accountsChanged: (accounts: string[]) => void;

349

350

/** Error occurred */

351

error: (error: Error) => void;

352

353

/** Message received */

354

message: (message: any) => void;

355

}

356

357

/**

358

* Add event listener to provider

359

* @param event - Event name

360

* @param listener - Event handler

361

*/

362

on<K extends keyof ProviderEvents>(event: K, listener: ProviderEvents[K]): void;

363

364

/**

365

* Remove event listener from provider

366

* @param event - Event name

367

* @param listener - Event handler

368

*/

369

removeListener<K extends keyof ProviderEvents>(event: K, listener: ProviderEvents[K]): void;

370

```

371

372

**Usage Examples:**

373

374

```typescript

375

// Provider event handling

376

const provider = new WebSocketProvider('wss://localhost:8546');

377

378

provider.on('connect', (connectInfo) => {

379

console.log('Connected to chain:', connectInfo.chainId);

380

});

381

382

provider.on('disconnect', (error) => {

383

console.log('Disconnected:', error.message);

384

});

385

386

provider.on('chainChanged', (chainId) => {

387

console.log('Chain changed to:', chainId);

388

});

389

390

provider.on('accountsChanged', (accounts) => {

391

console.log('Accounts changed:', accounts);

392

});

393

394

provider.on('error', (error) => {

395

console.error('Provider error:', error);

396

});

397

```

398

399

## Types

400

401

```typescript { .api }

402

interface JsonRpcRequest {

403

jsonrpc: '2.0';

404

method: string;

405

params?: unknown[];

406

id?: string | number;

407

}

408

409

interface JsonRpcResponse<T = unknown> {

410

jsonrpc: '2.0';

411

id?: string | number;

412

result?: T;

413

error?: {

414

code: number;

415

message: string;

416

data?: unknown;

417

};

418

}

419

420

interface EIP1193Provider<API = unknown> {

421

request<T>(request: JsonRpcRequest): Promise<T>;

422

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

423

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

424

}

425

426

interface Web3BaseProvider<API = unknown> {

427

request<T>(request: JsonRpcRequest): Promise<JsonRpcResponse<T>>;

428

}

429

430

interface EIP6963ProviderInfo {

431

uuid: string;

432

name: string;

433

icon: string;

434

rdns: string;

435

}

436

437

interface EIP6963ProviderDetail {

438

info: EIP6963ProviderInfo;

439

provider: EIP1193Provider;

440

}

441

442

interface EIP6963ProviderResponse {

443

[uuid: string]: EIP6963ProviderDetail;

444

}

445

446

type EIP6963ProvidersMapUpdateEvent = CustomEvent<{

447

providersMap: Map<string, EIP6963ProviderDetail>;

448

}>;

449

```

450

451

## EIP-6963 Provider Discovery

452

453

Modern Web3 applications can automatically discover and connect to browser wallets using the EIP-6963 standard for provider discovery.

454

455

### Provider Discovery Functions

456

457

Discover available wallet providers in the browser environment.

458

459

```typescript { .api }

460

/**

461

* Request all available EIP-6963 compatible providers

462

* @returns Promise resolving to map of available providers

463

*/

464

function requestEIP6963Providers(): Promise<EIP6963ProviderResponse>;

465

466

/**

467

* Listen for new provider discoveries

468

* @param callback - Function called when new providers are discovered

469

*/

470

function onNewProviderDiscovered(

471

callback: (providerEvent: EIP6963ProvidersMapUpdateEvent) => void

472

): void;

473

```

474

475

**Usage Examples:**

476

477

```typescript

478

import { Web3, requestEIP6963Providers, onNewProviderDiscovered } from 'web3';

479

480

// Discover all available providers

481

async function connectToWallet() {

482

const providers = await requestEIP6963Providers();

483

484

// List available wallets

485

Object.values(providers).forEach((provider) => {

486

console.log(`Found wallet: ${provider.info.name}`);

487

console.log(`Icon: ${provider.info.icon}`);

488

console.log(`RDNS: ${provider.info.rdns}`);

489

});

490

491

// Connect to first available provider

492

if (Object.keys(providers).length > 0) {

493

const firstProvider = Object.values(providers)[0];

494

const web3 = new Web3(firstProvider.provider);

495

return web3;

496

}

497

}

498

499

// Listen for newly installed wallets

500

onNewProviderDiscovered((event) => {

501

const providersMap = event.detail.providersMap;

502

providersMap.forEach((providerDetail, uuid) => {

503

console.log(`New wallet discovered: ${providerDetail.info.name}`);

504

});

505

});

506

507

// Usage with provider selection

508

async function selectWalletProvider(walletName: string) {

509

const providers = await requestEIP6963Providers();

510

511

const selectedProvider = Object.values(providers).find(

512

(provider) => provider.info.name === walletName

513

);

514

515

if (selectedProvider) {

516

return new Web3(selectedProvider.provider);

517

}

518

519

throw new Error(`Wallet "${walletName}" not found`);

520

}

521

522

// Connect to MetaMask specifically

523

const web3 = await selectWalletProvider('MetaMask');

524

```

525

526

### Provider Information Structure

527

528

Each discovered provider includes detailed metadata for user interface display.

529

530

```typescript { .api }

531

interface EIP6963ProviderInfo {

532

/** Unique identifier for the provider */

533

uuid: string;

534

535

/** Human-readable name of the wallet */

536

name: string;

537

538

/** Data URL or HTTP URL of wallet icon */

539

icon: string;

540

541

/** Reverse DNS notation identifier */

542

rdns: string;

543

}

544

545

interface EIP6963ProviderDetail {

546

/** Provider metadata */

547

info: EIP6963ProviderInfo;

548

549

/** EIP-1193 compatible provider instance */

550

provider: EIP1193Provider;

551

}

552

```