Scholarpeak

Chain Methods

Query which blockchain network the user is connected to.

eth_chainId

Get the current chain ID

Returns the chain ID of the network the user is currently connected to. Different networks have different IDs.

typescript
async function getCurrentChain() {
  const chainId = await window.ethereum.request({
    method: 'eth_chainId'
  });

  console.log('Chain ID:', chainId);  // e.g., '0x1' for Mainnet

  // Map to network name
  const networks = {
    '0x1': 'Ethereum Mainnet',
    '0xaa36a7': 'Sepolia Testnet',
    '0x89': 'Polygon',
    '0xa4b1': 'Arbitrum',
  };

  const networkName = networks[chainId] || 'Unknown Network';
  console.log('Network:', networkName);

  return { chainId, networkName };
}

Common Chain IDs:

Ethereum Mainnet0x1
Sepolia Testnet0xaa36a7
Polygon0x89
Arbitrum0xa4b1
Optimism0xa
Base0x2105

net_version

Get the network version (legacy method)

Similar to eth_chainId but returns a string. This is the older standard method. Prefer eth_chainId for new code.

typescript
async function getNetworkVersion() {
  const version = await window.ethereum.request({
    method: 'net_version'
  });

  console.log('Network version:', version);
  // Returns: '1' (Mainnet), '11155111' (Sepolia), etc.
}

Listening to Network Changes

Users can switch networks in MetaMask. Listen for changes to keep your app in sync:

typescript
// Listen for network changes
window.ethereum.on('chainChanged', (chainId) => {
  console.log('User switched to chain:', chainId);
  
  // Reload page or update UI
  window.location.reload();
});

Best Practices

  • ✓ Always check the chain ID before executing transactions
  • ✓ Support only the networks your app can handle
  • ✓ Listen for chainChanged events to detect network switches
  • ✓ Show a warning if user is on an unsupported network
  • ✓ Use eth_chainId instead of net_version for new applications