Scholarpeak

Network Methods

Switch networks and add new networks to MetaMask.

wallet_switchEthereumChain

Switch to a different Ethereum network

Prompts the user to switch to a different network. The network must already be added to MetaMask, or the user will get an error.

typescript
async function switchToSepolia() {
  try {
    await window.ethereum.request({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId: '0xaa36a7' }]  // Sepolia
    });
    console.log('Switched to Sepolia');
  } catch (error) {
    if (error.code === 4902) {
      console.error('Sepolia not added to MetaMask');
      // Optionally add the network with wallet_addEthereumChain
    } else {
      console.error('Switch failed:', error);
    }
  }
}

Predefined Networks (usually pre-added to MetaMask):

Ethereum Mainnet0x1
Sepolia Testnet0xaa36a7
Polygon0x89
Arbitrum0xa4b1
Optimism0xa

wallet_addEthereumChain

Add a new custom network to MetaMask

Adds a new blockchain network to MetaMask that the user can then connect to. Useful for L2s, private networks, or testnets not pre-configured.

typescript
async function addArbitrum() {
  try {
    await window.ethereum.request({
      method: 'wallet_addEthereumChain',
      params: [{
        chainId: '0xa4b1',
        chainName: 'Arbitrum One',
        rpcUrls: ['https://arb1.arbitrum.io/rpc'],
        blockExplorerUrls: ['https://arbiscan.io/'],
        nativeCurrency: {
          name: 'Ethereum',
          symbol: 'ETH',
          decimals: 18
        }
      }]
    });
    console.log('Arbitrum added to MetaMask');
  } catch (error) {
    console.error('Add network failed:', error);
  }
}

Required Parameters:

  • ✓ chainId: Hex format chain ID
  • ✓ chainName: Display name in MetaMask
  • ✓ rpcUrls: Array of RPC endpoint URLs
  • ✓ nativeCurrency: Info about the native token
  • ✓ blockExplorerUrls: Optional explorer URLs

Best Practice: Switch or Add Network

typescript
async function ensureNetwork(chainId, networkConfig) {
  try {
    // Try to switch first
    await window.ethereum.request({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId }]
    });
  } catch (error) {
    // If network not found, add it
    if (error.code === 4902) {
      try {
        await window.ethereum.request({
          method: 'wallet_addEthereumChain',
          params: [networkConfig]
        });
      } catch (addError) {
        console.error('Failed to add network:', addError);
      }
    } else {
      console.error('Failed to switch network:', error);
    }
  }
}

// Usage
const arbitrumConfig = {
  chainId: '0xa4b1',
  chainName: 'Arbitrum One',
  rpcUrls: ['https://arb1.arbitrum.io/rpc'],
  blockExplorerUrls: ['https://arbiscan.io/'],
  nativeCurrency: {
    name: 'Ethereum',
    symbol: 'ETH',
    decimals: 18
  }
};

await ensureNetwork('0xa4b1', arbitrumConfig);

Key Takeaways

  • ✓ wallet_switchEthereumChain switches to existing networks
  • ✓ wallet_addEthereumChain adds new networks
  • ✓ Chain ID must be in hex format (e.g., "0x1", not 1)
  • ✓ Always provide reliable RPC URLs
  • ✓ Handle the case where a network doesn't exist yet