Skip to content

perf: encode ABI parameters in one pass - #5525

Closed
jxom wants to merge 3 commits into
mainfrom
perf/encode-abi-parameters
Closed

jxom wants to merge 3 commits into
mainfrom
perf/encode-abi-parameters

Conversation

@jxom

@jxom jxom commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Speeds up encodeAbiParameters and encodeFunctionData (B3 from the perf audit).

Changes

  • encodeAbiParameters parses each parameter once per call into a small descriptor (kind, array length, tuple components, integer bounds). Before, it re-ran the type regexes, startsWith, split and { ...param, type } spreads for every value.
  • Values are encoded straight to un-prefixed hex, appended with +=, and joined once at the end. This replaces a concatHex (reduce + replace('0x', '')) and a size() per part. The final join flattens the string, so callers retain the same size as before.
  • Integer bounds are computed once per bit size (a map with at most 64 entries) instead of 2n ** BigInt(size) per value.
  • The address, bool, integer and string checks run in the same order and throw the same errors as before. Values the bytes fast path does not handle (odd length, malformed, wrong size, odd bytesN types) go through the existing encodeBytes. Malformed parameters (missing type, tuples without components, unknown types) throw the same errors at the same point.
  • prepareEncodeFunctionData caches selectors in a WeakMap keyed by the ABI item, and encodeFunctionData concatenates the selector directly. Entries die with the ABI. A caller that mutates an ABI item after first use keeps the old selector.

Bundle size (needs a maintainer decision)

The encoder adds about 430–570 B (brotli) to the bundles that include it. main has only about 300 B of headroom on privateKeyToAccount and about 700 B on viem/actions, so this PR raises five limits by 0.5 kB:

Entry main This PR Old limit → new limit
import * from 'viem' (esm) 91,274 91,846 92 → 92.5 kB
require('viem') (cjs) 118.5 → 119 kB
viem/account-abstraction 61,458 61,941 62 → 62.5 kB
privateKeyToAccount 21,696 22,125 22 → 22.5 kB
viem/actions 72,793 73,365 73.5 → 74 kB

(Measured locally with the same tsc build and size-limit; the cjs entry wasn't measured locally.)

Benchmarks

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

Bench Before After
encodeAbiParameters nested struct (existing) 112,299 165,697 1.5×
Seaport fulfillAdvancedOrder (existing) 10,024 35,159 3.5×
uint256[1000] 674 7,010 10.4×
address[1000] 1,054 2,926 2.8×
string[100] 2,153 6,438 3.0×
tuple[300] 564 3,038 5.4×
encodeFunctionData ERC-20 transfer 284,788 750,858 2.6×
encodeFunctionData multicall3 aggregate3, 100 calls 1,744 6,778 3.9×

Memory per call (node --expose-gc, 512 MiB young generation):

Case Allocated before → after Retained before → after
uint256[1000] 1.37 MiB → 254 KiB 62.8 → 62.7 KiB
aggregate3 calls (500) 3.59 MiB → 717 KiB 219.1 → 218.9 KiB
encodeFunctionData transfer 4.2 → 1.8 KiB 292 → 234 B

Correctness

  • Equivalence with origin/main: a scratch harness ran 12,547 inputs per seed over 5 seeds (about 63k inputs, about 22k of them errors). It compared output, error class and error message.
    • Inputs: random nested types and values; corrupted values (wrong types, out-of-range integers, odd and invalid hex, bad checksums).
    • Odd type strings: bytes0, bytes33, bytesbytes, uint7, tuple without components, string[0], tuple[0][].
    • Malformed ABI objects: holes in components, non-array components, missing type.
    • Every input matched. encodeFunctionData matched on about 100 inputs per seed across the ERC-20, multicall3 and Seaport ABIs, with the selector cache cold and warm.
  • Ox's ABI fuzz suites run against Viem: AbiParameters.fuzz, AbiParameters.differential.fuzz (encode vs ethers AbiCoder, encodeFunctionData vs ethers Interface) and AbiParameters.adversarial.fuzz (mutated decode throws only BaseErrors) all passed at FC_NUM_RUNS=20000. A deliberately broken bytesN padding made 4 of the 8 properties fail, so the harness catches regressions.
  • New tests: numbers encode like bigints, odd-length bytes is left-padded, and the first invalid value throws.

Tests

  • src/utils/abi (Anvil-backed): all pass.
  • readContract, multicall, simulateContract: all pass except simulateContract > node errors > fee cap too low, which fails the same way on origin/main in this environment.
  • tsc -p src/tsconfig.json: passes. Biome: clean.

Parse parameters once per call, build un-prefixed hex and join it once,
precompute integer bounds, and cache function selectors per ABI item.
Values outside the fast path go through the existing per-parameter code,
so output and errors are unchanged.

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:20am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: de46219

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:18:57.523436Z de46219 New commits
ℹ️ 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

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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

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

Fold the address, bool, number and string checks into the fast path and
keep only the bytes encoder as a fallback, so the encoder adds less to
the bundle. Raise the size limits the change still crosses by 0.5 kB.
Fix the test value types.

Amp-Thread-ID: https://ampcode.com/threads/T-01a1e1b3-ce83-72d3-b448-f29dd09b6e57
Co-authored-by: jxom <[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 — de462193 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