Web3 module to interact with Ethereum nodes networking properties
npx @tessl/cli install tessl/npm-web3-net@4.0.00
# Web3 Net
1
2
Web3 Net is a TypeScript module that provides functionality to interact with Ethereum nodes' networking properties. It enables developers to query network information, peer connections, and node synchronization status through a clean API as part of the broader web3.js ecosystem.
3
4
## Package Information
5
6
- **Package Name**: web3-net
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install web3-net`
10
11
## Core Imports
12
13
```typescript
14
import Net from "web3-net";
15
import { FMT_NUMBER, FMT_BYTES } from "web3-types";
16
```
17
18
For CommonJS:
19
20
```javascript
21
const Net = require("web3-net");
22
const { FMT_NUMBER, FMT_BYTES } = require("web3-types");
23
```
24
25
Alternative named imports:
26
27
```typescript
28
import { Net } from "web3-net";
29
import { FMT_NUMBER, FMT_BYTES } from "web3-types";
30
```
31
32
## Basic Usage
33
34
```typescript
35
import Net from "web3-net";
36
import { FMT_NUMBER, FMT_BYTES } from "web3-types";
37
38
// Create a Net instance with provider
39
const net = new Net("ws://localhost:8546");
40
41
// Get network ID
42
const networkId = await net.getId();
43
console.log(networkId); // 1337n (BigInt)
44
45
// Check if node is listening for peers
46
const isListening = await net.isListening();
47
console.log(isListening); // true
48
49
// Get peer count
50
const peerCount = await net.getPeerCount();
51
console.log(peerCount); // 0n (BigInt)
52
```
53
54
## Architecture
55
56
Web3 Net is built around the following key components:
57
58
- **Net Class**: Main class extending Web3Context for network operations
59
- **RPC Method Wrappers**: Low-level functions that handle RPC communication with Ethereum nodes
60
- **Data Formatting**: Integration with web3-utils for flexible return format options
61
- **Type Safety**: Full TypeScript support with generic return type handling
62
63
## Capabilities
64
65
### Network ID Retrieval
66
67
Gets the current network ID (chain ID) of the connected Ethereum node.
68
69
```typescript { .api }
70
/**
71
* Gets the current network ID
72
* @param returnFormat - Return format specification (defaults to DEFAULT_RETURN_FORMAT)
73
* @returns Promise of the network ID in the specified format
74
*/
75
async getId<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
76
returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat
77
): Promise<FormatType<Numbers, ReturnFormat>>;
78
```
79
80
**Usage Examples:**
81
82
```typescript
83
import Net from "web3-net";
84
import { FMT_NUMBER, FMT_BYTES } from "web3-types";
85
86
const net = new Net("ws://localhost:8546");
87
88
// Default format (BigInt)
89
const networkId = await net.getId();
90
console.log(networkId); // 1337n
91
92
// Hex format
93
const networkIdHex = await net.getId({
94
number: FMT_NUMBER.HEX,
95
bytes: FMT_BYTES.HEX
96
});
97
console.log(networkIdHex); // "0x539"
98
99
// String format
100
const networkIdStr = await net.getId({
101
number: FMT_NUMBER.STR,
102
bytes: FMT_BYTES.UINT8ARRAY
103
});
104
console.log(networkIdStr); // "1337"
105
```
106
107
### Peer Count Retrieval
108
109
Gets the number of peers connected to the Ethereum node.
110
111
```typescript { .api }
112
/**
113
* Get the number of peers connected to the node
114
* @param returnFormat - Return format specification (defaults to DEFAULT_RETURN_FORMAT)
115
* @returns Promise of the peer count in the specified format
116
*/
117
async getPeerCount<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
118
returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat
119
): Promise<FormatType<Numbers, ReturnFormat>>;
120
```
121
122
**Usage Examples:**
123
124
```typescript
125
// Default format (BigInt)
126
const peerCount = await net.getPeerCount();
127
console.log(peerCount); // 3n
128
129
// Number format
130
const peerCountNum = await net.getPeerCount({
131
number: FMT_NUMBER.NUMBER,
132
bytes: FMT_BYTES.UINT8ARRAY
133
});
134
console.log(peerCountNum); // 3
135
```
136
137
### Network Listening Status
138
139
Checks if the Ethereum node is actively listening for peer connections.
140
141
```typescript { .api }
142
/**
143
* Check if the node is listening for peers
144
* @returns Promise of boolean indicating if the node is listening
145
*/
146
async isListening(): Promise<boolean>;
147
```
148
149
**Usage Examples:**
150
151
```typescript
152
const isListening = await net.isListening();
153
154
if (isListening) {
155
console.log("Node is actively listening for peer connections");
156
} else {
157
console.log("Node is not listening for peers");
158
}
159
```
160
161
## RPC Method Wrappers
162
163
The package also exports low-level RPC method wrappers that can be used independently:
164
165
```typescript { .api }
166
/**
167
* RPC wrapper for getting network ID
168
* @param web3Context - Web3 context instance
169
* @param returnFormat - Return format specification
170
* @returns Formatted network ID
171
*/
172
function getId<ReturnFormat extends DataFormat>(
173
web3Context: Web3Context<Web3NetAPI>,
174
returnFormat: ReturnFormat
175
): Promise<FormatType<Numbers, ReturnFormat>>;
176
177
/**
178
* RPC wrapper for getting peer count
179
* @param web3Context - Web3 context instance
180
* @param returnFormat - Return format specification
181
* @returns Formatted peer count
182
*/
183
function getPeerCount<ReturnFormat extends DataFormat>(
184
web3Context: Web3Context<Web3NetAPI>,
185
returnFormat: ReturnFormat
186
): Promise<FormatType<Numbers, ReturnFormat>>;
187
188
/**
189
* RPC wrapper for checking listening status
190
* @param web3Context - Web3 context instance
191
* @returns Promise of boolean listening status
192
*/
193
function isListening(web3Context: Web3Context<Web3NetAPI>): Promise<boolean>;
194
```
195
196
## Types
197
198
```typescript { .api }
199
/**
200
* Main Net class extending Web3Context for network operations
201
*/
202
class Net extends Web3Context<Web3NetAPI> {
203
constructor(provider?: SupportedProviders<Web3NetAPI> | Web3ContextInitOptions<Web3NetAPI>);
204
205
async getId<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
206
returnFormat?: ReturnFormat
207
): Promise<FormatType<Numbers, ReturnFormat>>;
208
209
async getPeerCount<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
210
returnFormat?: ReturnFormat
211
): Promise<FormatType<Numbers, ReturnFormat>>;
212
213
async isListening(): Promise<boolean>;
214
}
215
216
/**
217
* Data format specification for return values
218
*/
219
interface DataFormat {
220
readonly number: FMT_NUMBER;
221
readonly bytes: FMT_BYTES;
222
}
223
224
/**
225
* Number formatting options
226
*/
227
enum FMT_NUMBER {
228
NUMBER = "NUMBER_NUMBER", // JavaScript number
229
HEX = "NUMBER_HEX", // Hex string
230
STR = "NUMBER_STR", // String representation
231
BIGINT = "NUMBER_BIGINT", // BigInt (default)
232
}
233
234
/**
235
* Bytes formatting options
236
*/
237
enum FMT_BYTES {
238
HEX = "BYTES_HEX", // Hex string (default)
239
UINT8ARRAY = "BYTES_UINT8ARRAY", // Uint8Array
240
}
241
242
/**
243
* Return type for numeric values based on format
244
*/
245
type Numbers = string | number | bigint | HexString;
246
247
/**
248
* Hex-encoded string type
249
*/
250
type HexString = string;
251
252
/**
253
* Utility type that transforms return types based on format specification
254
*/
255
type FormatType<T, F extends DataFormat> = F extends { number: FMT_NUMBER.NUMBER }
256
? number
257
: F extends { number: FMT_NUMBER.HEX }
258
? HexString
259
: F extends { number: FMT_NUMBER.STR }
260
? string
261
: F extends { number: FMT_NUMBER.BIGINT }
262
? bigint
263
: T;
264
265
/**
266
* Default return format constant
267
*/
268
const DEFAULT_RETURN_FORMAT: DataFormat;
269
270
/**
271
* Web3 context for Net API operations
272
*/
273
type Web3NetAPI = {
274
net_version: () => string;
275
net_peerCount: () => HexString;
276
net_listening: () => boolean;
277
};
278
279
/**
280
* Supported provider types for Web3Context
281
*/
282
type SupportedProviders<T> = string | Web3Provider<T>;
283
284
/**
285
* Web3Context initialization options
286
*/
287
interface Web3ContextInitOptions<T> {
288
provider?: SupportedProviders<T>;
289
config?: Partial<Web3ConfigOptions>;
290
}
291
292
/**
293
* Base Web3 provider interface
294
*/
295
interface Web3Provider<T> {
296
request(payload: JsonRpcPayload): Promise<JsonRpcResponse>;
297
}
298
299
/**
300
* Web3 configuration options
301
*/
302
interface Web3ConfigOptions {
303
handleRevert: boolean;
304
defaultAccount?: string;
305
defaultBlock: BlockNumberOrTag;
306
transactionSendTimeout: number;
307
transactionBlockTimeout: number;
308
transactionConfirmationBlocks: number;
309
transactionPollingInterval: number;
310
transactionPollingTimeout: number;
311
transactionReceiptPollingInterval: number;
312
transactionConfirmationPollingInterval: number;
313
blockHeaderTimeout: number;
314
maxListenersWarningThreshold: number;
315
contractDataInputFill: "data" | "input" | "both";
316
defaultReturnFormat: DataFormat;
317
}
318
319
/**
320
* JSON-RPC payload structure
321
*/
322
interface JsonRpcPayload {
323
jsonrpc: "2.0";
324
id: string | number;
325
method: string;
326
params?: unknown[];
327
}
328
329
/**
330
* JSON-RPC response structure
331
*/
332
interface JsonRpcResponse {
333
jsonrpc: "2.0";
334
id: string | number;
335
result?: unknown;
336
error?: JsonRpcError;
337
}
338
339
/**
340
* JSON-RPC error structure
341
*/
342
interface JsonRpcError {
343
code: number;
344
message: string;
345
data?: unknown;
346
}
347
348
/**
349
* Block number or tag type
350
*/
351
type BlockNumberOrTag = number | bigint | HexString | "latest" | "earliest" | "pending";
352
```
353
354
## Integration with Web3.js
355
356
When using the full web3.js library, web3-net is available through the `web3.eth.net` property:
357
358
```typescript
359
import Web3 from "web3";
360
361
const web3 = new Web3("ws://localhost:8546");
362
363
// Access Net functionality through web3.eth.net
364
const networkId = await web3.eth.net.getId();
365
const peerCount = await web3.eth.net.getPeerCount();
366
const isListening = await web3.eth.net.isListening();
367
```