You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Coalesce concurrent checkBalance() RPC reads in BalanceMonitor (src/balance.ts) and SolanaBalanceMonitor (src/solana-balance.ts) using singleflight deduplication, and guard cache writes with an invalidation epoch so superseded in-flight reads cannot overwrite newer state.
Root Cause & Problem
When the 30s balance cache is cold, expired, or zero, every concurrent checkBalance() / checkSufficient() call fires its own independent RPC request (readContract on Base, /v1/balance on Arc, or getTokenAccountsByOwner with up to 3 retries on Solana). Under concurrent traffic or after the proxy's 2.5s optimistic balance-check timeout leaves a background RPC in flight, subsequent requests stampede the RPC endpoint and trigger rate limits (especially 429s on public Solana RPC).
Calling invalidate() (for example after a payment failure) while an RPC read is already in flight could allow the older read to populate cachedBalance once it resolved.
cachedAt was captured before await this.fetchBalance() rather than when the RPC response arrived, and a 0n result did not clear cachedBalance.
Technical Solution
Added inflightFetch to both BalanceMonitor and SolanaBalanceMonitor so concurrent checkBalance() calls share a single in-flight fetchBalance() promise and clean it up in .finally() (allowing subsequent checks to retry after errors or zero balances).
Added a cacheEpoch counter incremented by invalidate(). invalidate() clears inflightFetch and ensures any pre-invalidation in-flight read neither overwrites cachedBalance/cachedAt nor clears a newer inflightFetch.
Recorded cachedAt = Date.now() upon RPC completion and explicitly cleared cachedBalance/cachedAt when the fetched balance is 0n.
Added regression tests in src/balance.arc.test.ts and src/solana-balance.test.ts covering concurrent coalescing, error recovery, and mid-flight invalidate() epoch isolation.
Test Plan
npx vitest run src/balance.arc.test.ts src/solana-balance.test.ts src/proxy.balance-check-latency.test.ts src/proxy.health-balance-timeout.test.ts -> 4 test files passed, 15 tests passed (11 in src/balance.arc.test.ts, 2 in src/solana-balance.test.ts, 1 in src/proxy.balance-check-latency.test.ts, 1 in src/proxy.health-balance-timeout.test.ts).
npm run typecheck (tsc --noEmit) -> passed (exit code 0).
No actionable comments were generated in the recent review.
Walkthrough
Both balance monitors now share concurrent reads and use an epoch to prevent reads started before invalidation from replacing newer cached results. Tests cover read sharing, retry after failure, and invalidation behavior.
Changes: Balance read coordination
Layer / File(s)
Summary
BalanceMonitor read and invalidation src/balance.ts, src/balance.arc.test.ts
checkBalance() reuses a pending read. Cache updates apply only when the read’s epoch is current. Tests cover concurrent callers, failed-read retry, and late results after invalidation.
Solana balance read and invalidation src/solana-balance.ts, src/solana-balance.test.ts
checkBalance() reuses a pending RPC read. Cache updates apply only when the read’s epoch is current. Tests cover concurrent callers and late results after invalidation.
BlockRunAI/ClawRouter#527: Adds Arc balance fetching to BalanceMonitor, whose fetchBalance() call is now covered by the shared-read and epoch logic.
Suggested reviewers:1bcmax, tenequm, vickyxai
Merge Risk: Minimal · up to 98a05
This change shares concurrent balance reads and stops reads started before an invalidation from overwriting newer cached balances. No concrete merge-blocking risk was found, and the change is easy to revert.
Pre-merge checks: 4
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
The title follows the conventional commit format and names the main change: concurrent checkBalance RPC reads are coalesced, and invalidation is made epoch-safe. The raw summary confirms both behavior…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title follows the conventional commit format and names the main change: concurrent checkBalance RPC reads are coalesced, and invalidation is made epoch-safe. The raw summary confirms both behaviors in src/balance.ts and src/solana-balance.ts, with matching tests. The title is specific and accurate, and it is a single sentence. It is long at 85 characters, but it stays readable.
Finishing Touches
Generate unit tests (beta)
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Reviewing files that changed from the base of the PR and between b7f6b4b and 98a050c.
Files selected for processing: 4
src/balance.arc.test.ts
src/balance.ts
src/solana-balance.test.ts
src/solana-balance.ts
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Coalesce concurrent
checkBalance()RPC reads inBalanceMonitor(src/balance.ts) andSolanaBalanceMonitor(src/solana-balance.ts) using singleflight deduplication, and guard cache writes with an invalidation epoch so superseded in-flight reads cannot overwrite newer state.Root Cause & Problem
checkBalance()/checkSufficient()call fires its own independent RPC request (readContracton Base,/v1/balanceon Arc, orgetTokenAccountsByOwnerwith up to 3 retries on Solana). Under concurrent traffic or after the proxy's 2.5s optimistic balance-check timeout leaves a background RPC in flight, subsequent requests stampede the RPC endpoint and trigger rate limits (especially 429s on public Solana RPC).invalidate()(for example after a payment failure) while an RPC read is already in flight could allow the older read to populatecachedBalanceonce it resolved.cachedAtwas captured beforeawait this.fetchBalance()rather than when the RPC response arrived, and a0nresult did not clearcachedBalance.Technical Solution
inflightFetchto bothBalanceMonitorandSolanaBalanceMonitorso concurrentcheckBalance()calls share a single in-flightfetchBalance()promise and clean it up in.finally()(allowing subsequent checks to retry after errors or zero balances).cacheEpochcounter incremented byinvalidate().invalidate()clearsinflightFetchand ensures any pre-invalidation in-flight read neither overwritescachedBalance/cachedAtnor clears a newerinflightFetch.cachedAt = Date.now()upon RPC completion and explicitly clearedcachedBalance/cachedAtwhen the fetched balance is0n.src/balance.arc.test.tsandsrc/solana-balance.test.tscovering concurrent coalescing, error recovery, and mid-flightinvalidate()epoch isolation.Test Plan
npx vitest run src/balance.arc.test.ts src/solana-balance.test.ts src/proxy.balance-check-latency.test.ts src/proxy.health-balance-timeout.test.ts-> 4 test files passed, 15 tests passed (11 insrc/balance.arc.test.ts, 2 insrc/solana-balance.test.ts, 1 insrc/proxy.balance-check-latency.test.ts, 1 insrc/proxy.health-balance-timeout.test.ts).npm run typecheck(tsc --noEmit) -> passed (exit code 0).npm run lint(eslint src/ scripts/) -> passed (exit code 0).npx prettier --check src/balance.ts src/solana-balance.ts src/balance.arc.test.ts src/solana-balance.test.ts-> passed (all matched files use Prettier code style).Summary by CodeRabbit