or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

batch-processing.mdconfiguration-management.mdcontext-management.mdevent-system.mdindex.mdprovider-integration.mdrequest-management.mdsubscription-management.md

request-management.mddocs/

0

# Request Management

1

2

The Web3 request management system handles JSON-RPC communication with blockchain providers, offering comprehensive provider abstraction, middleware support, and batch processing capabilities. It provides the core networking layer for all blockchain interactions.

3

4

## Capabilities

5

6

### Web3RequestManager Class

7

8

The main request manager class that handles JSON-RPC requests to blockchain providers with full middleware and event support.

9

10

```typescript { .api }

11

/**

12

* Manages JSON-RPC requests to blockchain providers with middleware support

13

* @template API - JSON-RPC API specification type

14

*/

15

class Web3RequestManager<API extends Web3APISpec = Web3APISpec> extends Web3EventEmitter<{

16

PROVIDER_CHANGED: SupportedProviders<API>;

17

BEFORE_PROVIDER_CHANGE: SupportedProviders<API>;

18

}> {

19

constructor(

20

provider?: SupportedProviders<API> | string,

21

useRpcCallSpecification?: boolean,

22

requestManagerMiddleware?: RequestManagerMiddleware<API>

23

);

24

25

// Request handling

26

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

27

request: Web3APIRequest<API, Method>

28

): Promise<ResponseType>;

29

30

sendBatch(request: JsonRpcBatchRequest): Promise<JsonRpcBatchResponse<unknown, unknown>>;

31

32

// Provider management

33

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

34

readonly provider: SupportedProviders<API> | undefined;

35

36

// Middleware

37

setMiddleware(requestManagerMiddleware: RequestManagerMiddleware<API>): void;

38

readonly middleware?: RequestManagerMiddleware<API>;

39

40

// Static provider constructors

41

static readonly providers: {

42

HttpProvider: typeof HttpProvider;

43

WebsocketProvider: typeof WebsocketProvider;

44

};

45

46

// Provider access

47

readonly providers: typeof Web3RequestManager.providers;

48

}

49

```

50

51

**Usage Examples:**

52

53

```typescript

54

import { Web3RequestManager } from "web3-core";

55

import { EthExecutionAPI } from "web3-types";

56

57

// Create with HTTP provider URL

58

const requestManager = new Web3RequestManager<EthExecutionAPI>(

59

"https://eth-mainnet.g.alchemy.com/v2/your-api-key"

60

);

61

62

// Create with WebSocket provider

63

const wsRequestManager = new Web3RequestManager(

64

"wss://eth-mainnet.ws.alchemyapi.io/v2/your-api-key"

65

);

66

67

// Send single request

68

const blockNumber = await requestManager.send({

69

method: "eth_blockNumber",

70

params: []

71

});

72

73

// Send request with parameters

74

const balance = await requestManager.send({

75

method: "eth_getBalance",

76

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

77

});

78

79

// Listen to provider changes

80

requestManager.on("PROVIDER_CHANGED", (newProvider) => {

81

console.log("Provider changed:", newProvider);

82

});

83

84

// Change provider

85

requestManager.setProvider("https://polygon-rpc.com/");

86

```

87

88

### Provider Management

89

90

Static and instance methods for managing blockchain providers with automatic detection and validation.

91

92

```typescript { .api }

93

/**

94

* Set or change the blockchain provider

95

* @param provider - Provider instance, URL string, or undefined to clear

96

* @returns Boolean indicating if provider was successfully set

97

*/

98

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

99

100

/**

101

* Access to provider constructor classes

102

*/

103

static readonly providers: {

104

HttpProvider: typeof HttpProvider;

105

WebsocketProvider: typeof WebsocketProvider;

106

};

107

```

108

109

**Usage Examples:**

110

111

```typescript

112

// Change provider to different network

113

const success = requestManager.setProvider("https://bsc-dataseed.binance.org/");

114

console.log("Provider changed:", success);

115

116

// Use provider constructors

117

const httpProvider = new Web3RequestManager.providers.HttpProvider(

118

"https://eth-mainnet.g.alchemy.com/v2/your-api-key",

119

{

120

timeout: 30000,

121

headers: { "User-Agent": "MyApp/1.0" }

122

}

123

);

124

125

const wsProvider = new Web3RequestManager.providers.WebsocketProvider(

126

"wss://eth-mainnet.ws.alchemyapi.io/v2/your-api-key",

127

{

128

timeout: 30000,

129

reconnect: { auto: true, delay: 5000, maxAttempts: 5 }

130

}

131

);

132

133

// Create request manager with configured provider

134

const customRequestManager = new Web3RequestManager(httpProvider);

135

```

136

137

### Batch Request Processing

138

139

Efficient batch processing capabilities for sending multiple JSON-RPC requests in a single network call.

140

141

```typescript { .api }

142

/**

143

* Send multiple JSON-RPC requests in a single batch call

144

* @param request - Array of JSON-RPC request objects

145

* @returns Promise resolving to batch response with all results

146

*/

147

sendBatch(request: JsonRpcBatchRequest): Promise<JsonRpcBatchResponse<unknown, unknown>>;

148

```

149

150

**Usage Examples:**

151

152

```typescript

153

// Create batch request array

154

const batchRequest: JsonRpcBatchRequest = [

155

{

156

id: 1,

157

jsonrpc: "2.0",

158

method: "eth_blockNumber",

159

params: []

160

},

161

{

162

id: 2,

163

jsonrpc: "2.0",

164

method: "eth_gasPrice",

165

params: []

166

},

167

{

168

id: 3,

169

jsonrpc: "2.0",

170

method: "eth_getBalance",

171

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

172

}

173

];

174

175

// Send batch request

176

const batchResponse = await requestManager.sendBatch(batchRequest);

177

178

// Process results

179

batchResponse.forEach((response, index) => {

180

if ('result' in response) {

181

console.log(`Request ${index + 1} result:`, response.result);

182

} else if ('error' in response) {

183

console.error(`Request ${index + 1} error:`, response.error);

184

}

185

});

186

```

187

188

### Middleware System

189

190

Request and response middleware for intercepting and modifying JSON-RPC communications.

191

192

```typescript { .api }

193

/**

194

* Middleware interface for processing requests and responses

195

* @template API - JSON-RPC API specification type

196

*/

197

interface RequestManagerMiddleware<API extends Web3APISpec = Web3APISpec> {

198

/**

199

* Process outgoing JSON-RPC requests before sending

200

* @param request - The JSON-RPC request payload

201

* @param options - Additional processing options

202

* @returns Promise resolving to processed request

203

*/

204

processRequest<ParamType = unknown[]>(

205

request: JsonRpcPayload<ParamType>,

206

options?: {[key: string]: unknown}

207

): Promise<JsonRpcPayload<ParamType>>;

208

209

/**

210

* Process incoming JSON-RPC responses after receiving

211

* @param response - The JSON-RPC response payload

212

* @param options - Additional processing options

213

* @returns Promise resolving to processed response

214

*/

215

processResponse<AnotherMethod extends Web3APIMethod<API> = Web3APIMethod<API>, ResponseType = Web3APIReturnType<API, AnotherMethod>>(

216

response: JsonRpcResponse<ResponseType>,

217

options?: {[key: string]: unknown}

218

): Promise<JsonRpcResponse<ResponseType>>;

219

}

220

221

/**

222

* Set middleware for request/response processing

223

* @param requestManagerMiddleware - Middleware implementation

224

*/

225

setMiddleware(requestManagerMiddleware: RequestManagerMiddleware<API>): void;

226

```

227

228

**Usage Examples:**

229

230

```typescript

231

// Create logging middleware

232

const loggingMiddleware: RequestManagerMiddleware<EthExecutionAPI> = {

233

async processRequest(request, options) {

234

console.log("Outgoing request:", request.method, request.params);

235

return request;

236

},

237

238

async processResponse(response, options) {

239

if ('result' in response) {

240

console.log("Response result:", response.result);

241

} else if ('error' in response) {

242

console.error("Response error:", response.error);

243

}

244

return response;

245

}

246

};

247

248

// Create authentication middleware

249

const authMiddleware: RequestManagerMiddleware<EthExecutionAPI> = {

250

async processRequest(request, options) {

251

// Add authentication headers or modify request

252

return {

253

...request,

254

// Add custom properties if needed

255

};

256

},

257

258

async processResponse(response, options) {

259

// Process or validate response

260

return response;

261

}

262

};

263

264

// Apply middleware

265

requestManager.setMiddleware(loggingMiddleware);

266

267

// Create request manager with middleware

268

const authenticatedManager = new Web3RequestManager(

269

"https://protected-api.example.com/",

270

false, // useRpcCallSpecification

271

authMiddleware

272

);

273

```

274

275

### Event System Integration

276

277

Event emission for provider lifecycle and request management events.

278

279

```typescript { .api }

280

/**

281

* Events emitted by Web3RequestManager

282

*/

283

enum Web3RequestManagerEvent {

284

PROVIDER_CHANGED = 'PROVIDER_CHANGED',

285

BEFORE_PROVIDER_CHANGE = 'BEFORE_PROVIDER_CHANGE'

286

}

287

```

288

289

**Usage Examples:**

290

291

```typescript

292

// Listen to provider change events

293

requestManager.on("PROVIDER_CHANGED", (newProvider) => {

294

console.log("New provider set:", newProvider);

295

296

// Reinitialize dependent components

297

if (newProvider) {

298

console.log("Provider type:", typeof newProvider);

299

}

300

});

301

302

requestManager.on("BEFORE_PROVIDER_CHANGE", (oldProvider) => {

303

console.log("About to change provider from:", oldProvider);

304

305

// Cleanup or save state before provider change

306

if (oldProvider) {

307

// Perform cleanup

308

}

309

});

310

311

// Provider change triggers events

312

requestManager.setProvider("https://polygon-rpc.com/");

313

// Logs: "About to change provider from: [previous provider]"

314

// Logs: "New provider set: [new provider]"

315

```

316

317

### Advanced Request Configuration

318

319

Configuration options for request manager behavior and RPC specification handling.

320

321

```typescript { .api }

322

/**

323

* Create request manager with advanced configuration

324

* @param provider - Blockchain provider

325

* @param useRpcCallSpecification - Use RPC call specification for validation

326

* @param requestManagerMiddleware - Middleware for request/response processing

327

*/

328

constructor(

329

provider?: SupportedProviders<API> | string,

330

useRpcCallSpecification?: boolean,

331

requestManagerMiddleware?: RequestManagerMiddleware<API>

332

);

333

```

334

335

**Usage Examples:**

336

337

```typescript

338

// Create with RPC specification validation

339

const strictRequestManager = new Web3RequestManager(

340

"https://eth-mainnet.g.alchemy.com/v2/your-api-key",

341

true, // Enable RPC call specification validation

342

loggingMiddleware

343

);

344

345

// This will validate requests against the API specification

346

try {

347

const result = await strictRequestManager.send({

348

method: "eth_getBalance",

349

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

350

});

351

} catch (error) {

352

// Handle validation or network errors

353

console.error("Request failed:", error);

354

}

355

```