0
# Context Management
1
2
The Web3 context system provides unified state management and component coordination for Web3 applications. It serves as the central orchestrator that manages configuration, providers, request managers, subscription managers, and plugins in a cohesive, type-safe environment.
3
4
## Capabilities
5
6
### Web3Context Class
7
8
The main context class that extends configuration management with provider handling and component orchestration.
9
10
```typescript { .api }
11
/**
12
* Main context class providing unified Web3 functionality management
13
* @template API - JSON-RPC API specification type
14
* @template RegisteredSubs - Registered subscription types
15
*/
16
class Web3Context<API extends Web3APISpec = Web3APISpec, RegisteredSubs extends Web3SubscriptionConstructor = Record<string, unknown>> extends Web3Config {
17
constructor(providerOrContext?: string | SupportedProviders<API> | Web3ContextInitOptions<API, RegisteredSubs>);
18
19
// Component access
20
readonly requestManager: Web3RequestManager<API>;
21
readonly subscriptionManager?: Web3SubscriptionManager<API, RegisteredSubs>;
22
readonly wallet?: Web3BaseWallet<Web3BaseWalletAccount>;
23
readonly accountProvider?: Web3AccountProvider<Web3BaseWalletAccount>;
24
readonly provider: Web3BaseProvider<API> | undefined;
25
readonly currentProvider: Web3BaseProvider<API> | undefined;
26
readonly BatchRequest: new () => Web3BatchRequest;
27
28
// Static properties
29
static providers: {
30
HttpProvider: typeof HttpProvider;
31
WebsocketProvider: typeof WebsocketProvider;
32
};
33
static givenProvider?: SupportedProviders<never>;
34
35
// Context management
36
use<T, T2 extends unknown[]>(ContextRef: Web3ContextConstructor<T, T2>, ...args: [...T2]): T;
37
link<T>(parentContext: T): void;
38
39
// Provider management
40
setProvider(provider?: SupportedProviders<API> | string): boolean;
41
setRequestManagerMiddleware(requestManagerMiddleware: RequestManagerMiddleware<API>): void;
42
43
// Plugin system
44
registerPlugin(plugin: Web3PluginBase): void;
45
46
// Extensibility
47
extend(extendObj: ExtensionObject): this;
48
49
// Context utilities
50
getContextObject(): Web3ContextObject<API, RegisteredSubs>;
51
static fromContextObject<T, T3 extends unknown[]>(
52
this: Web3ContextConstructor<T, T3>,
53
contextObject: Web3ContextObject,
54
...args: [...T3]
55
): T;
56
}
57
```
58
59
**Usage Examples:**
60
61
```typescript
62
import { Web3Context } from "web3-core";
63
import { EthExecutionAPI } from "web3-types";
64
65
// Create context with provider string
66
const web3 = new Web3Context<EthExecutionAPI>("https://eth-mainnet.g.alchemy.com/v2/your-api-key");
67
68
// Create context with configuration
69
const web3WithConfig = new Web3Context({
70
provider: "wss://eth-mainnet.ws.alchemyapi.io/v2/your-api-key",
71
config: {
72
defaultBlock: "latest",
73
transactionSendTimeout: 60000,
74
transactionConfirmationBlocks: 24,
75
handleRevert: true
76
}
77
});
78
79
// Create linked context (shares provider and config)
80
const linkedContext = web3.use(Web3Context);
81
82
// Access components
83
const requestManager = web3.requestManager;
84
const subscriptionManager = web3.subscriptionManager;
85
const batchRequest = new web3.BatchRequest();
86
```
87
88
### Plugin System
89
90
Abstract base classes for creating Web3 plugins that extend functionality.
91
92
```typescript { .api }
93
/**
94
* Base class for Web3 plugins providing extensibility framework
95
* @template API - JSON-RPC API specification type
96
*/
97
abstract class Web3PluginBase<API extends Web3APISpec = Web3APISpec> extends Web3Context<API> {
98
abstract pluginNamespace: string;
99
100
protected registerNewTransactionType<NewTxTypeClass extends new (...args: any[]) => any>(
101
type: Numbers,
102
txClass: NewTxTypeClass
103
): void;
104
}
105
106
/**
107
* Base class for Ethereum-specific plugins
108
* @template API - JSON-RPC API specification type
109
*/
110
abstract class Web3EthPluginBase<API extends Web3APISpec = Web3APISpec> extends Web3PluginBase<API & EthExecutionAPI> {
111
// Inherits all Web3PluginBase functionality with Ethereum API types
112
}
113
```
114
115
**Usage Examples:**
116
117
```typescript
118
import { Web3PluginBase } from "web3-core";
119
120
// Create a custom plugin
121
class MyCustomPlugin extends Web3PluginBase {
122
pluginNamespace = "myPlugin";
123
124
async getCustomData(address: string) {
125
return this.requestManager.send({
126
method: "eth_getBalance",
127
params: [address, "latest"]
128
});
129
}
130
131
customBatchOperation() {
132
const batch = new this.BatchRequest();
133
batch.add({ method: "eth_blockNumber", params: [] });
134
batch.add({ method: "eth_gasPrice", params: [] });
135
return batch.execute();
136
}
137
}
138
139
// Register and use plugin
140
const web3 = new Web3Context("https://eth-mainnet.g.alchemy.com/v2/your-api-key");
141
const plugin = new MyCustomPlugin();
142
web3.registerPlugin(plugin);
143
144
// Access plugin functionality
145
const balance = await (web3 as any).myPlugin.getCustomData("0x742d35Cc6634C0532925a3b8D0d3");
146
```
147
148
### Context Initialization Types
149
150
Type definitions for configuring Web3 context initialization.
151
152
```typescript { .api }
153
/**
154
* Complete context object containing all Web3 components
155
* @template API - JSON-RPC API specification type
156
* @template RegisteredSubs - Registered subscription types
157
*/
158
type Web3ContextObject<API extends Web3APISpec = Web3APISpec, RegisteredSubs extends Web3SubscriptionConstructor = Record<string, unknown>> = {
159
config: Web3ConfigOptions;
160
provider?: SupportedProviders<API> | string;
161
requestManager: Web3RequestManager<API>;
162
subscriptionManager?: Web3SubscriptionManager<API, RegisteredSubs>;
163
registeredSubscriptions?: RegisteredSubs;
164
providers: typeof Web3RequestManager.providers;
165
accountProvider?: Web3AccountProvider<Web3BaseWalletAccount>;
166
wallet?: Web3BaseWallet<Web3BaseWalletAccount>;
167
};
168
169
/**
170
* Options for initializing Web3 context
171
* @template API - JSON-RPC API specification type
172
* @template RegisteredSubs - Registered subscription types
173
*/
174
type Web3ContextInitOptions<API extends Web3APISpec = Web3APISpec, RegisteredSubs extends Web3SubscriptionConstructor = Record<string, unknown>> = {
175
provider?: SupportedProviders<API> | string;
176
config?: Partial<Web3ConfigOptions>;
177
registeredSubscriptions?: RegisteredSubs;
178
accountProvider?: Web3AccountProvider<Web3BaseWalletAccount>;
179
wallet?: Web3BaseWallet<Web3BaseWalletAccount>;
180
};
181
182
/**
183
* Constructor type for Web3 context classes
184
* @template T - Context class type
185
* @template T2 - Constructor argument types
186
*/
187
type Web3ContextConstructor<T = Web3Context, T2 extends unknown[] = any[]> = {
188
new (...args: T2): T;
189
} & typeof Web3Context;
190
```
191
192
### Extension System
193
194
Dynamic extension capabilities for adding custom methods and properties.
195
196
```typescript { .api }
197
/**
198
* Method definition for context extensions
199
*/
200
interface Method {
201
name: string;
202
call: string;
203
}
204
205
/**
206
* Extension object for adding custom functionality
207
*/
208
interface ExtensionObject {
209
property?: string;
210
methods: Method[];
211
}
212
```
213
214
**Usage Examples:**
215
216
```typescript
217
// Extend context with custom methods
218
const web3 = new Web3Context("https://eth-mainnet.g.alchemy.com/v2/your-api-key");
219
220
web3.extend({
221
property: "customMethods",
222
methods: [
223
{
224
name: "getBlockByHash",
225
call: "eth_getBlockByHash"
226
},
227
{
228
name: "getTransactionByHash",
229
call: "eth_getTransactionByHash"
230
}
231
]
232
});
233
234
// Access extended methods
235
const block = await (web3 as any).customMethods.getBlockByHash("0x1234...", true);
236
const tx = await (web3 as any).customMethods.getTransactionByHash("0x5678...");
237
```
238
239
### Context Sharing and Linking
240
241
Mechanisms for sharing context state between multiple Web3 instances.
242
243
```typescript { .api }
244
/**
245
* Link context to parent for sharing configuration and providers
246
* @template T - Parent context type
247
*/
248
link<T>(parentContext: T): void;
249
250
/**
251
* Create new context instance that shares state with this context
252
* @template T - New context type
253
* @template T2 - Constructor argument types
254
*/
255
use<T, T2 extends unknown[]>(ContextRef: Web3ContextConstructor<T, T2>, ...args: [...T2]): T;
256
257
/**
258
* Create context from existing context object
259
* @template T - Context type
260
* @template T3 - Constructor argument types
261
*/
262
static fromContextObject<T, T3 extends unknown[]>(
263
this: Web3ContextConstructor<T, T3>,
264
contextObject: Web3ContextObject,
265
...args: [...T3]
266
): T;
267
```
268
269
**Usage Examples:**
270
271
```typescript
272
// Create parent context
273
const parentWeb3 = new Web3Context({
274
provider: "https://eth-mainnet.g.alchemy.com/v2/your-api-key",
275
config: { defaultBlock: "latest" }
276
});
277
278
// Create child context that shares parent's state
279
const childWeb3 = parentWeb3.use(Web3Context);
280
281
// Child inherits parent's provider and config
282
console.log(childWeb3.provider === parentWeb3.provider); // true
283
console.log(childWeb3.defaultBlock); // "latest"
284
285
// Create context from context object
286
const contextObj = parentWeb3.getContextObject();
287
const newWeb3 = Web3Context.fromContextObject(contextObj);
288
```