eth_chainId
Returns the chain ID of the current Berachain network.
When to Use This Method
eth_chainId
is essential for:
- Transaction Signing - Required for EIP-155 replay protection
- Network Verification - Confirm you're connected to the correct network
- Wallet Configuration - Set up wallets and dApps for the right chain
- Multi-chain Applications - Distinguish between different networks
Parameters
This method accepts no parameters.
{
"jsonrpc": "2.0",
"method": "eth_chainId",
"params": [],
"id": 1
}
Returns
QUANTITY
- Integer representing the chain ID.
- Type: Hexadecimal string
- Format:
0x
prefixed - Berachain Mainnet:
0x138de
(80094 in decimal) - Bepolia Testnet:
0x138c5
(80069 in decimal)
Implementation Examples
- cURL
- JavaScript
- Python
- Go
# Mainnet
curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_chainId",
"params": [],
"id": 1
}'
# Testnet
curl -X POST https://api-berachain-bepolia.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_chainId",
"params": [],
"id": 1
}'
// Using fetch API
const getChainId = async () => {
const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_chainId',
params: [],
id: 1
})
});
const data = await response.json();
const chainId = parseInt(data.result, 16);
console.log('Chain ID:', chainId);
return chainId;
};
// Using ethers.js
import { JsonRpcProvider } from 'ethers';
const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY');
const network = await provider.getNetwork();
console.log('Chain ID:', network.chainId);
import requests
import json
def get_chain_id():
url = 'https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'
payload = {
"jsonrpc": "2.0",
"method": "eth_chainId",
"params": [],
"id": 1
}
response = requests.post(url, json=payload)
data = response.json()
# Convert hex to decimal
chain_id = int(data['result'], 16)
print(f"Chain ID: {chain_id}")
return chain_id
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'))
chain_id = w3.eth.chain_id
print(f"Chain ID: {chain_id}")
package main
import (
"context"
"fmt"
"log"
"github.com/ethereum/go-ethereum/ethclient"
)
func main() {
client, err := ethclient.Dial("https://api-berachain-mainnet.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)
}
Response Example
Successful Response
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x138de"
}
Note: Chain ID 80094 (0x138de
in hexadecimal) identifies the Berachain mainnet.
Error Response
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32603,
"message": "Internal error"
}
}
Common Use Cases
1. Network Verification
Verify you're connected to the correct Berachain network:
async function verifyNetwork() {
const chainId = await provider.getNetwork().then(n => n.chainId);
if (chainId === 80094) {
console.log('Connected to Berachain Mainnet');
} else if (chainId === 80069) {
console.log('Connected to Bepolia Testnet');
} else {
console.warn(`Unexpected chain ID: ${chainId}`);
}
return chainId;
}
2. Transaction Signing Setup
Configure transaction signing with proper chain ID:
import { ethers } from 'ethers';
async function signTransaction(privateKey, to, value) {
const chainId = await provider.getNetwork().then(n => n.chainId);
const tx = {
to,
value: ethers.parseEther(value),
gasLimit: 21000,
chainId // Required for EIP-155 replay protection
};
const wallet = new ethers.Wallet(privateKey, provider);
return await wallet.signTransaction(tx);
}
3. Multi-chain dApp Support
Handle multiple networks in your dApp:
const SUPPORTED_CHAINS = {
80094: { name: 'Berachain Mainnet', currency: 'BERA', explorer: 'https://beratrail.io' },
80069: { name: 'Bepolia Testnet', currency: 'BERA', explorer: 'https://bepolia.beratrail.io' }
};
async function getNetworkInfo() {
const chainId = await provider.getNetwork().then(n => n.chainId);
const networkInfo = SUPPORTED_CHAINS[chainId];
if (!networkInfo) {
throw new Error(`Unsupported chain ID: ${chainId}`);
}
return networkInfo;
}
Performance Optimization
Caching Strategy
Cache chain ID since it never changes:
class ChainCache {
constructor() {
this.chainId = null;
}
async getChainId(provider) {
if (this.chainId === null) {
const network = await provider.getNetwork();
this.chainId = network.chainId;
}
return this.chainId;
}
clear() {
this.chainId = null;
}
}
const chainCache = new ChainCache();
Batch with Other Calls
Combine with other network info requests:
const batch = [
{ jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 1 },
{ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 2 },
{ jsonrpc: '2.0', method: 'net_version', params: [], id: 3 }
];
const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
});
const results = await response.json();
Error Handling
Common errors and solutions:
Error Code | Description | Solution |
---|---|---|
-32603 | Internal error | Retry with exponential backoff |
-32005 | Rate limit exceeded | Implement rate limiting client-side |
-32000 | Server error | Check network connectivity |
async function safeGetChainId(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await provider.getNetwork().then(n => n.chainId);
} catch (error) {
if (error.code === -32005) {
// Rate limited, wait exponentially
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
Need help? Contact our support team or check the Berachain documentation.