Skip to content

perf: decode ABI parameters with compiled descriptors - #5532

Closed
jxom wants to merge 1 commit into
mainfrom
perf/decode-abi-parameters
Closed

jxom wants to merge 1 commit into
mainfrom
perf/decode-abi-parameters

Conversation

@jxom

@jxom jxom commented Nov 16, 2026

Copy link
Copy Markdown
Member

Speeds up decodeAbiParameters (B2 from the perf audit). The decoder's safety limits are unchanged: the 8192 recursive read limit, the 32× bytes/string budget and every bounds check.

Changes

  • Parse once per call: each parameter becomes a descriptor (kind, array length and element, tuple components and naming, integer size and sign) instead of re-running getArrayComponents, split('bytes'), split('int'), hasDynamicChild and { ...param, type } spreads for every element. A cross-call WeakMap cache was measured during the audit and didn't help, so descriptors are rebuilt per call and retain nothing.
  • Offsets, lengths and small integers: read straight from the 32-byte word when it is below 2^53, falling back to bytesToNumber, so unsafe values throw the same IntegerOutOfRangeError.
  • uint256/int256: read as four getBigUint64 limbs from the cursor's DataView instead of bytesToHex + BigInt.
  • Addresses and bools: addresses are hex-encoded from a subarray (no sliceBytes copy). Bools are checked in place, with bytesToBool kept for invalid words so the error is identical.
  • Strings: decoded with one shared TextDecoder.
  • Cursor (src/utils/cursor.ts, internal):
    • The DataView is created on first use.
    • Re-reads are tracked in a lazily allocated bitset instead of a Map<number, number>. The bitset grows when a read starts past the end: a short bytesN in a final partial word moves the cursor up to 32 bytes past the end, and zero-width reads there must still count against the limit.
    • A new test covers that case. A bitset sized only to the input would let uint256[0][4294967295] after such a bytes1 run 4 billion iterations.
    • positionReadCount and getReadCount were only used by the cursor itself and are gone.

Bundle size (needs a maintainer decision)

Adds about 400–700 B (brotli). 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,782 92 → 92.5 kB
require('viem') (cjs) 118.5 → 119 kB
viem/account-abstraction 61,458 61,847 62 → 62.5 kB
viem/actions 72,793 73,479 73.5 → 74 kB
viem/chains 136,793 137,291 137.5 → 138 kB

CI measures about 200–300 B more than this local build. #5525 (encoder) raises the same limits, so whichever lands second needs another bump.

Benchmarks

SKIP_GLOBAL_SETUP=true ./node_modules/.bin/vitest bench -c ./test/vitest.config.ts --project core --run src/utils/abi/decodeAbiParameters.bench.ts, origin/main vs this branch (ops/s):

Bench Before After
Seaport fulfillAdvancedOrder (existing static struct) 11,233 22,587 2.0×
uint256[1000] 590 1,658 2.8×
address[1000] 629 771 1.2×
string[100] 2,753 6,591 2.4×
multicall3 aggregate3 return, 500 results 347 861 2.5×

address[1000] is dominated by checksumAddress (keccak per address), which is outside this change. After this change, hexToBytes on the input is the largest remaining cost of most decodes. Decoding straight from the hex string is the next step, not done here.

Memory per call (node --expose-gc):

Case Allocated before → after
uint256[1000] 1.59 MiB → 341 KiB
address[1000] 1.61 → 1.19 MiB
aggregate3 return (500) 3.35 MiB → 835 KiB
Seaport 102 → 38 KiB

Correctness

  • Equivalence with origin/main: a scratch harness ran about 89.7k inputs per seed over 5 seeds (about 449k inputs, about 208k of them errors). It compared values, error class and error message.
    • Valid encodings of random nested types.
    • Mutations: truncations, adversarial words (offsets at, past and around the end, 2^32, 2^53, 2^255, 2^256−1), byte flips, uppercase, odd length, invalid characters.
    • Shared-tail and zero-width amplification payloads, including the read-past-the-end case above.
    • Odd types (bytes0, bytes33, bytesbytes, uint7, tuple without components) and malformed ABI objects.
    • Everything matched.
  • Ox's ABI fuzz suites run against Viem: round-trip, differential encode vs ethers, and adversarial decode (mutated data must throw only BaseErrors) all passed at FC_NUM_RUNS=20000.
  • New committed tests:
    • The read-past-the-end read-limit regression.
    • A seeded encode → decode → encode round-trip over 500 random type trees.
  • Existing bug found, not changed here: decoding a zero-length fixed array of a dynamic type as the last parameter (string[0], bytes[0]) throws PositionOutOfBoundsError on main and on this branch. The round-trip test leaves zero-length arrays out.

Tests

  • src/utils/abi, src/utils/encoding, src/utils/blob, cursor, readContract, multicall, call (Anvil-backed): all pass except call > errors > gas fee is less than block base fee, which fails the same way on origin/main in this environment.
  • tsc -p src/tsconfig.json: passes. Biome: clean.

Parse parameters once per call, read offsets, lengths and integers
straight from the word, create the cursor's DataView lazily, track
re-reads with a bitset, and share one TextDecoder. The read limit,
budget and bounds checks are unchanged.

Co-authored-by: jxom <[email protected]>
Amp-Thread-ID: https://ampcode.com/threads/T-01a1e1b3-ce83-72d3-b448-f29dd09b6e57
@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:22am UTC

Request Review

@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:21:39.139768Z 66b7881 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.

@changeset-bot

changeset-bot Bot commented Nov 16, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 66b7881

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

@github-actions

Copy link
Copy Markdown
Contributor

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

pnpm add viem@pr-5532
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 — 66b7881b 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