Etherscan API Client
This library provides a promise-based client for interacting with the Etherscan.io API, as well as several other blockchain explorers like Arbiscan and Snowtrace. It simplifies fetching blockchain data such as account balances, transaction details, and contract information, abstracting away direct HTTP requests. The current stable version is 10.3.0. The project currently indicates that development has started on a "NEXTGEN" version, suggesting future significant changes or a new major release is anticipated. It offers flexibility by allowing users to provide their own Axios instance for custom request configurations, and supports various Ethereum testnets and L2 networks beyond just Etherscan's mainnet, distinguishing it by its multi-chain support and configurable HTTP client.
Common errors
-
{ status: '0', message: 'NOTOK', result: 'Invalid API Key' }cause The provided API key is either incorrect, expired, or missing in the `init` call.fixVerify your API key on Etherscan.io (or other explorer's API page), generate a new one if necessary, and ensure it's correctly passed as the first argument to `etherscanApi.init('YOUR_API_KEY')`. -
{ status: '0', message: 'NOTOK', result: 'Max rate limit reached, please use API Key for higher rate limit' }cause The client has exceeded the Etherscan API rate limits. This can happen quickly without an API key or with a free-tier key under heavy load.fixObtain a valid Etherscan API key and pass it to `init()`. For higher volume, consider Etherscan's premium plans or implement robust rate-limiting and retry logic in your application. -
UnhandledPromiseRejectionWarning: Unhandled promise rejection.
cause The promise returned by API methods (e.g., `api.account.balance()`) was not caught, meaning errors are not handled.fixAlways attach a `.catch()` block to your promise chains or use `try...catch` with `async/await` to handle potential errors from API requests: `api.account.balance(...).then(...).catch(error => console.error(error));` -
Error: Network Error / Request failed with status code 404
cause The API client failed to reach the blockchain explorer server. This could be due to an incorrect chain URL, network connectivity issues, or an unsupported network configuration.fixDouble-check the network string passed to `init()` (e.g., 'rinkeby', 'arbitrum') for typos. Verify your internet connection and that the target explorer's API is operational.
Warnings
- breaking The project README explicitly states: "Development of a NEXTGEN Version has started - please stand by". This strongly indicates that future major versions will introduce significant breaking changes to the API and internal architecture. Developers should be prepared for migrations when upgrading from v10.x to a potential v11+.
- gotcha Etherscan and other supported blockchain explorers enforce API rate limits. Exceeding these limits without proper handling will result in failed requests and HTTP 429 'Too Many Requests' errors. The default timeout might also not be sufficient for all network conditions.
- gotcha Using an invalid or missing API key will lead to API request failures, often returning a status '0' with a 'NOTOK' message from the Etherscan API. This is a common setup issue for all supported explorers.
- gotcha Incorrectly specifying the network for testnets or L2 solutions (e.g., Rinkeby, Goerli, Arbitrum) can lead to unexpected data or errors. The default network for `init` without the second argument is usually Ethereum Mainnet ('homestead').
Install
-
npm install etherscan-api -
yarn add etherscan-api -
pnpm add etherscan-api
Imports
- init
import EtherscanApi from 'etherscan-api'; // 'init' is a named export, not a default export
import { init } from 'etherscan-api'; // For CommonJS: const { init } = require('etherscan-api'); - pickChainUrl
import pickChainUrl from 'etherscan-api'; // 'pickChainUrl' is a named export
import { pickChainUrl } from 'etherscan-api'; // For CommonJS: const { pickChainUrl } = require('etherscan-api'); - EtherscanClientInstance
const api = new EtherscanAPI(); // 'etherscan-api' does not export a class constructor, 'init' returns the instance
import { init } from 'etherscan-api'; const api = init('YOUR_API_KEY', 'homestead');
Quickstart
const { init } = require('etherscan-api');
const API_KEY = process.env.ETHERSCAN_API_KEY ?? ''; // Always use environment variables for sensitive data
if (!API_KEY) {
console.error('Error: Please set the ETHERSCAN_API_KEY environment variable.');
process.exit(1);
}
// Initialize the API for Ethereum Mainnet (homestead). 'null' or 'homestead' can be used for mainnet.
const api = init(API_KEY, 'homestead');
const targetAddress = '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae'; // Example: Ethereum Foundation address
console.log(`Fetching balance for address: ${targetAddress} on Ethereum Mainnet...`);
api.account.balance(targetAddress)
.then(balanceData => {
if (balanceData && balanceData.status === '1' && balanceData.result) {
const wei = BigInt(balanceData.result);
const ether = Number(wei) / (10**18); // Convert Wei to Ether
console.log(`Balance in Wei: ${balanceData.result}`);
console.log(`Balance in Ether: ${ether.toFixed(4)}`);
} else {
console.error('Error fetching balance:', balanceData);
}
})
.catch(error => {
console.error('An unexpected error occurred:', error.message);
});