Decoding contracts at scale: ABIs, proxies, tokens and prices
A raw log is an address, up to four 32-byte topics and a blob of data. None of it says "a swap of 1,200 USDC for 0.4 ETH". To get there, you need the right ABI for the right block, the token's decimals, and a price.
This note covers that decoding layer for EVM chains. Solana programs describe their interfaces differently and their logs have no topics, so they need a separate approach. The note assumes your raw data is already correct; see reorgs, finality and idempotency. For the full stack, see the decentralized data stack.
What a raw log is
In the Solidity ABI spec, topics[0] is the Keccak hash of the event signature, for example Transfer(address,address,uint256). "This value is only present in topics[0] if the event is not declared as anonymous" (Solidity ABI spec). Indexed parameters fill the other topics, "up to 3 (for non-anonymous events) or 4 (for anonymous ones)". Non-indexed parameters are ABI-encoded in data.
For dynamic types such as string, bytes, arrays and structs, an indexed parameter holds "the Keccak hash of a special in-place encoded value". The spec says this "leaves applications unable to decode indexed values they have not queried for." Try to recover the value from the transaction's input or from a non-indexed copy in the same log. Otherwise keep the hash.
A function selector is "the first (left, high-order in big-endian) four bytes of the Keccak-256 hash of the signature of the function". Decoding function calls, like Dune's _call_* tables, needs trace data, not logs, from a node or provider with tracing.
Where ABIs come from
Etherscan. The V2 API getabi endpoint will "Retrieve the ABI for a verified smart contract" (Etherscan API). For a proxy it returns the proxy's own ABI. The source-code endpoint's response includes Proxy and Implementation fields, which are a useful hint. Several endpoints are "throttled to 2 calls/second regardless of API Pro tier". Check the limit for your plan and cache every ABI.
Sourcify. Sourcify recompiles source and compares bytecode. An exact match means the deployed bytecode "is byte-by-byte the same (excluding libraries and immutables)" and "the fingerprints (metadata hashes for Solidity) ... are exactly matching" (Sourcify docs). A plain "match" means the same bytecode with a different metadata hash. Its ABI is still usable for decoding.
Signature databases. The 4byte directory maps selectors and event hashes back to text. It held "1,464,446 signatures" when I read it on 2026-10-30, and anyone can submit entries (4byte). A signature gives types but no parameter names. One selector can return several candidates, some of them crafted on purpose. Rank candidates by how many known ABIs use them. Do not trust a signature-only decode without a second check.
My ranking: Sourcify exact match, Etherscan verified, Sourcify match, a reviewed manual ABI, then signature-only. The order follows the strength of the link between source and deployed code. Store the source with every ABI.
Proxies: the address you see is not the code that runs
Users call a proxy. The proxy forwards the call with delegatecall to an implementation. Logs carry the proxy's address, but the events live in the implementation's ABI. Resolve proxies, or you miss every business event.
EIP-1967 fixes storage slots. The implementation sits in slot 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, "obtained as bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)" (EIP-1967). A beacon proxy stores a beacon address in slot 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50. Call implementation() on the beacon to get the target. Changes "SHOULD be notified" by Upgraded(address indexed implementation). SHOULD is not MUST.
Older patterns use other slots. EIP-1822 (UUPS, now stagnant) uses keccak256("PROXIABLE") (ERC-1822). Safe proxies keep the singleton address as the "first declared variable", which is slot 0 (Safe source). Early OpenZeppelin proxies used their own named slots.
EIP-1167 clones have fixed bytecode starting 363d3d373d3d3d363d73, with the target in bytes 10 to 29 (EIP-1167). Each factory usually points its clones to its own implementation. Variants exist, such as the PUSH0 clone in ERC-7511 starting 365f5f375f5f365f73 (ERC-7511). Where you can, record the implementation from the factory's creation event.
EIP-2535 diamonds route each selector to a facet. They implement IDiamondLoupe with facets() and facetAddress(bytes4), and changes emit DiamondCut (EIP-2535). The selector map changes per cut, so it needs per-block-range rows. Calling facets() at an old block needs archive state.
EIP-7702 accounts are EOAs that delegate to code. Their code is 0xef0100 || address (EIP-7702). Treat the designator like a proxy.
A resolver:
- Match clone bytecode patterns and extract the address.
- Read the EIP-1967 implementation slot. If empty, read the beacon slot and call
implementation(). - Check legacy slots: PROXIABLE, slot 0 for Safe-style proxies.
- For diamonds, call
facets()and indexDiamondCut. - Resolve again on the result, with a depth limit of about 5.
Events are a hint, not ground truth. Some proxies change the slot with no event. The ground truth is the slot value at a block, read with eth_getStorageAt (archive state) or taken from trace storage diffs.
The ABI registry must be reorg-safe
The output is one ABI per address per block range: (chain_id, address, valid_from_block, valid_to_block). Near the head, a block number is the wrong coordinate. An Upgraded log in a reorged block would create a registry row that survives the reorg. Build registry rows only from finalized data, or store block_hash and apply the same rollback rule as your other tables. With finalized-only rows, logs from a just-upgraded proxy cannot decode at the head. They wait in the unknown-topics backlog. When the registry row lands, replay the backlog for that address and block range.
A metamorphic contract (CREATE2 plus self-destruct) can change code at one address. Close the old range when the code hash changes.
Collisions and ambiguity
ERC-20 defines event Transfer(address indexed _from, address indexed _to, uint256 _value) (EIP-20). ERC-721 defines the same event with uint256 indexed _tokenId (EIP-721). The name and types match, so topics[0] matches too. Some early tokens index nothing. Handle three shapes:
| Topics | Data | Decode as |
|---|---|---|
| 3 | 32 bytes | ERC-20 |
| 4 | empty | ERC-721 |
| 1 | 96 bytes | legacy, no indexed args |
Send anything else to the unknown backlog. A token-type flag helps, but ERC-165 detection is optional, so it is a hint too. Event topics use the full 32-byte hash, so accidental event collisions are not a practical concern. The problem is identical signatures with different semantics.
Token metadata
ERC-20 makes name, symbol and decimals optional: "interfaces and other contracts MUST NOT expect these values to be present." Decimals of "8, means to divide the token amount by 100000000" (EIP-20).
Build a token dimension with provenance: chain_id, token_address, decimals, symbol, name, read_at_block, source (contract call or manual override), standard, and flags such as is_rebasing and is_fee_on_transfer. Common failure modes:
- Some tokens return
nameandsymbolasbytes32. Decode both forms. - Calls revert. Store null and queue for review.
- Never default missing decimals to 18. A wrong default causes no error.
- Rebasing and share-based tokens (stETH-style) emit Transfer amounts that do not equal balance changes. Fee-on-transfer tokens deliver less than the amount sent.
- Spam tokens copy symbols. Never join or deduplicate on
symbol.
ERC-1155 metadata URIs use {id}. The substituted ID "MUST be lowercase alphanumeric" with no 0x prefix and "leading zero padded to 64 hex characters" (EIP-1155). Store the raw JSON you fetch.
Store amounts safely. A uint256 can reach 78 digits. That overflows DECIMAL(38) in Spark and Snowflake, and BigQuery BIGNUMERIC cannot hold the full range either. Use Postgres NUMERIC(78,0) or ClickHouse UInt256. Elsewhere, store the raw amount as a string and derive a scaled decimal column. Never cast through a double.
Prices
Oracle feeds. Chainlink aggregators update "only when the Deviation Threshold or Heartbeat Threshold triggers an update" (Chainlink docs). Between updates, the answer can lag the market. latestRoundData returns updatedAt for that reason. answeredInRound is marked "Deprecated" (API reference). For history, ingest each feed's onchain updates as rows. Feed proxies can switch to a new aggregator, so record the aggregator address with each row. Chainlink asks users to "implement controls that detect stale, delayed, missing, or unexpected values" (selecting feeds).
Pyth publishes a confidence interval "because, in real markets, there is no one single price for a product", and suggests pausing "when confidence / price exceeds a threshold" (Pyth best practices). With Pyth Core, a price is written onchain when someone submits an update, so onchain history has gaps. Use Pyth's own historical data for analytics.
DEX-derived prices. Dune combines "Coinpaprika (~2,000 major tokens)" with DEX prices for the long tail. As documented on 2026-10-30, it drops "Prices deviating >3x from 7-day rolling median", "Prices deviating >2x median absolute deviation", and "Trades <$0.01 or >$1M" (Dune prices). Add your own guards:
- Thin pools are easy to move with a flash loan. Set a minimum liquidity.
- Stablecoins can depeg. Do not hardcode $1.
- Wrapped and staked assets (wstETH vs stETH) need their exchange rate.
Fallback order. For each token and timestamp:
- Oracle price, if its age is within the feed heartbeat plus a margin.
- Liquidity-filtered DEX price.
- External market reference, such as an exchange aggregate.
- Null.
A null price is better than a guessed one. Store price_usd, price_source, price_ts, price_age_s and confidence. Token amounts divide by 10^token_decimals. Oracle answers divide by 10^feed_decimals. They differ.
The decode pipeline
raw.logs --> match topic0 --> abi_registry (finalized or hash-keyed)
| | (chain, address, valid_from/to,
| | impl, abi, source)
| | ^
| | resolver: clones, 1967 + beacon,
| | legacy slots, diamonds, depth limit
| v
| decoded events --> facts (transfers, swaps)
| | join token_dim (decimals)
v v join price (fallback order)
unknown_topics backlog usd_value, price_source, price_age_s
Decoding is a pure function of the raw log and the registry row. When a row changes, rebuild only the affected address and block range. Dune names decoded tables <project_name>_<blockchain>.<contract_name>_evt_* and _call_* (Dune docs). A similar convention makes your tables easy to find.
What to take away
- Resolve proxies per block range, from slot values, with beacons and legacy slots.
- Build the ABI registry from finalized data.
- Decode
Transferby shape and backlog the rest. - Keep missing decimals null and store
uint256without loss. - Price with a stated fallback order, and store source and age.
The on-chain analytics lakehouse uses this layer in a full design. Real-time chain data for trading covers prices for trading. The on-chain analytics warehouse and market data lakehouse pages describe how I approach this work.
If your decoded tables have gaps from proxies, wrong decimals or stale prices, I can review your decoding layer with you.