# eth_chainId - Moonriver RPC Method

Returns the chain ID used for transaction signing on Moonriver.

> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.

## When to Use This Method

`eth_chainId` is essential for dApp developers testing on Kusama, early adopters, and teams requiring production-ready experimentation:

- **EIP-155 Transaction Signing** -- Include the chain ID in transaction signatures to prevent replay attacks across different networks
- **Multi-Chain Application Routing** -- Detect which network the RPC endpoint serves and configure application logic accordingly
- **Wallet Integration** -- Verify users are connected to the expected network before prompting transaction approval
- **Cross-Chain Security** -- Validate chain identity before bridging assets or relaying messages on production-grade dApp testing, early feature deployment, and Kusama-based EVM applications

## Common Use Cases

### 1. Multi-Network Connection Guard

Reject connections to unexpected networks before any transaction is sent:

```javascript
import { JsonRpcProvider, BrowserProvider } from 'ethers';

async function guardNetwork(provider, allowedChainIds) {
  const network = await provider.getNetwork();
  const chainId = Number(network.chainId);
  
  if (!allowedChainIds.includes(chainId)) {
    throw new Error(
      `Wrong network: connected to chain ${chainId}, expected one of [${allowedChainIds}]`
    );
  }
  
  console.log(`Connected to chain ${chainId}`);
  return chainId;
}

// Example: only allow Ethereum mainnet (1) and Arbitrum (42161)
await guardNetwork(provider, [1, 42161]);
```

### 2. Wallet Network Switcher

Detect the current chain and prompt wallet to switch if needed:

```javascript
async function ensureCorrectChain(walletProvider, targetChainId, chainParams) {
  const currentChainId = await walletProvider.send('eth_chainId', []);
  const currentId = parseInt(currentChainId, 16);
  
  if (currentId !== targetChainId) {
    try {
      await walletProvider.send('wallet_switchEthereumChain', [
        { chainId: '0x' + targetChainId.toString(16) }
      ]);
    } catch (switchError) {
      // Chain not added to wallet -- add it
      if (switchError.code === 4902) {
        await walletProvider.send('wallet_addEthereumChain', [chainParams]);
      } else {
        throw switchError;
      }
    }
    
    console.log(`Switched to chain ${targetChainId}`);
  } else {
    console.log(`Already on chain ${targetChainId}`);
  }
  
  return targetChainId;
}
```

### 3. Chain-Aware Configuration Loader

Dynamically load chain-specific contract addresses and settings:

```python
from web3 import Web3

def load_chain_config(rpc_url):
    w3 = Web3(Web3.HTTPProvider(rpc_url))
    chain_id = w3.eth.chain_id
    
    configs = {
        1: {
            'name': 'Ethereum Mainnet',
            'uniswap_router': '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
            'explorer': 'https://etherscan.io',
            'native_symbol': 'ETH'
        },
        137: {
            'name': 'Polygon',
            'uniswap_router': '0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff',
            'explorer': 'https://polygonscan.com',
            'native_symbol': 'MATIC'
        },
        42161: {
            'name': 'Arbitrum One',
            'uniswap_router': '0xE592427A0AEce92De3Edee1F18E0157C05861564',
            'explorer': 'https://arbiscan.io',
            'native_symbol': 'ETH'
        }
    }
    
    if chain_id not in configs:
        raise ValueError(f'Unsupported chain ID: {chain_id}')
    
    config = configs[chain_id]
    print(f'Loaded config for {config["name"]} (chain {chain_id})')
    return {'chain_id': chain_id, **config}
```

## Best Practices

- Use `eth_chainId` (not `net_version`) for EIP-155 transaction signing -- chain ID is the canonical signing value
- Cache the chain ID at application startup -- it does not change during a session
- For browser wallet dApps, use `wallet_switchEthereumChain` and `wallet_addEthereumChain` to guide users to the correct network
- Some L2 chains share the same chain ID as their L1 -- always combine chain ID checks with additional endpoint verification
- Return value is a hex-encoded integer -- parse with `parseInt(result, 16)` before using

## Request Parameters

This method accepts no parameters.

## Request Example

```json
{
  "jsonrpc": "2.0",
  "method": "eth_chainId",
  "params": [],
  "id": 1
}
```

## Response Fields

- `result` (`QUANTITY, required`): Chain ID in hexadecimal

## Successful Response

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0x1"
}
```

## Code Examples

cURL
JavaScript
Python
Go

```bash
curl -X POST https://api-moonriver.n.dwellir.com/YOUR_API_KEY \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "eth_chainId",
    "params": [],
    "id": 1
  }'
```

```javascript
import { JsonRpcProvider } from 'ethers';

const provider = new JsonRpcProvider('https://api-moonriver.n.dwellir.com/YOUR_API_KEY');

const network = await provider.getNetwork();
console.log('Chain ID:', network.chainId);

// Verify network before transaction
async function verifyNetwork(expectedChainId) {
  const network = await provider.getNetwork();
  if (network.chainId !== BigInt(expectedChainId)) {
    throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`);
  }
  return true;
}
```

```python
from web3 import Web3

w3 = Web3(Web3.HTTPProvider('https://api-moonriver.n.dwellir.com/YOUR_API_KEY'))

chain_id = w3.eth.chain_id
print(f'Chain ID: {chain_id}')

# Verify network
def verify_network(expected_chain_id):
    chain_id = w3.eth.chain_id
    if chain_id != expected_chain_id:
        raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}')
    return True
```

```go
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.Dial("https://api-moonriver.n.dwellir.com/YOUR_API_KEY")
    if err != nil {
        log.Fatal(err)
    }

    chainID, err := client.ChainID(context.Background())
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Chain ID: %d\n", chainID)
}
```

## Related Methods

- [`net_version`](https://www.dwellir.com/docs/moonriver/net_version) - Get network version
- [`eth_syncing`](https://www.dwellir.com/docs/moonriver/eth_syncing) - Check sync status
