How do smart contract ABIs work?

GoldRush TeamUpdated 13 min read

An ABI is the contract's interface: the JSON that turns calls into bytes and logs back into values. Selectors, event topics, where to get one, and code.

What a smart contract ABI is

A smart contract ABI (application binary interface) is the list of a contract's functions and events, with the name and type of every input and output, written as JSON. On Ethereum and other EVM chains a deployed contract is only bytecode: it receives a string of bytes and returns a string of bytes. The ABI is what tells your code which bytes to send to call transfer(to, amount), and how to read the bytes that come back, or the bytes in an event log, as named, typed values.

Three things use it:

  • Calls and transactions. Your library encodes a function name and arguments into calldata with the ABI.
  • Return values. It decodes the bytes a function returns.
  • Event logs. It decodes the topics and data of the logs a contract emits, which is how apps and indexers see transfers, swaps and mints.

The ABI isn't stored on the chain. The compiler produces it next to the bytecode, and you get it from the contract's source, from its build artifacts, or from a block explorer that has verified the source.

What an ABI looks like

An ABI is a JSON array with one object per function, event, error and constructor. Here are two entries every ERC-20 token has, the transfer function and the Transfer event, as the Solidity compiler emits them:

[  {    "type": "function",    "name": "transfer",    "stateMutability": "nonpayable",    "inputs": [      { "name": "to", "type": "address" },      { "name": "amount", "type": "uint256" }    ],    "outputs": [{ "name": "", "type": "bool" }]  },  {    "type": "event",    "name": "Transfer",    "anonymous": false,    "inputs": [      { "name": "from", "type": "address", "indexed": true },      { "name": "to", "type": "address", "indexed": true },      { "name": "value", "type": "uint256", "indexed": false }    ]  }]

The fields that matter:

Field What it says
type function, event, error, constructor, receive or fallback
name The function or event name
inputs Parameters, in order, each with a name and a Solidity type
outputs What a function returns
stateMutability view or pure (reads only, callable for free), nonpayable or payable (needs a transaction)
indexed For event inputs: whether the value goes in a log topic (searchable) or in the log data
anonymous For events: true means the log has no signature topic

Compilers also add an internalType field (such as contract IERC20) that encoding ignores. Libraries such as viem and ethers accept a shorter, human-readable form of the same thing: "function transfer(address to, uint256 amount) returns (bool)".

Function selectors: how a call is encoded

When you call a function, the first 4 bytes of the calldata say which function. That is the function selector: the first 4 bytes of the keccak-256 hash of the function's canonical signature, its name and parameter types with no spaces and no parameter names.

Prerequisites for the code on this page: Node.js 18 or later, and viem@2.52.2 (plus ethers@6.16.0 for the ethers example; the install line is in "Call a contract with its ABI"). Save each JavaScript example as a .mjs file, because several use top-level await. Each example is a separate file; none reuses another's variables.

import { keccak256, toBytes, toFunctionSelector } from "viem"; console.log(toFunctionSelector("transfer(address,uint256)")); // 0xa9059cbb // The same thing by hand: hash the signature, keep the first 4 bytes.console.log(keccak256(toBytes("transfer(address,uint256)")).slice(0, 10)); // 0xa9059cbb

After the selector come the arguments, each padded to 32 bytes. Encoding a transfer of 1 USDC (6 decimals, so 1000000) to vitalik.eth's address with the ABI, and decoding it back:

import { decodeFunctionData, encodeFunctionData, parseAbi } from "viem"; const abi = parseAbi(["function transfer(address to, uint256 amount) returns (bool)"]); const data = encodeFunctionData({  abi,  functionName: "transfer",  args: ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", 1_000_000n],});console.log(data);// 0xa9059cbb//   000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa96045  <- to//   00000000000000000000000000000000000000000000000000000000000f4240  <- amount (1,000,000) console.log(decodeFunctionData({ abi, data }));// { functionName: 'transfer', args: [ '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', 1000000n ] }

(The output is one hex string; it is split here to show the parts.) This is the input field you see on any transaction in a block explorer. Every ERC-20 contract uses the same selectors because they share the same signatures: balanceOf(address) is 0x70a08231, approve(address,uint256) is 0x095ea7b3 and transferFrom(address,address,uint256) is 0x23b872dd.

A selector is only 4 bytes, so different signatures can share one, and the selector alone doesn't tell you the parameter names. Public databases such as the Ethereum Signature Database map known selectors back to signatures, which is how explorers guess the function name of an unverified contract. The full rules for every type, including dynamic ones such as string and arrays, are in the Solidity ABI specification.

Event topics: how logs are encoded

When a contract emits an event, the chain stores a log with up to four topics (32 bytes each) and a data field:

  • topic0 is the event signature hash: the full keccak-256 hash of Transfer(address,address,uint256), not cut to 4 bytes. It identifies which event this is.
  • topic1 to topic3 hold the indexed parameters, at most three. Nodes can filter logs by them, which is why from and to are indexed in Transfer.
  • data holds the parameters that aren't indexed, ABI-encoded.
import { toEventSelector } from "viem"; console.log(toEventSelector("Transfer(address,address,uint256)"));// 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef

That hash is the same for every contract with that event, so one topic0 filter finds every ERC-20 transfer on a chain. ERC-721 NFTs emit an event with the same signature too, but index the third parameter (tokenId), so their Transfer logs have four topics and empty data, while ERC-20 logs have three topics and the amount in data. The ABI's indexed flags are what tell a decoder which layout to expect.

Two details that trip people up: an indexed parameter of a dynamic type (string, bytes, an array) is stored as the keccak-256 hash of its value, so you can filter by it but not read it back; and an anonymous event has no topic0, so you can only decode it if you already know which event it is.

Where to get a contract's ABI

  • Etherscan (or another explorer) for verified contracts. If the source is verified, the contract page's Contract tab shows the ABI under "Contract ABI". The Etherscan API returns it too, with module=contract&action=getabi (the result is the ABI as a JSON string, so parse it). Unverified contracts have no published ABI.
  • Your own build. Hardhat writes it to artifacts/contracts/<File>.sol/<Contract>.json after npx hardhat compile; Foundry writes it to out/<File>.sol/<Contract>.json after forge build, and forge inspect <Contract> abi prints it. Each file holds the abi array alongside the bytecode. Remix shows it under Compilation Details after you compile.
  • The standard. For ERC-20, ERC-721, ERC-1155 or ERC-4626 calls you only need the standard's functions, so you can write the few lines in human-readable form, as the examples here do, without fetching anything.

Proxies. Many contracts, USDC among them, are proxies: the address you call holds little code of its own and forwards every call to an implementation contract. The ABI you need is the implementation's. On Etherscan, use the Read as Proxy and Write as Proxy tabs, or fetch the implementation address's ABI; calls still go to the proxy address.

Call a contract with its ABI

With an ABI and an address, a library can call any function. Read-only (view and pure) functions are free and need no wallet, only an RPC endpoint. Install the two libraries at the versions the examples were run with:

npm install viem@2.52.2 ethers@6.16.0

Set RPC_URL to an Ethereum mainnet endpoint that needs no auth header (a GoldRush JSON-RPC URL needs an Authorization: Bearer header, set up as in the JSON-RPC authentication docs). This reads USDC's symbol, decimals and a balance on Ethereum mainnet with viem:

import { createPublicClient, formatUnits, http, parseAbi } from "viem";import { mainnet } from "viem/chains"; const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";const abi = parseAbi([  "function symbol() view returns (string)",  "function decimals() view returns (uint8)",  "function balanceOf(address owner) view returns (uint256)",]); // RPC_URL: any Ethereum mainnet JSON-RPC endpoint.const client = createPublicClient({ chain: mainnet, transport: http(process.env.RPC_URL) }); const [symbol, decimals, balance] = await Promise.all([  client.readContract({ address: USDC, abi, functionName: "symbol" }),  client.readContract({ address: USDC, abi, functionName: "decimals" }),  client.readContract({    address: USDC,    abi,    functionName: "balanceOf",    args: ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"],  }),]);console.log(symbol, formatUnits(balance, decimals)); // USDC 39.192124 (on 21 November 2026)

The same with ethers v6, which also gives you the selector and topic hash from its Interface:

import { Contract, Interface, JsonRpcProvider, formatUnits } from "ethers"; const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";const abi = [  "function symbol() view returns (string)",  "function decimals() view returns (uint8)",  "function balanceOf(address owner) view returns (uint256)",  "function transfer(address to, uint256 amount) returns (bool)",  "event Transfer(address indexed from, address indexed to, uint256 value)",]; const iface = new Interface(abi);console.log(iface.getFunction("transfer").selector); // 0xa9059cbbconsole.log(iface.getEvent("Transfer").topicHash); // 0xddf252ad…b3ef const provider = new JsonRpcProvider(process.env.RPC_URL);const usdc = new Contract(USDC, abi, provider);const [symbol, decimals, balance] = await Promise.all([  usdc.symbol(),  usdc.decimals(),  usdc.balanceOf("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"),]);console.log(symbol, formatUnits(balance, decimals));

Save either one as read.mjs and run node read.mjs. If an older tutorial's ethers code fails, it is usually written for ethers v5: v6 moved ethers.providers.JsonRpcProvider to ethers.JsonRpcProvider, ethers.utils.formatUnits to ethers.formatUnits, and returns bigint where v5 returned BigNumber (migration notes). Write calls work the same way, with a wallet client (viem) or a signer (ethers) to sign the transaction.

Decode event logs with an ABI

A raw log is only topics and data. This fetches the last few blocks of USDC logs from a node and decodes one Transfer with decodeEventLog:

import { createPublicClient, decodeEventLog, formatUnits, http, parseAbi } from "viem";import { mainnet } from "viem/chains"; const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";const abi = parseAbi(["event Transfer(address indexed from, address indexed to, uint256 value)"]);const client = createPublicClient({ chain: mainnet, transport: http(process.env.RPC_URL) }); const latest = await client.getBlockNumber();// The raw logs, as the node stores them.const logs = await client.getLogs({ address: USDC, fromBlock: latest - 2n, toBlock: latest });const log = logs.find((l) => l.topics.length === 3);console.log(log.topics, log.data);// [ '0xddf252ad…b3ef',              <- topic0: Transfer(address,address,uint256)//   '0x000000000000000000000000…',  <- topic1: from, padded to 32 bytes//   '0x000000000000000000000000…' ] <- topic2: to// '0x…'                             <- data: value // The ABI turns them back into named, typed values.const { eventName, args } = decodeEventLog({ abi, topics: log.topics, data: log.data });console.log(eventName, args.from, args.to, formatUnits(args.value, 6));

This works for one contract whose ABI you have. An app that reads activity across many contracts (a wallet history, a portfolio, a tax report) has to find, store and update an ABI for every contract it meets, including new ones deployed every day, and handle the proxies and unverified contracts among them.

Skip the ABI: decoded logs from GoldRush

GoldRush returns event logs already decoded: each log carries a decoded object with the event name, its signature and its params (each with name, type, indexed and value), next to the raw raw_log_topics and raw_log_data, and the emitting contract's name, ticker and decimals. You don't fetch or manage an ABI.

This gets USDC Transfer events in a block range from the Contract Event Logs API (credit cost: 0.01 per item), part of the GoldRush Foundational API. It is TypeScript: save it as transfers.mts, set GOLDRUSH_API_KEY, and run npx tsx@4.23.15 transfers.mts (Node.js 18 or later):

type DecodedParam = { name: string; type: string; indexed: boolean; decoded: boolean; value: string };type LogEvent = {  block_height: number;  tx_hash: string;  sender_address: string;  sender_contract_ticker_symbol: string | null;  sender_contract_decimals: number | null;  raw_log_topics: string[];  raw_log_data: string | null;  decoded: { name: string; signature: string; params: DecodedParam[] | null } | null;}; type Envelope = {  data: { items: LogEvent[]; pagination: { has_more: boolean } | null } | null;  error: boolean;  error_message: string | null;  error_code: number | null;};type Transfer = { tx: string; token: string | null; from: string; to: string; value: string }; const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; async function getTransfers(fromBlock: number, toBlock: number): Promise<Transfer[]> {  const transfers: Transfer[] = [];  for (let page = 0; ; page++) {    const url =      `https://api.covalenthq.com/v1/eth-mainnet/events/address/${USDC}/` +      `?starting-block=${fromBlock}&ending-block=${toBlock}&page-size=100&page-number=${page}`;    const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.GOLDRUSH_API_KEY}` } });    // Check the status before parsing: a request with no Authorization header gets an HTML 401, not JSON.    if (!res.ok) throw new Error(`GoldRush returned HTTP ${res.status}: ${await res.text()}`);    const body = (await res.json()) as Envelope;    if (body.error || !body.data) throw new Error(`GoldRush error ${body.error_code}: ${body.error_message}`);     for (const log of body.data.items) {      if (log.decoded?.name !== "Transfer") continue;      // params come back in ABI order: Transfer(from, to, value). Values are strings.      const [from, to, value] = (log.decoded.params ?? []).map((p) => p.value);      transfers.push({ tx: log.tx_hash, token: log.sender_contract_ticker_symbol, from, to, value });    }    if (!body.data.pagination?.has_more) return transfers;  }} console.log(await getTransfers(21_000_000, 21_000_010));

value is in the token's smallest unit: divide by 10 ** sender_contract_decimals to display it. Responses are paged (page-size and page-number, with pagination.has_more); the function asks for the next page until has_more is false, so a long block range takes one request per 100 logs. If a log comes back without a usable decoded object, the raw topics and data are still there to decode with your own ABI, as in the section above.

To find one event across every contract on a chain, such as every ERC-20 and ERC-721 Transfer, query by its topic0 hash with Event Logs by Topic Hash (credit cost: 0.01 per item), and narrow it by indexed values with secondary-topics. For everything that happened in one transaction, Get a transaction returns its log events, decoded the same way.

Handle errors from the GoldRush Foundational API

When a call fails, the Foundational API returns the same envelope as a successful response, with data set to null, error set to true and the reason in error_message. The docs show this body for a chain name the API doesn't recognize:

{  "data": null,  "error": true,  "error_message": "Chain nosuchchain-mainnet not supported.",  "error_code": 501}

error_code is a JSON number and always equals the HTTP status. A 501 is a stable answer (the chain or feature isn't supported), so change the request instead of retrying it. A request sent with no Authorization header at all is rejected by the edge proxy with an HTML 401 Authorization Required page, not JSON, which is why getTransfers checks res.ok before it parses the body. Failed requests cost no credits. The error handling reference lists every code and which ones to retry.

Frequently asked questions

What is an ABI in a smart contract?

An ABI (application binary interface) is a JSON description of a contract's functions, events and errors, with each parameter's name and type. Libraries use it to encode function calls into the bytes a contract expects and to decode return values and event logs back into readable values.

What is the difference between an ABI and bytecode?

Bytecode is the compiled program stored on the chain at the contract's address; it is what the EVM runs. The ABI is a description of that program's interface, produced by the compiler next to the bytecode but not stored on the chain. You need the bytecode to deploy a contract and the ABI to talk to it.

How do I get the ABI of a deployed contract?

If its source is verified, copy it from the Contract tab of the contract's page on Etherscan (or the chain's explorer), or fetch it from the Etherscan API with action=getabi. For a proxy, use the implementation contract's ABI. For your own contracts, it is in the Hardhat artifacts/ or Foundry out/ JSON files after compiling.

Can I interact with a contract without its ABI?

Yes, if you know the signatures of the functions you need: write them in human-readable form, such as "function balanceOf(address) view returns (uint256)", and the library builds the selector and encoding from that. For standard tokens, the ERC's function list is enough. For an unverified contract with unknown functions, you can only guess from selectors in its calldata.

What is a function selector?

The first 4 bytes of the keccak-256 hash of a function's signature, such as transfer(address,uint256), which gives 0xa9059cbb. It is the first 4 bytes of a transaction's calldata and tells the contract which function to run.

What is topic0 in an event log?

The keccak-256 hash of the event's signature, such as Transfer(address,address,uint256), which gives 0xddf252ad…b3ef. It identifies the event type, so filtering logs by topic0 finds that event from every contract that emits it. Anonymous events have no topic0.

Next steps

Get new guides by email

New tutorials and best practices for building with blockchain data, sent as they're published.