Skip to content

Repository files navigation

Explorers

Thirteen block explorer APIs, one shape.

Block explorers keep returning roughly the same data in completely different formats. Explorers deals with that mess and gives scripts, agents and humans one TypeScript API and one CLI for balances, transactions, token transfers, contracts, tokens, gas and blocks.

Features

  • Fourteen providers, one contract. Etherscan, Blockscout, Blockchair, Mempool, Blockstream, Solscan, Helius, TON, TRONSCAN, Aptos, Blockberry, Koios, Arweave and dcrdata.
  • 24 chains. Ethereum, Base, Arbitrum, Optimism, Polygon, BSC, Avalanche, Gnosis, Linea, Berachain, zkSync, Scroll, Bitcoin, Litecoin, Pepecoin, eCash, Solana, TON, TRON, Aptos, Sui, Cardano, Arweave and Decred.
  • Explorer data stays explorer data. A provider never quietly falls back to a fullnode RPC just to pretend an operation is supported.
  • Amounts stay exact. Native and token values use strings in the chain's smallest unit instead of lossy JavaScript numbers.
  • CLI, library and agent extensions. Use the same provider contract from a terminal, TypeScript, OMP or Pi.
  • ENS works where it should. Balance and transaction commands accept .eth names without another dependency.

Install

pnpm add @agntn/explorers

Requires Node.js 24 or newer.

Agent extensions

Explorers ships separate entrypoints for OMP and Pi. Installing the OMP extension does not replace or reuse the Pi integration.

Install the published package in OMP:

omp install @agntn/explorers

From a source checkout, link the local package instead:

omp install .

OMP loads packages/omp/extensions/explorers.ts through the package's omp.extensions manifest. It registers nine read-only tools for balances, transaction history and details, contract metadata, token holdings, token transfers, gas prices, blocks and provider discovery. The existing Pi entrypoint remains under packages/pi/extensions/ and registers the same nine.

CLI

The short path is usually enough:

npx @agntn/explorers vitalik.eth
npx @agntn/explorers tx vitalik.eth -n 5
npx @agntn/explorers providers

An address-like first argument defaults to balance. No ceremonial subcommand needed. When both provider and chain are omitted, balance reads start on Ethereum; selecting a provider explicitly keeps that provider's default chain.

Commands

Command What it does Example
balance Native token balance, including ENS explorers balance vitalik.eth
tx Transaction history or one transaction explorers tx vitalik.eth -n 5
contract ABI, source and verification status explorers contract 0x1f984...
tokens ERC-20, SPL and Cardano native holdings explorers tokens vitalik.eth
transfers ERC-20 transfer history for an address explorers transfers vitalik.eth
gas Current gas prices explorers gas -c base
block Block data by number explorers block 18000000
providers Registered providers and their capabilities explorers providers

Common options

Option Meaning
-c, --chain Chain name or alias, for example eth, mainnet, btc or arbitrum
-p, --provider Explorer backend, for example etherscan, blockscout or mempool
-n, --limit Maximum number of transactions
-m, --mode Force tx into history or detail mode when the input is ambiguous
-t, --token Limit transfers to one token contract

Without --provider, Explorers filters candidates by the requested chain and operation, then checks configured API keys before keyless providers. Blockscout remains the final backstop when no provider matches the chain.

TypeScript

import { create, resolveEns, resolveProvider } from "@agntn/explorers";

const provider = await create(resolveProvider(undefined, "ethereum"));
const address = await resolveEns("vitalik.eth");
if (!address) throw new Error("ENS name did not resolve");

const balance = await provider.getBalance(address, "ethereum");
const transactions = await provider.getTxHistory(address, "ethereum", { limit: 10 });

console.log(`${balance.balanceFormatted} ${balance.symbol}`);
console.log(transactions.map((transaction) => transaction.hash));

if (provider.capabilities.contractInfo && provider.getContractInfo) {
  const contract = await provider.getContractInfo(
    "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
    "ethereum",
  );
  console.log(contract.isVerified, contract.name);
}

UTXO providers that expose cumulative totals add funded and spent to Balance, in the chain's smallest native unit.

Mempool (Bitcoin, Litecoin and Pepecoin) and Blockstream keep balance, funded and spent confirmed. Their optional unconfirmed field is the signed mempool delta in base units: pending receipts minus pending spends. A negative value means pending activity reduces the balance. Add it to balance for a total including pending activity, not a spendability guarantee. Missing mempool statistics leave the field absent, not zero. The CLI and agent tools show the delta separately.

Required operations live on Provider. Optional operations stay absent when a backend cannot serve them, so check both capabilities and the method before calling. Unsupported operations have no stub that returns convincing nonsense. Every successful Balance includes its ISO read time plus nullable block height and hash fields, so an unavailable chain position stays explicit.

create() imports the provider it was asked for and nothing else, which is why it returns a promise. Everything the registry answers without an instance stays synchronous: providers(), has(), supportsChain(), supportsCapability(), getDefaultURL() and resolveProvider() read the metadata in builtins. Pass a capability as the third resolveProvider() argument when automatic selection must support a particular operation. A single backend can also skip the registry: import { Mempool } from "@agntn/explorers/providers/mempool" gives you the class and leaves the other providers out of your bundle.

withProvider() keeps an explicit provider strict. With neither provider nor chain, it starts on Ethereum; an explicit provider without a chain keeps that provider's default. Its optional fourth argument filters automatic selection by capability. Automatic reads get one try on the next available built-in provider after RateLimitError or PlanRestrictedError. Every other failure stays with the first provider. Its callback can run twice, so it belongs to read operations. Every CLI, MCP, Pi and OMP path that reads chain data requests its operation capability through this dispatcher.

Providers

Provider Auth Chains Capabilities
etherscan ETHERSCAN_API_KEY ethereum, base, arbitrum, optimism, polygon, bsc, avalanche, gnosis, linea, berachain balances, tx, transfers, contract, tokens, gas, block
blockscout None ethereum, base, arbitrum, optimism, polygon, gnosis, linea, scroll, zksync, avalanche balances, tx, transfers, contract, tokens, gas, block
blockchair Optional BLOCKCHAIR_API_KEY bitcoin, ethereum, ecash balances, tx, block
mempool None bitcoin, litecoin, pepecoin balances, tx; gas and block on Bitcoin and Litecoin
blockstream None bitcoin balances, tx detail/history, block
solscan SOLSCAN_API_KEY solana balances, tx detail/history, block
helius HELIUS_API_KEY solana tx detail/history, tokens
ton None ton balances, tx
tronscan TRONSCAN_API_KEY tron balances, tx detail/history, block
aptos None aptos no supported explorer operations
blockberry BLOCKBERRY_API_KEY sui balances, tx history
koios None cardano balances, tx detail/history, tokens
arweave None arweave balances, tx detail/history, block
dcrdata None decred balances, tx detail/history, block

dcrdata reads Decred balances, transactions and blocks without an API key. Balance calls use the Insight address endpoint with noTxList=1, not the full transaction list. Amounts come from integer atom fields (8 decimals), including the signed mempool balance delta. funded and spent cover confirmed activity only. Insight supplies no snapshot height or hash, so both stay null. These are indexed balances, not a guarantee that every output is mature or spendable.

baseUrl is the Insight API root, defaulting to https://explorer.dcrdata.org/insight/api. Address shape and mainnet version checks come from @agntn/chains; dcrdata checks the checksum. History, transaction details and blocks use the same Insight API root. Contracts, tokens and gas quotes stay unsupported. Insight's estimatefee endpoint returns the node relay fee regardless of the confirmation target, not a fee-market estimate.

explorers balance Dcur2mcGjmENx4DhNqDctW5wJCVyT3Qeqkx -c dcr
explorers balance Dcur2mcGjmENx4DhNqDctW5wJCVyT3Qeqkx -p dcrdata
explorers tx Dcur2mcGjmENx4DhNqDctW5wJCVyT3Qeqkx -c dcr -n 2
explorers tx 4b064b5a6255ed94bb9c4347e370c5ad034db4d0550e5bd6775cbed65015ebe3 -c dcr
explorers block 1000 -c dcr

Decred history supports limit (1 to 250, default 100), page (starting at 1) and both sort directions. Ascending pages read from the end of the index, not a reversed page of recent transactions. If the total changes during that two-request read, retry it. Insight has no block-range filter, so startBlock and endBlock are rejected rather than silently ignored.

A transaction's to and value describe one addressed output, not the total of all outputs. History prefers an external output for outgoing transactions and the queried address for incoming ones. Detail reads use the first addressed output. Data-only outputs are skipped, and all inputs, outputs and stake-specific scripts remain in raw. Decimal DCR output values and fees become integer atom strings without floating-point multiplication. success means positive confirmations, not an independent check of stake-vote approval; zero confirmations mean pending and negative confirmations mean failed. Coinbase and treasurybase fees are zero.

Insight returns blocks as a one-element array. Its transaction list includes both regular and stake trees, so txCount counts both. There is no miner address in that response: miner stays empty. Decred has no gas, so block gas fields use "0", as with the other non-EVM providers.

arweave reads balances and blocks through the gateway's wallet and block REST endpoints, and transaction history and details through its GraphQL index. No API key is needed. baseUrl is the gateway root, defaulting to https://arweave.net; every request stays on that gateway, without a fallback to another node. Balance responses have no block height or hash, so both snapshot fields remain null. Arweave has no gas: block gas fields use "0", following the existing non-EVM convention. Gas quotes, contracts and token holdings remain unsupported; /price/{bytes} quotes a storage cost, not a price per gas unit.

History includes sent and received transactions, removes self-transfer duplicates, and supports sort, inclusive startBlock/endBlock, limit (1 to 100, default 100) and page (starting at 1). Each read is limited to a window where page * limit <= 1000; use block bounds to narrow older history. Index coverage depends on the gateway, particularly for bundled data items. Quantity and top-level transaction fees use winstons (12 decimals). Bundle membership, data metadata and tags remain in raw; a data item's fee is omitted because its parent pays the network fee. An empty recipient stays "", not contract creation. A missing block means pending, with block number 0 and no timestamp. SmartWeave and AO execution status are not inferred from inclusion in an Arweave block.

Arweave addresses and transaction IDs have the same shape. Use -m detail for a transaction ID:

explorers balance FPjbN_btYKzcf8QASjs30v5C0FPv7XpwKXENBW8dqVw -c arweave
explorers block 1994692 -c arweave
explorers tx FPjbN_btYKzcf8QASjs30v5C0FPv7XpwKXENBW8dqVw -c arweave -n 3
explorers tx 2Bg8S0GcQmbC-FeT5dDKcj0WOK2YmH7Y4mlW-mO8_yE -p arweave -m detail

aptos is deliberately boring. It stays registered, advertises no capabilities and throws UnsupportedOperationError from required methods. Aptos Explorer has no documented account/history API, and hiding fullnode REST behind an explorer provider just to make the table look complete would be dishonest.

Data and errors

Wallet amounts stay as strings in the chain's smallest unit. Converting them to JavaScript numbers is an easy way to lose precision without noticing. Use formatWei(value, decimals) for display. The default is 18 decimals, so pass 8 for BTC, 9 for SOL and whatever the actual token uses.

Bitcoin, Litecoin and Pepecoin transactions from mempool expose their OP_RETURN data in opReturn. Every push arrives as raw hex, plus a text reading when the bytes are printable UTF-8. Binary carriers such as Runes or Omni keep the hex and skip the text instead of handing you mojibake.

normalizeChain() accepts practical aliases such as mainnet, btc, coinbase and apt. Unknown names fail instead of silently selecting another chain.

Explorer APIs fail in enough creative ways, so errors share one hierarchy: ExplorerError, HTTPError, AuthError, RateLimitError, PlanRestrictedError, NotFoundError, UnsupportedChainError, UnsupportedOperationError and UnknownProviderError. normalizeError() turns unknown transport failures into that shape and strips API keys from URLs before they reach logs.

Adding a provider

A new backend is five steps:

  1. Create a class extending Provider in src/providers/.
  2. Give it one unique static readonly key.
  3. Implement supported operations and advertise their capabilities. Required methods without an implementation throw UnsupportedOperationError.
  4. Export the class.
  5. Add an entry to builtins in src/providers/index.ts with its chains, its public endpoint and a load that imports the module.
  6. Add the file to build.config.ts so it ships as its own bundle.

The entry carries what the registry answers without an instance, so listing providers or matching a chain never loads explorer code. Skipping a step is not silent: test/unit/registry.test.ts compares the list against the files on disk, against the key of the class each entry loads, and against the build inputs.

Development

pnpm install
pnpm fmt
pnpm lint
pnpm typecheck
pnpm test:run
pnpm build

License

MIT

About

Unified TypeScript API and CLI for blockchain explorer providers

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages