CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-web3-eth

Web3 module to interact with the Ethereum blockchain and smart contracts.

67

0.98x
Overview
Eval results
Files

network-information.mddocs/

Network Information

The network information functionality provides access to Ethereum network and node details including protocol version, chain identification, synchronization status, and mining information.

Protocol and Version Information

getProtocolVersion

Returns the Ethereum protocol version supported by the connected node.

getProtocolVersion(): Promise<string>;

Usage Example:

const protocolVersion = await eth.getProtocolVersion();
console.log(`Node protocol version: ${protocolVersion}`);
// Example output: "63" or "64"

getChainId

Returns the chain ID of the current Ethereum network.

getChainId(): Promise<Numbers>;

Usage Example:

const chainId = await eth.getChainId();
console.log(`Chain ID: ${chainId}`);

// Common chain IDs:
// 1 = Ethereum Mainnet
// 5 = Goerli Testnet  
// 11155111 = Sepolia Testnet
// 137 = Polygon Mainnet
// 42161 = Arbitrum One

const networkNames = {
  1: "Ethereum Mainnet",
  5: "Goerli Testnet", 
  11155111: "Sepolia Testnet",
  137: "Polygon Mainnet",
  42161: "Arbitrum One"
};

const networkName = networkNames[Number(chainId)] || "Unknown Network";
console.log(`Connected to: ${networkName}`);

getNodeInfo

Returns detailed information about the connected Ethereum node.

getNodeInfo(): Promise<string>;

Usage Example:

const nodeInfo = await eth.getNodeInfo();
console.log(`Node information: ${nodeInfo}`);
// Example: "Geth/v1.10.26-stable-e5eb32ac/linux-amd64/go1.18.5"

Synchronization Status

isSyncing

Checks if the connected node is currently synchronizing with the network.

isSyncing(): Promise<SyncingStatusAPI | boolean>;

Returns:

  • false if the node is fully synchronized
  • SyncingStatusAPI object with sync progress if currently syncing

Usage Example:

const syncStatus = await eth.isSyncing();

if (syncStatus === false) {
  console.log("Node is fully synchronized");
} else {
  console.log("Node is synchronizing:", {
    startingBlock: syncStatus.startingBlock,
    currentBlock: syncStatus.currentBlock, 
    highestBlock: syncStatus.highestBlock,
    progress: ((Number(syncStatus.currentBlock) / Number(syncStatus.highestBlock)) * 100).toFixed(2) + '%'
  });
  
  // Optional additional sync info (if available)
  if (syncStatus.knownStates && syncStatus.pulledStates) {
    console.log("State sync progress:", {
      knownStates: syncStatus.knownStates,
      pulledStates: syncStatus.pulledStates,
      stateProgress: ((Number(syncStatus.pulledStates) / Number(syncStatus.knownStates)) * 100).toFixed(2) + '%'
    });
  }
}

Monitor Sync Progress

// Monitor synchronization progress in real-time
async function monitorSyncProgress() {
  console.log("Monitoring node synchronization...");
  
  const checkSync = async () => {
    const syncStatus = await eth.isSyncing();
    
    if (syncStatus === false) {
      console.log("✅ Node is fully synchronized");
      return true; // Fully synced
    } else {
      const progress = ((Number(syncStatus.currentBlock) / Number(syncStatus.highestBlock)) * 100).toFixed(2);
      console.log(`🔄 Syncing: Block ${syncStatus.currentBlock}/${syncStatus.highestBlock} (${progress}%)`);
      return false; // Still syncing
    }
  };
  
  // Check every 10 seconds until fully synced
  const syncInterval = setInterval(async () => {
    const isFullySynced = await checkSync();
    if (isFullySynced) {
      clearInterval(syncInterval);
    }
  }, 10000);
  
  // Initial check
  await checkSync();
}

Mining Information

getCoinbase

Returns the coinbase address where mining rewards are sent.

getCoinbase(): Promise<Address>;

Usage Example:

try {
  const coinbase = await eth.getCoinbase();
  console.log(`Coinbase address: ${coinbase}`);
} catch (error) {
  console.log("Node is not configured for mining or doesn't support mining");
}

isMining

Checks if the connected node is currently mining blocks.

isMining(): Promise<boolean>;

Usage Example:

const isMining = await eth.isMining();
console.log(`Node is mining: ${isMining}`);

if (isMining) {
  const coinbase = await eth.getCoinbase();
  console.log(`Mining rewards going to: ${coinbase}`);
}

getHashRate

Returns the current network hash rate (mining power).

getHashRate(): Promise<Numbers>;

Usage Example:

try {
  const hashRate = await eth.getHashRate();
  console.log(`Network hash rate: ${hashRate} hashes/second`);
  
  // Convert to more readable format
  const hashRateNum = Number(hashRate);
  if (hashRateNum > 1e18) {
    console.log(`Hash rate: ${(hashRateNum / 1e18).toFixed(2)} EH/s`);
  } else if (hashRateNum > 1e15) {
    console.log(`Hash rate: ${(hashRateNum / 1e15).toFixed(2)} PH/s`);
  } else if (hashRateNum > 1e12) {
    console.log(`Hash rate: ${(hashRateNum / 1e12).toFixed(2)} TH/s`);
  }
} catch (error) {
  console.log("Hash rate not available (non-PoW network or unsupported)");
}

Network Health Checks

Comprehensive Network Status

// Get comprehensive network and node status
async function getNetworkStatus() {
  try {
    const [
      chainId,
      blockNumber,
      syncStatus,
      protocolVersion,
      nodeInfo,
      isMining
    ] = await Promise.all([
      eth.getChainId(),
      eth.getBlockNumber(),
      eth.isSyncing(),
      eth.getProtocolVersion(),
      eth.getNodeInfo(),
      eth.isMining().catch(() => false)
    ]);
    
    const networkNames = {
      1: "Ethereum Mainnet",
      5: "Goerli Testnet",
      11155111: "Sepolia Testnet",
      137: "Polygon Mainnet",
      42161: "Arbitrum One"
    };
    
    const status = {
      network: {
        chainId: Number(chainId),
        name: networkNames[Number(chainId)] || "Unknown Network",
        currentBlock: Number(blockNumber),
        protocolVersion
      },
      node: {
        info: nodeInfo,
        isMining,
        isFullySynced: syncStatus === false
      },
      sync: syncStatus === false ? null : {
        startingBlock: Number(syncStatus.startingBlock),
        currentBlock: Number(syncStatus.currentBlock),
        highestBlock: Number(syncStatus.highestBlock),
        progress: ((Number(syncStatus.currentBlock) / Number(syncStatus.highestBlock)) * 100).toFixed(2) + '%'
      }
    };
    
    return status;
  } catch (error) {
    console.error("Error getting network status:", error);
    throw error;
  }
}

// Usage
const networkStatus = await getNetworkStatus();
console.log("Network Status:", JSON.stringify(networkStatus, null, 2));

Connection Health Check

// Check if connection to node is healthy
async function checkConnectionHealth(): Promise<boolean> {
  try {
    // Try multiple quick operations
    const startTime = Date.now();
    
    await Promise.all([
      eth.getBlockNumber(),
      eth.getChainId(),
      eth.getProtocolVersion()
    ]);
    
    const responseTime = Date.now() - startTime;
    
    console.log(`Connection healthy - Response time: ${responseTime}ms`);
    return responseTime < 5000; // Consider healthy if under 5 seconds
    
  } catch (error) {
    console.error("Connection health check failed:", error);
    return false;
  }
}

Network Performance Monitoring

// Monitor network performance metrics
async function monitorNetworkPerformance(intervalMs: number = 30000) {
  console.log("Starting network performance monitoring...");
  
  let lastBlockNumber = 0;
  let lastCheckTime = Date.now();
  
  const checkPerformance = async () => {
    try {
      const startTime = Date.now();
      const [blockNumber, syncStatus] = await Promise.all([
        eth.getBlockNumber(),
        eth.isSyncing()
      ]);
      const responseTime = Date.now() - startTime;
      
      const currentTime = Date.now();
      const timeDiff = (currentTime - lastCheckTime) / 1000; // seconds
      const blockDiff = Number(blockNumber) - lastBlockNumber;
      const blockRate = lastBlockNumber > 0 ? (blockDiff / timeDiff).toFixed(2) : "N/A";
      
      console.log(`Performance Check:`, {
        currentBlock: Number(blockNumber),
        responseTime: `${responseTime}ms`,
        blockRate: `${blockRate} blocks/sec`,
        isFullySynced: syncStatus === false,
        timestamp: new Date().toISOString()
      });
      
      lastBlockNumber = Number(blockNumber);
      lastCheckTime = currentTime;
      
    } catch (error) {
      console.error("Performance check failed:", error);
    }
  };
  
  // Initial check
  await checkPerformance();
  
  // Periodic checks
  const interval = setInterval(checkPerformance, intervalMs);
  
  // Return cleanup function
  return () => clearInterval(interval);
}

Core Types

interface SyncingStatusAPI {
  startingBlock: Numbers;
  currentBlock: Numbers;
  highestBlock: Numbers;
  knownStates?: Numbers;
  pulledStates?: Numbers;
}

type Numbers = HexString | number | bigint;
type Address = HexString20Bytes;
type HexString = string;
type HexString20Bytes = string;
type HexString32Bytes = string;

Install with Tessl CLI

npx tessl i tessl/npm-web3-eth

docs

account-operations.md

blockchain-state.md

cryptographic-operations.md

event-monitoring.md

gas-fee-management.md

index.md

network-information.md

smart-contract-interaction.md

transaction-management.md

transaction-utilities.md

tile.json