CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-web3-net

Web3 module to interact with Ethereum nodes networking properties

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Web3 Net

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.

Package Information

  • Package Name: web3-net
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install web3-net

Core Imports

import Net from "web3-net";
import { FMT_NUMBER, FMT_BYTES } from "web3-types";

For CommonJS:

const Net = require("web3-net");
const { FMT_NUMBER, FMT_BYTES } = require("web3-types");

Alternative named imports:

import { Net } from "web3-net";
import { FMT_NUMBER, FMT_BYTES } from "web3-types";

Basic Usage

import Net from "web3-net";
import { FMT_NUMBER, FMT_BYTES } from "web3-types";

// Create a Net instance with provider
const net = new Net("ws://localhost:8546");

// Get network ID
const networkId = await net.getId();
console.log(networkId); // 1337n (BigInt)

// Check if node is listening for peers
const isListening = await net.isListening();
console.log(isListening); // true

// Get peer count
const peerCount = await net.getPeerCount();
console.log(peerCount); // 0n (BigInt)

Architecture

Web3 Net is built around the following key components:

  • Net Class: Main class extending Web3Context for network operations
  • RPC Method Wrappers: Low-level functions that handle RPC communication with Ethereum nodes
  • Data Formatting: Integration with web3-utils for flexible return format options
  • Type Safety: Full TypeScript support with generic return type handling

Capabilities

Network ID Retrieval

Gets the current network ID (chain ID) of the connected Ethereum node.

/**
 * Gets the current network ID
 * @param returnFormat - Return format specification (defaults to DEFAULT_RETURN_FORMAT)
 * @returns Promise of the network ID in the specified format
 */
async getId<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
  returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat
): Promise<FormatType<Numbers, ReturnFormat>>;

Usage Examples:

import Net from "web3-net";
import { FMT_NUMBER, FMT_BYTES } from "web3-types";

const net = new Net("ws://localhost:8546");

// Default format (BigInt)
const networkId = await net.getId();
console.log(networkId); // 1337n

// Hex format
const networkIdHex = await net.getId({ 
  number: FMT_NUMBER.HEX, 
  bytes: FMT_BYTES.HEX 
});
console.log(networkIdHex); // "0x539"

// String format
const networkIdStr = await net.getId({ 
  number: FMT_NUMBER.STR, 
  bytes: FMT_BYTES.UINT8ARRAY 
});
console.log(networkIdStr); // "1337"

Peer Count Retrieval

Gets the number of peers connected to the Ethereum node.

/**
 * Get the number of peers connected to the node
 * @param returnFormat - Return format specification (defaults to DEFAULT_RETURN_FORMAT)
 * @returns Promise of the peer count in the specified format
 */
async getPeerCount<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
  returnFormat: ReturnFormat = DEFAULT_RETURN_FORMAT as ReturnFormat
): Promise<FormatType<Numbers, ReturnFormat>>;

Usage Examples:

// Default format (BigInt)
const peerCount = await net.getPeerCount();
console.log(peerCount); // 3n

// Number format
const peerCountNum = await net.getPeerCount({ 
  number: FMT_NUMBER.NUMBER, 
  bytes: FMT_BYTES.UINT8ARRAY 
});
console.log(peerCountNum); // 3

Network Listening Status

Checks if the Ethereum node is actively listening for peer connections.

/**
 * Check if the node is listening for peers
 * @returns Promise of boolean indicating if the node is listening
 */
async isListening(): Promise<boolean>;

Usage Examples:

const isListening = await net.isListening();

if (isListening) {
  console.log("Node is actively listening for peer connections");
} else {
  console.log("Node is not listening for peers");
}

RPC Method Wrappers

The package also exports low-level RPC method wrappers that can be used independently:

/**
 * RPC wrapper for getting network ID
 * @param web3Context - Web3 context instance
 * @param returnFormat - Return format specification
 * @returns Formatted network ID
 */
function getId<ReturnFormat extends DataFormat>(
  web3Context: Web3Context<Web3NetAPI>,
  returnFormat: ReturnFormat
): Promise<FormatType<Numbers, ReturnFormat>>;

/**
 * RPC wrapper for getting peer count
 * @param web3Context - Web3 context instance
 * @param returnFormat - Return format specification
 * @returns Formatted peer count
 */
function getPeerCount<ReturnFormat extends DataFormat>(
  web3Context: Web3Context<Web3NetAPI>,
  returnFormat: ReturnFormat
): Promise<FormatType<Numbers, ReturnFormat>>;

/**
 * RPC wrapper for checking listening status
 * @param web3Context - Web3 context instance
 * @returns Promise of boolean listening status
 */
function isListening(web3Context: Web3Context<Web3NetAPI>): Promise<boolean>;

Types

/**
 * Main Net class extending Web3Context for network operations
 */
class Net extends Web3Context<Web3NetAPI> {
  constructor(provider?: SupportedProviders<Web3NetAPI> | Web3ContextInitOptions<Web3NetAPI>);
  
  async getId<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
    returnFormat?: ReturnFormat
  ): Promise<FormatType<Numbers, ReturnFormat>>;
  
  async getPeerCount<ReturnFormat extends DataFormat = typeof DEFAULT_RETURN_FORMAT>(
    returnFormat?: ReturnFormat
  ): Promise<FormatType<Numbers, ReturnFormat>>;
  
  async isListening(): Promise<boolean>;
}

/**
 * Data format specification for return values
 */
interface DataFormat {
  readonly number: FMT_NUMBER;
  readonly bytes: FMT_BYTES;
}

/**
 * Number formatting options
 */
enum FMT_NUMBER {
  NUMBER = "NUMBER_NUMBER",    // JavaScript number
  HEX = "NUMBER_HEX",         // Hex string
  STR = "NUMBER_STR",         // String representation
  BIGINT = "NUMBER_BIGINT",   // BigInt (default)
}

/**
 * Bytes formatting options
 */
enum FMT_BYTES {
  HEX = "BYTES_HEX",           // Hex string (default)
  UINT8ARRAY = "BYTES_UINT8ARRAY", // Uint8Array
}

/**
 * Return type for numeric values based on format
 */
type Numbers = string | number | bigint | HexString;

/**
 * Hex-encoded string type
 */
type HexString = string;

/**
 * Utility type that transforms return types based on format specification
 */
type FormatType<T, F extends DataFormat> = F extends { number: FMT_NUMBER.NUMBER } 
  ? number 
  : F extends { number: FMT_NUMBER.HEX } 
  ? HexString 
  : F extends { number: FMT_NUMBER.STR } 
  ? string 
  : F extends { number: FMT_NUMBER.BIGINT } 
  ? bigint 
  : T;

/**
 * Default return format constant
 */
const DEFAULT_RETURN_FORMAT: DataFormat;

/**
 * Web3 context for Net API operations
 */
type Web3NetAPI = {
  net_version: () => string;
  net_peerCount: () => HexString;
  net_listening: () => boolean;
};

/**
 * Supported provider types for Web3Context
 */
type SupportedProviders<T> = string | Web3Provider<T>;

/**
 * Web3Context initialization options
 */
interface Web3ContextInitOptions<T> {
  provider?: SupportedProviders<T>;
  config?: Partial<Web3ConfigOptions>;
}

/**
 * Base Web3 provider interface
 */
interface Web3Provider<T> {
  request(payload: JsonRpcPayload): Promise<JsonRpcResponse>;
}

/**
 * Web3 configuration options
 */
interface Web3ConfigOptions {
  handleRevert: boolean;
  defaultAccount?: string;
  defaultBlock: BlockNumberOrTag;
  transactionSendTimeout: number;
  transactionBlockTimeout: number;
  transactionConfirmationBlocks: number;
  transactionPollingInterval: number;
  transactionPollingTimeout: number;
  transactionReceiptPollingInterval: number;
  transactionConfirmationPollingInterval: number;
  blockHeaderTimeout: number;
  maxListenersWarningThreshold: number;
  contractDataInputFill: "data" | "input" | "both";
  defaultReturnFormat: DataFormat;
}

/**
 * JSON-RPC payload structure
 */
interface JsonRpcPayload {
  jsonrpc: "2.0";
  id: string | number;
  method: string;
  params?: unknown[];
}

/**
 * JSON-RPC response structure
 */
interface JsonRpcResponse {
  jsonrpc: "2.0";
  id: string | number;
  result?: unknown;
  error?: JsonRpcError;
}

/**
 * JSON-RPC error structure
 */
interface JsonRpcError {
  code: number;
  message: string;
  data?: unknown;
}

/**
 * Block number or tag type
 */
type BlockNumberOrTag = number | bigint | HexString | "latest" | "earliest" | "pending";

Integration with Web3.js

When using the full web3.js library, web3-net is available through the web3.eth.net property:

import Web3 from "web3";

const web3 = new Web3("ws://localhost:8546");

// Access Net functionality through web3.eth.net
const networkId = await web3.eth.net.getId();
const peerCount = await web3.eth.net.getPeerCount();
const isListening = await web3.eth.net.isListening();
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/web3-net@4.0.x
Publish Source
CLI
Badge
tessl/npm-web3-net badge