Skip to content

perf: audit bundle: fixes, async waterfalls, primitives, ABI/RLP/formatters - #5543

Merged
jxom merged 25 commits into
mainfrom
perf/audit-bundle
Nov 16, 2026
Merged

jxom merged 25 commits into
mainfrom
perf/audit-bundle

Conversation

@jxom

@jxom jxom commented Nov 16, 2026

Copy link
Copy Markdown
Member

Bundles the performance, memory and security work from the Viem audit into one PR. Each commit is one logical change and matches one of the PRs listed below (review fixes and test-only follow-ups are folded into the commit they belong to). Every change keeps outputs and errors identical unless its changeset says otherwise, and every perf commit adds or extends a colocated *.bench.ts.

Fixes (#5523)

  • generateSiweNonce drew from a Math.random window that slid one character per call, so consecutive nonces shared 95 of 96 characters. It now uses crypto.getRandomValues.
  • WebSocket/IPC reconnects stalled after one failed attempt and left a dead client cached for the URL. Reconnects now continue, and a client is evicted only after its last attempt fails.
  • IPC handles a graceful close and shares one socket between requests and subscriptions.
  • waitForTransactionReceipt no longer polls forever when its timeout fires during the first lookup.
  • withCache and the EIP-1559 network cache are bounded LRUs.

Quadratic code made linear (#5526)

Change main → branch
Batch scheduler, 5,000 items in one tick 305ms → 1.93ms
Batched call, 5,000 calls end to end 243ms → 99ms
multicall, 10,000 calls 294ms → 203ms
IPC response, 16MB in 64KB chunks 5,798ms → 125ms

Async waterfalls (#5527–#5531), 50ms per request

Change main → branch
estimateFeesPerGas (EIP-1559 and legacy) 102 → 51ms
prepareTransactionRequest, legacy fees 153 → 102ms
prepareTransactionRequest, nonce manager 153 → 102ms
prepareTransactionRequest, first call on a new client 204 → 154ms
OP Stack getWithdrawalStatus 360 → 258ms
zkSync deposit 820 → 464ms

On a legacy network, the first call on a new client sends one extra request (#5529).

Encoding primitives (#5534–#5538)

Change main → branch
bytesToHex (native toHex when available) 1.9× at 32 B (1,003 → 119 B allocated), 4.6–5.2× at 1–100 KB
hexToBytes 2.4–2.9×
toBytes(hex) 2.4×
bytesToNumber 6.3×
small bytesToBigInt 4.6×
numberToHex with size 2.3×
hexToNumber 2.1×
concatHex 2.2–3.1×
trim, padBytes, sliceHex, normalizeSignature, formatUnits 1.3–2×

ABI, RLP and formatters (#5525, #5532, #5533, #5539–#5542)

Change main → branch
ABI encode uint256[1000] 10.4×, ERC-20 transfer 2.6×, 5× less allocation
ABI decode 1.2–2.8×; read limit, budget and bounds checks unchanged
parseEventLogs 1.7–2.8×, 8.1 → 3.9 MiB allocated
Transaction serialize / parse 1.45–7.2× / 1.5–5.5×; a parsed EIP-4844 wrapper retains 515 KiB instead of 8 MiB
OP Stack / Celo / zkSync block formatting 2.7× / 4.2× / 3.8×; transactions keep fast properties
hashTypedData, 100 structs 1.3–1.7×
formatLog 1.05–1.16×

Verification

  • Equivalence harnesses compared each change against main copies on hundreds of thousands of inputs, including malformed and adversarial ones. Relevant Ox fuzzers were ported.
  • On this combined branch: pnpm check:types, pnpm build and Biome pass, and the affected suites pass. The only failures are environment-only and fail the same way on main: anvil 1.9.0 eth_fillTransaction, the fork base fee in call, and a wall-clock bound in waitForTransactionReceipt.
  • CI runs Node 24, which has no native Uint8Array.prototype.toHex, so the native bytesToHex path is exercised only locally (Node 26, Bun).

Not included

  • verifyHash local recovery first: it changes the documented order of auto mode.
  • Native-first stringify: 2.7× slower for values containing bigints.
  • The @noble/hashes 2.x upgrade.
  • fallback({ rank }) stop, socket subscribe timeouts, and the supportsExecutionMode TTL. Each needs a design decision.

Supersedes #5523, #5525, #5526, #5527, #5528, #5529, #5530, #5531, #5532, #5533, #5534, #5535, #5536, #5537, #5538, #5539, #5540, #5541, #5542.

@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 8:53am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c613c0a

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-16T08:54:26.102509Z 6b1fc20 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.

This was referenced Nov 16, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 93e1b1dd31

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +299 to +300
// The timeout fired during the lookup, before polling could be stopped.
if (timedOut) return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve polling for callers still sharing the observer

When two callers with identical options start at different times, they share one observer but have separate timeout deadlines. If the first caller times out during the initial receipt lookup and that lookup subsequently returns no receipt (or a receipt needing more confirmations), this guard exits the shared setup even though the second caller is still waiting. Since observe only runs the first caller's setup callback, no block polling starts and the second caller inevitably times out, even if the transaction confirms before its deadline. Check whether the shared observer still has active listeners rather than stopping solely because its initiating caller timed out.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in the bundle's first commit (fix: secure SIWE nonces…). When the lookup finishes after this caller timed out, polling now still starts if another caller is listening on the same observer. The poll also stops itself once every caller has left. Added args: timeout (polls for a caller sharing a lookup that found no receipt), which fails without the fix.

@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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

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

@jxom jxom changed the title perf: audit bundle — fixes, async waterfalls, primitives, ABI/RLP/formatters perf: audit bundle: fixes, async waterfalls, primitives, ABI/RLP/formatters Nov 16, 2026
@jxom
jxom force-pushed the perf/audit-bundle branch from 93e1b1d to b9182da Compare November 16, 2026 04:40

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b9182dad41

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const requestsAfterLookup = requests
await wait(200)

expect(requests - requestsAfterLookup).toMatchInlineSnapshot('0')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Replace request-count assertions with observable cleanup checks

This timeout test introduces a requests++ counter and asserts its delta rather than verifying observable cleanup behavior. This violates AGENTS.md's explicit “Test behavior, not call-tracking” requirement, which prohibits invocation flags and counters. Replace the counter-based assertion with an observable cleanup check; the newly added recording-client request snapshots should follow the same convention.

AGENTS.md reference: AGENTS.md:L204-L207

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced the counter in args: timeout (fires during the first receipt lookup). The proxy now records the RPC methods sent after the first lookup returns, and the test snapshots that list as []. It fails with ["eth_blockNumber", …] when the timeout guard is removed.

The recording clients in the prepareTransactionRequest and estimateFeesPerGas tests stay as they are. They snapshot which RPC requests were already in flight when each request was sent. That concurrency is the behavior those commits change, it's observable on the wire, and it doesn't track whether a hook was called.

ampagent and others added 17 commits November 16, 2026 05:53
With a nonceManager, prepareTransactionRequest awaited the consumed nonce
before requesting the block and fees. consume is still called at the same
point, so concurrent prepares keep receiving nonces in call order, but the
nonce is now awaited together with the other parameters. It is still
awaited first when eth_fillTransaction is attempted or the chain has a
prepareTransactionRequest hook, since both read it from the request, and a
nonce error still takes precedence over the errors of the other
parameters.

Co-authored-by: jxom <[email protected]>
On a client that has not detected the network's transaction type yet,
prepareTransactionRequest requested the latest block and only then the
priority fee. Without chain fee hooks, the priority fee is now estimated
concurrently with that block. On legacy networks the estimate goes
unused, once per client.

Co-authored-by: jxom <[email protected]>
On Portal v3+, getWithdrawalStatus looked up the proof submitter before
starting the dispute game lookup and the finalizedWithdrawals read,
although neither depends on it. They now start right after the portal
version, and their results are still read through Promise.allSettled in
the same order, so the returned status and errors are unchanged.

Co-authored-by: jxom <[email protected]>
deposit read the bridge addresses, the bridgehub, the base token, the
fees, the token metadata and the asset id one after another, and
requested zks_getBridgeContracts twice. The independent reads now start
together and are awaited in their original order, so errors surface in
the same order, and the bridge addresses are reused for the L2 gas limit
estimate.

Co-authored-by: jxom <[email protected]>
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.

Co-authored-by: jxom <[email protected]>
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]>
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.

Co-authored-by: jxom <[email protected]>
toRlp builds hex output straight from hex and byte leaves, falling back to
the byte encoder for anything else so errors are unchanged. fromRlp walks
hex input as a string with the cursor's bounds errors. Leaves of inputs up
to 4096 hex characters, and leaves of at least an eighth of a longer
input, are slices of it; other leaves are copied so they do not keep a
long input alive.

Co-authored-by: jxom <[email protected]>
…elete

formatTransaction leaves fields a transaction type does not have out of
the copy instead of deleting them, so results stay fast-properties
objects. Fee fields are still parsed for every type, so errors are
unchanged. The OP Stack, Celo, and zkSync block formatters format each
transaction once and pass formatBlock an empty list, in the same order
of errors as before.

Co-authored-by: jxom <[email protected]>
hashStruct passes a map of type hashes through encodeData and
encodeField, so encodeType, the dependency walk, the sort and keccak run
once per struct type instead of once per struct value, such as every
element of a struct array.

Co-authored-by: jxom <[email protected]>
formatLog builds the formatted log once and assigns args and eventName
only when there is an event name, instead of spreading a temporary
object (or an empty one) into the result. Own args and eventName keys
on the input keep their position, as before.

Co-authored-by: jxom <[email protected]>
Raised the size-limit entries that the bundled changes exceed, to the next 0.5 kB step above CI's measured sizes.

Amp-Thread-ID: https://ampcode.com/threads/T-01a1e11e-d5d8-712a-b0ce-513efc7078b2
Co-authored-by: jxom <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c613c0aa65

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +617 to +620
// Every caller left, for example by timing out, so stop polling.
if (!listenersCache.get(observerId)?.length) {
_unwatch?.()
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stop shared polling when the last caller times out

When identical waits overlap and both time out while the chain head remains unchanged, the shared block watcher is never stopped. Only the initiating caller receives _unwatch; its timeout now deliberately preserves polling for the second caller, but the second caller's timeout has no _unwatch to invoke. This fallback does not run either, because watchBlockNumber skips onBlockNumber when the head is unchanged (and on RPC failures). On a stalled chain or an on-demand mining node, this leaves RPC polling and timers running indefinitely after every wait has rejected. Make the shared watcher's cleanup available to the last departing caller rather than relying on another block emission.

Useful? React with 👍 / 👎.

@jxom
jxom merged commit 79966ad into main Nov 16, 2026
39 of 40 checks passed
@jxom
jxom deleted the perf/audit-bundle branch November 16, 2026 09:10
This was referenced Nov 16, 2026

This branch had an error being deployed

1 failed deployment
Preview — 6b1fc208 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