Skip to content

perf: skip retries for method refusals and trim per-request overhead - #5392

Merged
jxom merged 2 commits into
mainfrom
perf/parallel-and-retries
Nov 3, 2026
Merged

jxom merged 2 commits into
mainfrom
perf/parallel-and-retries

Conversation

@gakonst

@gakonst gakonst commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Stops retrying deterministic method refusals and trims per-request overhead in the http and socket transports.

Changes

  • Don't retry method-not-found or method-not-supported refusals (buildRequest shouldRetry). Since fix: retry http JSON-RPC errors from non-2xx responses by status #5286, a JSON-RPC error from a non-2xx response is retried by its HTTP status. A 403 carrying { "code": -32601, "message": "method not allowed" } (how public Tempo RPCs refuse unserved methods) was retried 3 times with 150/300/600 ms backoff, so callers waited about 1.2 s before they could fall back. -32601 and -32004 now never retry, whatever the status. A retry gets the same refusal, and these codes already didn't retry from 2xx responses. fix: retry http JSON-RPC errors from non-2xx responses by status #5286's intent still holds: other JSON-RPC errors from non-2xx responses keep retrying by status and Retry-After (for example a 403 or 429 with -32000), and the rate-limit codes (-32005, -32007, 429) retry as before.

  • http: build the Request only for onFetchRequest. getHttpRpcClient constructed a Request for every call, but only the hook uses it. Construction copies and encodes the body and links an abort listener. In Node 22 that took about 77 µs for a 4 KB eth_call. fetch applies the same validation when it builds its own request.

  • http, webSocket, ipc: build the TimeoutError only on timeout. Every request eagerly built a TimeoutError for withTimeout. That re-serialized the whole body with stringify, parsed the URL and captured a stack: about 6 µs for a small request, 42 µs for a 4 KB eth_call and 2.4 ms for a 100-request batch, even when the request succeeded. Each client now passes a private marker and maps it to the same TimeoutError when a timeout happens. withTimeout's public signature is unchanged.

  • ZKsync finalizeWithdrawal / isWithdrawalFinalized: fetch the receipt once. getWithdrawalLog and getWithdrawalL2ToL1Log both read the same transaction receipt, one after the other. They now run concurrently, so the deduplicated eth_getTransactionReceipt is sent once instead of twice. I checked this with a counting custom transport.

  • Cache signature hashes in toSignatureHash. Selector matching (decodeFunctionData, decodeEventLog, decodeErrorResult, prepareEncodeFunctionData) ran toFunctionSelector(formatAbiItem(item)), which hashed every ABI item until it found a match. keccak was about 90% of that cost. A pure 8192-entry LruMap keyed by the definition string now memoizes the hash. ABI objects are formatted first, exactly as toSignature did. This follows the checksumAddress cache in getAddress. On Tempo's Abis.tip20 (52 functions, Bun), decoding transferWithMemo went from 1.69 ms to 0.13 ms and encoding it from 234 to 35 µs. Found by a downstream relay.

Overhead of getHttpRpcClient().request with an in-memory fetchFn (Bun, two runs each), before → after:

body before after
4 KB eth_call 974 / 787 µs 759 / 400 µs
100 × 4 KB batch 11.0 / 15.4 ms 6.1 / 8.0 ms

Verification

  • pnpm test --run --project core on src/utils/buildRequest.test.ts, src/utils/rpc/, src/clients/transports/, src/utils/promise/withTimeout.test.ts and the ZKsync withdrawal tests: 15 files passed, 1 skipped (278 tests passed, 26 skipped).
  • The new buildRequest tests (403 + -32601, 403 + -32004, and the shouldRetry unit test) fail without the fix. The 403 + -32000 test retries and succeeds.
  • Second run with the anvil harness on src/utils/abi/, src/utils/hash/, src/errors/, src/utils/errors/ and the getLogs, getContractEvents, readContract, simulateContract and writeContract tests: 801 passed. The one failure is simulateContract > node errors > fee cap too low. That test's TODO says it will fail once Anvil enforces the fee cap in eth_call, which the local Anvil 1.9.0 does. CI's Anvil passes it.
  • tsc -b (src and test projects) and biome check on the changed files pass.

- Never retry JSON-RPC -32601/-32004 errors, even from non-2xx responses.
- Build the onFetchRequest Request only when the hook is set.
- Build TimeoutError only when an http/socket request times out.
- Fetch the ZKsync withdrawal receipt once in finalizeWithdrawal and
  isWithdrawalFinalized.
@changeset-bot

changeset-bot Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 117745a

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

@vercel

vercel Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
viem Ready Ready Preview Nov 3, 2026 2:08am UTC

Request Review

@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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

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

@gakonst
gakonst enabled auto-merge (squash) November 3, 2026 01:44
Selector matching in decodeFunctionData, decodeEventLog, decodeErrorResult
and prepareEncodeFunctionData hashed every ABI item on each call. Memoize
the hash per definition string in an LruMap.
@jxom
jxom disabled auto-merge November 3, 2026 03:46
@jxom
jxom merged commit 9348d38 into main Nov 3, 2026
41 checks passed
@jxom
jxom deleted the perf/parallel-and-retries branch November 3, 2026 03:46
@github-actions github-actions Bot mentioned this pull request Nov 3, 2026
gakonst added a commit to tempoxyz/accounts that referenced this pull request Nov 3, 2026
Updates the Viem pin from the `main` build `0.0.0-9a2b41b1` (#930) to
`0.0.0-9348d386a9f62fd6713124e25360d6040e4a34cf`, the `main` build with
wevm/viem#5392 (published 2026-11-03T04:00:50Z). The catalog and the
override both change. Viem still depends on `ox` 0.14.59, so Ox stays
where it is; it moves in a follow-up.

#5392 is the reason for the bump:
- JSON-RPC `-32601` and `-32004` refusals are no longer retried, even
from non-2xx responses. A public RPC's 403 refusal of `tempo_simulateV1`
now fails at once in any client, not just in `Handler.relay`'s probe
(#941). That probe keeps `retryCount: 0`, which still matters for
transport failures.
- The `http` and socket transports build the `onFetchRequest` `Request`
and the `TimeoutError` only when they're needed.
- `toSignatureHash` caches signature hashes in an LRU, so selector
lookups in `decodeFunctionData`, `decodeEventLog`, `decodeErrorResult`
and `encodeFunctionData` stop rehashing every ABI item.

## Other Viem changes between `9a2b41b1` and `9348d386`

There are 37 commits in `9a2b41b1..9348d386`. These are the ones that
change Tempo behavior the SDK relies on:

- **#5360**: The default expiring-nonce `validBefore` goes from 25 to
270 seconds. A random `nonce` discriminator replaces the random
`validAfter`, and `Transaction.expiringNonceMaxExpiry` (300) is added.
`prepareTransactionRequest` drops a requested `feeToken` from a fill the
fee payer already signed, since that signature covers the filled token.
`Relay.feePayer` caps expiring windows, but the SDK's relay handler
doesn't use `Relay.feePayer`.
- **#5356**: The Tempo chain config adds 5,000 gas for the fee payer's
signature and fee token to a sponsored request whose gas came from the
fill. T14 charges these as intrinsic gas. It doesn't add the gas to
owner-approved configurable transactions. The Tempo formatter now keeps
`capabilities` on fill requests without Tempo fields; it used to drop
`errors: true` there. `Relay.autoSwap` and the opt-in balance diffs are
new `viem/tempo` relay plugins. `Handler.relay` has its own `autoSwap`
and `balanceDiffs` and is unaffected.
- **#5377 / #5382**: When `eth_sendRawTransactionSync` returns error
code 4, `sendTransactionSync` now keeps the nonce and waits for the
receipt with the node's hash, or with a hash it derives locally.
`fallback` no longer forwards that transaction to the next node. The
Provider's root-account sends go through this path.
`AccessKeyTransaction` sends the raw request itself and still treats
code 4 as maybe submitted.
- **#5336**: `fillTransaction` keeps a requested nonce as a `bigint`
(TIP-1106).
- **#5388**: Adds `Account.serialize`/`Account.deserialize` and a
`keyAuthorization` option for access key accounts. These are new APIs
only.
- **#5372**: `estimateGas` now applies block and state overrides instead
of returning a gas limit filled during preparation. The SDK doesn't pass
overrides.
- **#5373**: `NonceManager.reset` now receives the consumed nonce. The
SDK has no nonce manager.
- **#5380 / #5381**: `watchBlocks` and `watchBlockNumber` now emit
missed blocks on fast chains, with catch-up capped at 100 blocks. The
SDK doesn't watch blocks.
- **#5339 / #5370**: `getAbiItem` now rejects overloads it can't tell
apart, and `validateTypedData` rejects invalid EIP-712 field types.
Nothing in the suites hits either.

No source changes were needed. The error snapshots now show the new
version string.

## Lockfile

A full resolution re-resolves every peer and adds a real `[email protected]`
(with `[email protected]`) as a tooling peer, which
`scripts/zod-security.test.ts` rejects. `--fix-lockfile` does the same.
So the lockfile is edited directly:
- the version and integrity of `viem`;
- the 5 hashed peer suffixes whose input contains the `viem` version
(`@wagmi/[email protected]`, 3× `@wagmi/[email protected]` and
`[email protected]`).

To get the new hashes, I resolved both the old and the new graphs with
`--config.peers-suffix-max-length=100000`. Hashing the old graph's
unhashed suffixes (SHA-256, first 32 hex characters) reproduces every
hash on `main`. The new hashes match what pnpm wrote on a full
resolution. The lockfile diff touches only these entries.

I logged this as friction in `.agents/friction-log/`.

No changeset: the published `viem` peer range (`>=2.57.12`) and the `ox`
range don't change.

## Validation

- `pnpm install --frozen-lockfile` from empty `node_modules`: passed.
- `pnpm check:types`: passed.
- `pnpm check`: 0 errors; the 5 warnings are already on `main`.
- `pnpm build`: passed.
- `pnpm test --project lib/pure --reporter=dot`: 50 files, 889 tests
passed.
- `VITE_NODE_ENV=localnet VITE_NODE_TAG=latest pnpm test --project
lib/localnet --reporter=dot --maxWorkers=4` against
`ghcr.io/tempoxyz/tempo:latest` in OrbStack: 10 files, 658 tests passed.

This branch was successfully deployed

1 active deployment
Preview — 117745ae Deployed Nov 3, 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