eth_accounts
Returns a list of addresses owned by the client.
When to Use This Method
eth_accounts
is essential for:
- Wallet Integration - Retrieve available accounts from connected wallets
- Account Management - List user-controlled addresses for transaction signing
- dApp Authentication - Identify available user accounts for login flows
- Multi-Account Support - Display multiple wallet addresses in your application
note
This method only returns accounts that the client has access to. For most dApps, this will be empty unless using a local node with unlocked accounts.
Parameters
This method accepts no parameters.
{
"jsonrpc": "2.0",
"method": "eth_accounts",
"params": [],
"id": 1
}
Returns
Array
- Array of 20-byte addresses owned by the client.
- Type: Array of strings
- Format: Each address is a 20-byte hex string prefixed with
0x
- Example:
["0x407d73d8a49eeb85d32cf465507dd71d507100c1"]
Implementation Examples
- cURL
- JavaScript
- Python
- Go
curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_accounts",
"params": [],
"id": 1
}'
// Using fetch API
const getAccounts = 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_accounts',
params: [],
id: 1
})
});
const data = await response.json();
console.log('Available accounts:', data.result);
return data.result;
};
// Using ethers.js (for wallet connections)
import { JsonRpcProvider } from 'ethers';
const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY');
// Note: This will typically return empty array for public RPC endpoints
const accounts = await provider.send('eth_accounts', []);
console.log('Accounts:', accounts);
// For wallet integration, use eth_requestAccounts instead
if (window.ethereum) {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
console.log('Connected accounts:', accounts);
}
import requests
import json
def get_accounts():
url = 'https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'
payload = {
"jsonrpc": "2.0",
"method": "eth_accounts",
"params": [],
"id": 1
}
response = requests.post(url, json=payload)
data = response.json()
accounts = data.get('result', [])
print(f"Available accounts: {accounts}")
return accounts
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'))
# This will typically return empty for public endpoints
accounts = w3.eth.accounts
print(f"Accounts: {accounts}")
# For local development with unlocked accounts
# accounts = w3.geth.personal.list_accounts() # If using Geth with personal module
package main
import (
"context"
"fmt"
"log"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
)
func main() {
client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
// Using raw RPC client for eth_accounts
rpcClient, err := rpc.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
var accounts []string
err = rpcClient.CallContext(context.Background(), &accounts, "eth_accounts")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Available accounts: %v\n", accounts)
}
Response Example
Successful Response
{
"jsonrpc": "2.0",
"id": 1,
"result": [
"0x407d73d8a49eeb85d32cf465507dd71d507100c1",
"0x85f43d8a49eeb85d32cf465507dd71d507100c12"
]
}
Empty Response (Typical for Public RPC)
{
"jsonrpc": "2.0",
"id": 1,
"result": []
}
Error Response
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32601,
"message": "Method not found"
}
}
Common Use Cases
1. Wallet Connection Status
Check if wallet is connected:
async function checkWalletConnection() {
if (!window.ethereum) {
console.log('No wallet detected');
return null;
}
try {
// Request account access
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts'
});
if (accounts.length > 0) {
console.log('Connected to account:', accounts[0]);
return accounts[0];
}
} catch (error) {
console.error('User denied account access');
}
return null;
}
2. Multi-Account Management
Handle multiple accounts:
class AccountManager {
constructor(provider) {
this.provider = provider;
this.accounts = [];
}
async loadAccounts() {
try {
this.accounts = await this.provider.send('eth_accounts', []);
return this.accounts;
} catch (error) {
console.error('Failed to load accounts:', error);
return [];
}
}
getDefaultAccount() {
return this.accounts.length > 0 ? this.accounts[0] : null;
}
async switchAccount(accountIndex) {
if (accountIndex < this.accounts.length) {
// Implementation depends on wallet
return this.accounts[accountIndex];
}
throw new Error('Account index out of bounds');
}
}
3. Development Environment Setup
For local development with unlocked accounts:
// Check if running on local development node
async function setupDevelopmentAccounts() {
const accounts = await provider.send('eth_accounts', []);
if (accounts.length > 0) {
console.log('Development accounts available:', accounts);
// Use first account as default signer for transactions
const signer = await provider.getSigner(accounts[0]);
return signer;
} else {
console.log('No unlocked accounts. Using wallet connection.');
return null;
}
}
Performance Optimization
Account Caching
Cache account information to reduce API calls:
class AccountCache {
constructor(ttl = 30000) { // 30 second cache
this.cache = null;
this.timestamp = 0;
this.ttl = ttl;
}
async getAccounts(provider) {
const now = Date.now();
if (this.cache && (now - this.timestamp) < this.ttl) {
return this.cache;
}
try {
this.cache = await provider.send('eth_accounts', []);
this.timestamp = now;
return this.cache;
} catch (error) {
// Return cached data on error if available
return this.cache || [];
}
}
invalidate() {
this.cache = null;
this.timestamp = 0;
}
}
Event-Driven Updates
Listen for account changes:
if (window.ethereum) {
window.ethereum.on('accountsChanged', (accounts) => {
console.log('Accounts changed:', accounts);
// Update application state
updateUserInterface(accounts);
});
window.ethereum.on('chainChanged', (chainId) => {
// Account access might change with chain
window.location.reload();
});
}
Error Handling
Common errors and solutions:
Error Code | Description | Solution |
---|---|---|
-32601 | Method not found | Verify RPC endpoint supports this method |
-32603 | Internal error | Check node connectivity and retry |
4100 | Unauthorized | User denied account access in wallet |
4001 | User rejected | User cancelled the request |
async function safeGetAccounts(provider, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await provider.send('eth_accounts', []);
} catch (error) {
console.error(`Attempt ${i + 1} failed:`, error.message);
if (error.code === 4001) {
// User rejected - don't retry
throw new Error('User denied account access');
}
if (error.code === -32601) {
// Method not supported - don't retry
throw new Error('eth_accounts not supported by this provider');
}
if (i === maxRetries - 1) {
throw error;
}
// Wait before retry
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
}