or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-web3-core

Core tools and utilities for the web3.js ecosystem, providing foundational layer functionality for blockchain interactions.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/web3-core@4.7.x

To install, run

npx @tessl/cli install tessl/npm-web3-core@4.7.0

0

# Web3 Core

1

2

Web3 Core provides foundational infrastructure and utilities for the web3.js ecosystem, serving as the internal backbone for blockchain interactions. It offers comprehensive request management, subscription handling, configuration management, and context coordination across all web3.js packages with full TypeScript support.

3

4

## Package Information

5

6

- **Package Name**: web3-core

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install web3-core`

10

- **Node.js**: >=14

11

- **Repository**: https://github.com/ChainSafe/web3.js

12

13

## Core Imports

14

15

```typescript

16

import {

17

Web3Context,

18

Web3RequestManager,

19

Web3Config,

20

Web3SubscriptionManager,

21

Web3BatchRequest

22

} from "web3-core";

23

```

24

25

For CommonJS:

26

27

```javascript

28

const {

29

Web3Context,

30

Web3RequestManager,

31

Web3Config,

32

Web3SubscriptionManager,

33

Web3BatchRequest

34

} = require("web3-core");

35

```

36

37

## Basic Usage

38

39

```typescript

40

import { Web3Context, Web3RequestManager } from "web3-core";

41

42

// Create request manager with HTTP provider

43

const requestManager = new Web3RequestManager("https://eth-mainnet.g.alchemy.com/v2/your-api-key");

44

45

// Create Web3 context with configuration

46

const web3Context = new Web3Context({

47

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

48

config: {

49

defaultBlock: "latest",

50

transactionSendTimeout: 60000,

51

transactionConfirmationBlocks: 24

52

}

53

});

54

55

// Send JSON-RPC request

56

const blockNumber = await requestManager.send({

57

method: "eth_blockNumber",

58

params: []

59

});

60

61

// Create batch request for efficiency

62

const batch = new web3Context.BatchRequest();

63

batch.add({ method: "eth_blockNumber", params: [] });

64

batch.add({ method: "eth_gasPrice", params: [] });

65

const results = await batch.execute();

66

```

67

68

## Architecture

69

70

Web3 Core is built around several key architectural components:

71

72

- **Context Management**: `Web3Context` provides unified state management and component coordination

73

- **Request Layer**: `Web3RequestManager` handles JSON-RPC communication with blockchain providers

74

- **Configuration System**: `Web3Config` manages global and per-instance settings with event notification

75

- **Subscription Engine**: `Web3SubscriptionManager` manages real-time WebSocket subscriptions

76

- **Batch Processing**: `Web3BatchRequest` enables efficient grouping of multiple requests

77

- **Event System**: `Web3EventEmitter` provides robust event handling across all components

78

- **Type Safety**: Comprehensive TypeScript generics preserve type information throughout the stack

79

- **Provider Abstraction**: Support for HTTP, WebSocket, IPC, and custom providers with automatic detection

80

81

## Capabilities

82

83

### Context Management

84

85

Unified context system for managing Web3 instances, configurations, and component coordination. Provides plugin support and extensibility.

86

87

```typescript { .api }

88

class Web3Context<API, RegisteredSubs> extends Web3Config {

89

constructor(providerOrContext?: string | SupportedProviders<API> | Web3ContextInitOptions<API, RegisteredSubs>);

90

use<T, T2>(ContextRef: Web3ContextConstructor<T, T2>, ...args: [...T2]): T;

91

registerPlugin(plugin: Web3PluginBase): void;

92

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

93

}

94

```

95

96

[Context Management](./context-management.md)

97

98

### Request Management

99

100

JSON-RPC request handling with provider abstraction, middleware support, and automatic provider detection.

101

102

```typescript { .api }

103

class Web3RequestManager<API> extends Web3EventEmitter {

104

constructor(provider?: SupportedProviders<API> | string, useRpcCallSpecification?: boolean, requestManagerMiddleware?: RequestManagerMiddleware<API>);

105

send<Method, ResponseType>(request: Web3APIRequest<API, Method>): Promise<ResponseType>;

106

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

107

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

108

}

109

```

110

111

[Request Management](./request-management.md)

112

113

### Configuration Management

114

115

Centralized configuration system with event-driven updates and comprehensive blockchain-specific settings.

116

117

```typescript { .api }

118

abstract class Web3Config extends Web3EventEmitter {

119

constructor(options?: Partial<Web3ConfigOptions>);

120

setConfig(options: Partial<Web3ConfigOptions>): void;

121

122

// Configuration properties

123

defaultAccount?: HexString;

124

defaultBlock: BlockNumberOrTag;

125

transactionSendTimeout: number;

126

transactionConfirmationBlocks: number;

127

handleRevert: boolean;

128

}

129

130

interface Web3ConfigOptions {

131

handleRevert: boolean;

132

defaultAccount?: HexString;

133

defaultBlock: BlockNumberOrTag;

134

transactionSendTimeout: number;

135

transactionBlockTimeout: number;

136

transactionConfirmationBlocks: number;

137

transactionPollingInterval: number;

138

transactionPollingTimeout: number;

139

blockHeaderTimeout: number;

140

maxListenersWarningThreshold: number;

141

contractDataInputFill: 'data' | 'input' | 'both';

142

defaultNetworkId?: Numbers;

143

defaultChain: string;

144

defaultHardfork: string;

145

ignoreGasPricing: boolean;

146

defaultReturnFormat: DataFormat;

147

}

148

```

149

150

[Configuration Management](./configuration-management.md)

151

152

### Subscription Management

153

154

Real-time WebSocket subscription system for blockchain events with automatic reconnection and event handling.

155

156

```typescript { .api }

157

class Web3SubscriptionManager<API, RegisteredSubs> {

158

constructor(requestManager: Web3RequestManager<API>, registeredSubscriptions: RegisteredSubs, tolerateUnlinkedSubscription?: boolean);

159

subscribe<T>(name: T, args?: ConstructorParameters<RegisteredSubs[T]>[0], returnFormat?: DataFormat): Promise<InstanceType<RegisteredSubs[T]>>;

160

unsubscribe(condition?: ShouldUnsubscribeCondition): Promise<string[]>;

161

supportsSubscriptions(): boolean;

162

}

163

164

abstract class Web3Subscription<EventMap, ArgsType, API> extends Web3EventEmitter {

165

subscribe(): Promise<string>;

166

unsubscribe(): Promise<void>;

167

resubscribe(): Promise<void>;

168

}

169

```

170

171

[Subscription Management](./subscription-management.md)

172

173

### Batch Request Processing

174

175

Efficient batching system for grouping multiple JSON-RPC requests into single network calls.

176

177

```typescript { .api }

178

class Web3BatchRequest {

179

constructor(requestManager: Web3RequestManager);

180

add<ResponseType>(request: JsonRpcOptionalRequest<unknown>): Web3DeferredPromise<ResponseType>;

181

execute(options?: {timeout?: number}): Promise<JsonRpcBatchResponse<unknown, unknown>>;

182

}

183

```

184

185

[Batch Request Processing](./batch-processing.md)

186

187

### Event System

188

189

Robust event emission and handling system with type-safe event listeners and Promise-Event hybrids.

190

191

```typescript { .api }

192

class Web3EventEmitter<T extends Web3EventMap> implements Web3Emitter<T> {

193

on<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;

194

once<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;

195

off<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;

196

emit<K extends Web3EventKey<T>>(eventName: K, params: T[K]): void;

197

}

198

199

class Web3PromiEvent<ResolveType, EventMap> extends Web3EventEmitter<EventMap> implements Promise<ResolveType> {

200

then<TResult1, TResult2>(onfulfilled?: ((value: ResolveType) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;

201

catch<TResult>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null): Promise<ResolveType | TResult>;

202

}

203

```

204

205

[Event System](./event-system.md)

206

207

### Provider Integration

208

209

Comprehensive provider support with type guards, capability detection, and seamless integration patterns.

210

211

```typescript { .api }

212

function isWeb3Provider<API>(provider: unknown): provider is Web3BaseProvider<API>;

213

function isMetaMaskProvider<API>(provider: unknown): provider is MetaMaskProvider<API>;

214

function isEIP1193Provider<API>(provider: unknown): provider is EIP1193Provider<API>;

215

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

216

function isSupportSubscriptions<API>(provider: unknown): boolean;

217

```

218

219

[Provider Integration](./provider-integration.md)

220

221

### Deprecated Data Formatters

222

223

Legacy data formatting functions for backward compatibility. These functions are deprecated and should not be used in new code.

224

225

```typescript { .api }

226

// Input formatters (deprecated - use web3-utils format functions instead)

227

function inputStorageKeysFormatter(keys: Array<string>): Array<string>;

228

function inputBlockNumberFormatter(blockNumber: Numbers | undefined): string | undefined;

229

function inputDefaultBlockNumberFormatter(blockNumber: Numbers | undefined, defaultBlock: Numbers): string | undefined;

230

function inputAddressFormatter(address: string): string;

231

function txInputOptionsFormatter(options: TransactionInput): Mutable<TransactionOutput>;

232

function inputCallFormatter(options: TransactionInput, defaultAccount?: string): TransactionOutput;

233

function inputTransactionFormatter(options: TransactionInput, defaultAccount?: string): TransactionOutput;

234

function inputSignFormatter(data: string): string;

235

function inputTopicFormatter(topic: Topic): Topic | null;

236

function inputLogFormatter(filter: Filter): Filter;

237

238

// Output formatters (deprecated - use web3-utils format functions instead)

239

function outputProofFormatter(proof: Proof): Proof;

240

function outputBigIntegerFormatter(number: Numbers): number;

241

function outputTransactionFormatter(tx: TransactionInput): TransactionOutput;

242

function outputLogFormatter(log: Partial<LogsInput>): LogsOutput;

243

function outputTransactionReceiptFormatter(receipt: ReceiptInput): ReceiptOutput;

244

function outputBlockFormatter(block: BlockInput): BlockOutput;

245

function outputSyncingFormatter(result: SyncInput): SyncOutput;

246

```

247

248

**Note**: All formatter functions are deprecated. Use format functions from the `web3-utils` package instead for new development.

249

250

## Types

251

252

### Core Context Types

253

254

```typescript { .api }

255

type Web3ContextObject<API, RegisteredSubs> = {

256

config: Web3ConfigOptions;

257

provider?: SupportedProviders<API> | string;

258

requestManager: Web3RequestManager<API>;

259

subscriptionManager?: Web3SubscriptionManager<API, RegisteredSubs>;

260

registeredSubscriptions?: RegisteredSubs;

261

providers: typeof Web3RequestManager.providers;

262

accountProvider?: Web3AccountProvider<Web3BaseWalletAccount>;

263

wallet?: Web3BaseWallet<Web3BaseWalletAccount>;

264

};

265

266

type Web3ContextInitOptions<API, RegisteredSubs> = {

267

provider?: SupportedProviders<API> | string;

268

config?: Partial<Web3ConfigOptions>;

269

registeredSubscriptions?: RegisteredSubs;

270

accountProvider?: Web3AccountProvider<Web3BaseWalletAccount>;

271

wallet?: Web3BaseWallet<Web3BaseWalletAccount>;

272

};

273

```

274

275

### Event System Types

276

277

```typescript { .api }

278

type Web3EventMap = Record<string, unknown>;

279

type Web3EventKey<T extends Web3EventMap> = string & keyof T;

280

type Web3EventCallback<T> = (params: T) => void | Promise<void>;

281

282

interface Web3Emitter<T extends Web3EventMap> {

283

on<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;

284

once<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;

285

off<K extends Web3EventKey<T>>(eventName: K, fn: Web3EventCallback<T[K]>): void;

286

emit<K extends Web3EventKey<T>>(eventName: K, params: T[K]): void;

287

}

288

```

289

290

### Middleware Types

291

292

```typescript { .api }

293

interface RequestManagerMiddleware<API> {

294

processRequest<ParamType>(

295

request: JsonRpcPayload<ParamType>,

296

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

297

): Promise<JsonRpcPayload<ParamType>>;

298

processResponse<AnotherMethod, ResponseType>(

299

response: JsonRpcResponse<ResponseType>,

300

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

301

): Promise<JsonRpcResponse<ResponseType>>;

302

}

303

```

304

305

### Extension Types

306

307

```typescript { .api }

308

interface Method {

309

name: string;

310

call: string;

311

}

312

313

interface ExtensionObject {

314

property?: string;

315

methods: Method[];

316

}

317

```