Repository navigation
Conversation
- `generateSiweNonce` now draws from `crypto.getRandomValues`. It used `uid(96)`, whose `Math.random` window slid one character per call, so consecutive nonces shared 95 of 96 characters. - WebSocket and IPC clients keep reconnecting after a failed attempt. The failed socket's error and close events arrived while the attempt was in progress, so reconnection stalled and the dead client stayed cached for the URL. Once attempts run out, the client is dropped from the cache and its keep-alive interval stops. - IPC clients handle a graceful close: pending requests reject with `SocketClosedError` instead of waiting for their timeout, and reconnect starts. IPC subscriptions and `getRpcClient` reuse the socket configured with `reconnect` instead of opening a second one. - `waitForTransactionReceipt` no longer starts polling when its timeout fires during the first receipt lookup. - `withCache` and the EIP-1559 network cache are bounded LRUs; both grew by one entry per client. Amp-Thread-ID: https://ampcode.com/threads/T-01a1e11e-d5d8-712a-b0ce-513efc7078b2 Co-authored-by: jxom <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
🦋 Changeset detectedLatest commit: 0a62e65 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 60b7e9d655
ℹ️ 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".
| keepAliveTimer && clearInterval(keepAliveTimer) | ||
| if (socketClientCache.get(id) === socketClient) | ||
| socketClientCache.delete(id) |
There was a problem hiding this comment.
Defer cache eviction until the final reconnect actually fails
With reconnect: { attempts: 1 }, a WebSocket disconnect reaches this eviction branch before its reconnect attempt even starts: attemptReconnect() increments reconnectCount, then calls socket.close(), whose implementation in src/utils/rpc/webSocket.ts synchronously invokes onClose_() and re-enters attemptReconnect(). Because the count now equals the limit, this branch deletes the cached client despite the pending reconnect. If that reconnect succeeds, setup() restarts its keep-alive interval without restoring the cache entry, so subsequent transport requests open another socket while the recovered socket remains alive. Check reconnectInProgress before the exhaustion branch and evict only after the final attempt has actually failed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7d8b0fe: a re-entrant call while the last attempt is pending now returns early, so eviction waits until that attempt fails. Covered by reconnects the cached client when the last attempt succeeds in src/utils/rpc/webSocket.test.ts, which failed before the fix.
| return { | ||
| close() {}, | ||
| ping() { | ||
| pings++ |
There was a problem hiding this comment.
Exercise reconnect exhaustion against a real ephemeral server
The new reconnect regression test supplies a fake socket with no-op close() and request() methods, contrary to the root AGENTS.md prohibition on mocks and stubs. In particular, the no-op close() omits the production WebSocket wrapper's synchronous close callback, so this test cannot expose eviction caused by re-entering attemptReconnect() when the last attempt is scheduled. Replace the fabricated socket with a real ephemeral WebSocket or IPC server and verify recovery and exhaustion through observable connection behavior.
AGENTS.md reference: AGENTS.md:L155-L158
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Replaced in 7d8b0fe: the stub-socket test is gone, and reconnect recovery and exhaustion are now tested against a real ws server in src/utils/rpc/webSocket.test.ts.
The WebSocket wrapper's `close()` calls back into `attemptReconnect()` while the final attempt is pending, so the client was evicted even when that attempt then succeeded. Eviction now waits until the last attempt fails. The reconnect tests now run against a real `ws` server instead of a stub socket. Amp-Thread-ID: https://ampcode.com/threads/T-01a1e11e-d5d8-712a-b0ce-513efc7078b2 Co-authored-by: jxom <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7d8b0fe27f
ℹ️ 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".
| if (socketClientCache.get(id) === socketClient) | ||
| socketClientCache.delete(id) |
There was a problem hiding this comment.
Guard stale clients against evicting their replacements
After a disconnect with reconnect: false, or after reconnect attempts are exhausted, this eviction allows another request to cache a replacement client. If the caller subsequently cleans up the old client with oldClient.close(), that method still unconditionally calls socketClientCache.delete(id), removing the live replacement's entry. The following request then opens another connection while the replacement remains alive and potentially retains its keep-alive interval. This reproduces against a real ephemeral TCP server. Apply the same client-identity guard to cache deletion in close() so cleaning up an evicted client cannot evict its replacement.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the latest commit: close() now only deletes the cache entry if it still points to this client. Covered by closing an evicted client keeps its replacement cached in src/utils/rpc/webSocket.test.ts, against a real ws server.
| )({ hash }).catch(() => undefined) | ||
|
|
||
| if (signal?.aborted) return | ||
| if (signal?.aborted || timedOut) return |
There was a problem hiding this comment.
Preserve shared receipt lookups for callers that have not timed out
When two calls use the same client, hash, and options without an abort signal, observe() shares the first call's lookup, but their timeout deadlines differ if they start at different times. For example, with timeout: 100, calls starting at 0 ms and 60 ms share a receipt lookup that returns successfully at 120 ms. The first caller's timeout removes only its own listener, but this new guard then abandons the shared lookup because it captures that caller's timedOut flag. The second caller consequently times out at 160 ms even though the receipt arrived within its deadline; previously emit.resolve(receipt) resolved it. Stop the lookup only when no active observers remain, or isolate calls whose timeout lifetimes differ.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in the latest commit: a receipt from the first lookup resolves every caller sharing the observer, and the timeout only stops polling from starting afterwards. Covered by args: timeout (a caller sharing the first receipt lookup keeps its own deadline), which failed before the fix.
|
Published pnpm add viem@pr-5523
pnpm add [email protected] |
- A receipt found by the first lookup now resolves every caller sharing the observer, even when the first caller already timed out. The timeout only stops polling from starting afterwards. - Closing a socket client that was already evicted no longer evicts the client that replaced it. - Added `@types/ws` for the WebSocket server used in the reconnect tests. Amp-Thread-ID: https://ampcode.com/threads/T-01a1e11e-d5d8-712a-b0ce-513efc7078b2 Co-authored-by: jxom <[email protected]>
|
Bundled into #5543 as its own commit, so this PR is superseded. Closing in favour of the bundle. |
Fixes found in a performance and memory audit of Viem. Each fix has a regression test that fails without it.
Security
generateSiweNoncewas predictable. It returneduid(96), which reads aMath.randombuffer through a window that slides one character per call, so consecutive nonces shared 95 of their 96 characters. It now usescrypto.getRandomValues(viaox/Hex).Reliability and memory
errorandclosewhile the reconnect attempt is still in progress, so neither scheduled the next attempt. The client stayed cached for the URL, so every later request failed, even from new clients and after the node recovered, and its keep-alive interval kept the process alive. Now a failed attempt schedules the next one. Once attempts run out, the client is removed fromsocketClientCacheand its keep-alive interval stops.getSocketnever wiredonClose, so in-flight requests hung until their timeout and no reconnect started. Also fixessocket.off('message'), which should be'data'.subscribeandgetRpcClientcalledgetIpcRpcClient(path)withoutreconnect, so they got a different cache entry, and the subscription socket ignored the reconnect policy.waitForTransactionReceiptkept polling after timing out. If the timeout fired during the first receipt lookup, the timer ran beforewatchBlockNumberexisted. The poll then started anyway and never stopped: about 168 requests/s for 50 timed-out waits.withCacheandeip1559NetworkCachewere unbounded maps keyed byclient.uid, adding one entry per client orclient.scope(): +23.7MB per 100k clients. They are nowLruMap(8192)andLruMap(128), matchingsupportsFillTransaction.Left for follow-ups
These were found in the same audit but need a design decision:
fallback({ rank }): ranking never stops after the client is dropped; noticing a dropped client needsWeakRefor an explicit stop.unsubscribecould surface as an unhandled rejection in watchers.supportsExecutionModecaches withcacheTime: Infinity: the result goes stale after a delegation change. This PR's LRU bounds its memory.Verification
main:connections2 vs 4TimeoutErrorvsSocketClosedErrortrueresponseCache.size8200src/utils/rpc,src/clients/transports,src/utils/promise,src/utils/siwe,getBlockNumber,watchBlockNumber,waitForTransactionReceiptandprepareTransactionRequest.prepareTransactionRequest > with eth_fillTransaction > args: maxFeePerGas (under default tip)fails identically onmainwith anvil 1.9.0.waitForTransactionReceipt > waits for confirmationsfailed a wall-clock bound under load (6,546 ms vs 6,500 ms) and passes in isolation.pnpm check:typesandbiome checkpass.