Etherscan API Client

10.3.0 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This example demonstrates how to initialize the Etherscan API client using an API key and fetch the ETH balance for a specific address on the Ethereum Mainnet, handling the promise resolution and potential errors.

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);
  });

view raw JSON →