Skip to content

perf: parse event logs with per-call event plans - #5533

Closed
jxom wants to merge 1 commit into
mainfrom
perf/parse-event-logs
Closed

jxom wants to merge 1 commit into
mainfrom
perf/parse-event-logs

Conversation

@jxom

@jxom jxom commented Nov 16, 2026

Copy link
Copy Markdown
Member

Speeds up parseEventLogs and decodeEventLog (B1 from the perf audit). Outputs and errors are unchanged. Logs are still formatted before they are matched, so a malformed RpcLog that matches no event still throws.

Changes

  • Event plans (internal, decodeEventLog.ts): toEventPlan reads an event's indexed and non-indexed inputs and each indexed input's topic kind once. decodeEventLogWithPlan decodes against one event exactly as decodeEventLog({ abi: [event] }) did, including the 'name' in filter, the selector from formatAbiItem, the anonymous candidate rules and every error. The public decodeEventLog builds a plan for the event it selects.
  • parseEventLogs: builds the plans once per call and maps selectors to plans in ABI order, so overloads keep their precedence. Each log looks up its candidates in the map instead of filtering the whole ABI. A WeakMap index across calls was avoided because it goes stale when an ABI array is mutated.
  • Topic shortcut: a topic that matches /^0x[0-9a-fA-F]{64}$/ is read directly for address (checksum of the last 20 bytes), uint wider than 48 bits (BigInt(topic)) and bytesN (lowercased prefix). Other topics and types still go through decodeAbiParameters, so short, long or invalid topics throw the same errors.
  • Skipping certain failures: in strict mode, a candidate with fewer topics than indexed inputs, or with empty data and non-indexed inputs, always throws. Those candidates were tried and the error discarded; they are now skipped before the error is built. This is the ERC-721 Transfer matched against ERC-20's Transfer. Non-strict fallback still uses the first candidate.
  • .map().filter() became one loop.

Benchmarks

src/utils/abi/parseEventLogs.bench.ts used to fetch logs from mainnet at import. It now builds 1000 deterministic logs: 60% ERC-20 Transfer, 10% Approval, 10% ERC-721 Transfer and 20% events outside the ABI. src/utils/abi/decodeEventLog.bench.ts is new.

SKIP_GLOBAL_SETUP=true ./node_modules/.bin/vitest bench -c ./test/vitest.config.ts --project core --run src/utils/abi/parseEventLogs.bench.ts src/utils/abi/decodeEventLog.bench.ts, origin/main vs this branch, mean ms per call (two runs, noisy machine):

Bench Before After
parseEventLogs, 1000 RpcLogs, erc20Abi 9.2–10.4 4.4–5.5 1.7–2.4×
parseEventLogs, 1000 formatted Logs 8.9–11.7 4.1–4.6 1.9–2.8×
parseEventLogs, eventName + args filter 9.6–10.7 3.9–4.1 2.4–2.7×
decodeEventLog × 500 ERC-20 logs 5.1–6.7 3.9–4.3 1.3–1.6×

Memory per call (node --expose-gc, 1000 logs, erc20Abi):

Case Allocated before → after Retained
parseEventLogs, RpcLogs 8.08 → 3.86 MiB unchanged (189 KiB)
parseEventLogs, Logs 8.27 → 3.66 MiB unchanged (168 KiB)
decodeEventLog, one Transfer 11.1 → 7.5 KiB

After this change the profile is led by the checksumAddress LRU (lru.get, about 10%), formatLog, createCursor and hexToBytes in the data decode, all outside this PR's files. The topic regex is about 7%.

Correctness

  • Equivalence with origin/main: scratch harnesses compared output values, key order, error class and error message against copies of the origin/main modules.
    • parseEventLogs: about 3.1k calls per seed over 5 seeds, each with up to 1000 logs. They covered erc20Abi, a 32-event ABI, anonymous events, a nameless event, same-selector overloads (Transfer(bytes20,uint160,uint256)), bytes4/uint48/uint56/int256/bool/uint8[] topics, and every combination of args, eventName and strict. Mutations included truncated or invalid data, missing, extra or uppercase topics, 0X prefixes, 31- and 33-byte topics, invalid hex, random topics, logs with their own eventName, and malformed RpcLog quantities. Everything matched.
    • decodeEventLog: 2k cases per seed over 3 seeds, adding events without inputs, string/tuple indexed inputs and the same topic mutations. Everything matched.
  • Ox fuzz: Ox's AbiEvent fuzz properties were ported to Viem's API, with a differential property against origin/main added for both functions, using Ox's arbitraries for events and logs, recased topics, dropped topics and noise. At 20,000 runs each, all 5 properties passed: round-trip decode, Viem errors only for noise logs, lone-event parseEventLogs, and differential decodeEventLog and parseEventLogs (random eventName, strict).
  • New tests:
    • decodeEventLog: indexed topics in mixed case and dirty address padding decode as before, and a 31-byte address topic still throws AbiDecodingDataSizeTooSmallError. The snapshots were written against origin/main.
    • parseEventLogs: a malformed RpcLog that matches no event still throws.
  • src/utils/abi/ and the getLogs, getContractEvents, watchContractEvent, watchEvent, getFilterLogs and getFilterChanges tests pass against Anvil: 26 files, 623 tests. tsc on src and on the touched tests and benches passes.

Bundle size (needs a maintainer decision)

Measured locally with the same tsc build and size-limit:

Entry main This PR Old limit → new limit
import * from 'viem' (esm) 91,274 91,559 92 → 92.5 kB
require('viem') (cjs) 118.5 → 119 kB
viem/actions 72,793 73,284 73.5 → 74 kB

CI measures about 200–300 B more than this local build. #5525 and #5532 raise the same limits, so whichever lands later needs another bump.

Prepare each event once per parseEventLogs call and look candidates up by
selector, read well-formed address, uint and bytesN topics directly, and
skip candidates that strict decoding would reject for missing topics or
data. Logs are still formatted before matching, so malformed logs keep
throwing.

Amp-Thread-ID: https://ampcode.com/threads/T-01a1e1b3-ce83-72d3-b448-f29dd09b6e57
Co-authored-by: jxom <[email protected]>
@vercel

vercel Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
viem Error Error Nov 16, 2026 1:47am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 16, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 59ab168

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
viem Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T01:45:40.346847Z 59ab168 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

Copy link
Copy Markdown
Contributor

Published [email protected] under the pr-5533 dist-tag, which follows this pull request until it closes.

pnpm add viem@pr-5533
pnpm add [email protected]

jxom commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

Bundled into #5543 as its own commit, so this PR is superseded. Closing in favour of the bundle.

@jxom jxom closed this Nov 16, 2026

This branch had an error being deployed

1 failed deployment
Preview — 59ab168d Deployed Nov 16, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants