From 98a050c69545a7f1a0acddfe5700671902f9df28 Mon Sep 17 00:00:00 2001 From: Tyagiquamar Date: Wed, 25 Nov 2026 22:48:12 +0530 Subject: [PATCH] fix(balance): coalesce concurrent checkBalance RPC reads with epoch-safe invalidation --- src/balance.arc.test.ts | 74 +++++++++++++++++++++++++++++++ src/balance.ts | 35 ++++++++++++--- src/solana-balance.test.ts | 90 ++++++++++++++++++++++++++++++++++++++ src/solana-balance.ts | 35 ++++++++++++--- 4 files changed, 224 insertions(+), 10 deletions(-) create mode 100644 src/solana-balance.test.ts diff --git a/src/balance.arc.test.ts b/src/balance.arc.test.ts index e7236439..4fa39c8e 100644 --- a/src/balance.arc.test.ts +++ b/src/balance.arc.test.ts @@ -85,4 +85,78 @@ describe("BalanceMonitor on Arc", () => { expect(monitor.getChain()).toBe("base"); expect(fetchImpl).not.toHaveBeenCalled(); }); + + it("coalesces concurrent checkBalance calls into a single RPC read", async () => { + let resolveFetch!: (res: Response) => void; + const fetchImpl = vi.fn( + () => + new Promise((resolve) => { + resolveFetch = resolve; + }), + ); + const monitor = new BalanceMonitor(ADDRESS, "arc", fetchImpl as typeof fetch); + + const p1 = monitor.checkBalance(); + const p2 = monitor.checkBalance(); + const p3 = monitor.checkSufficient(1_000_000n); + + expect(fetchImpl).toHaveBeenCalledTimes(1); + resolveFetch(jsonResponse({ balance: "2500000" })); + + const [r1, r2, r3] = await Promise.all([p1, p2, p3]); + expect(r1.balance).toBe(2_500_000n); + expect(r2.balance).toBe(2_500_000n); + expect(r3.sufficient).toBe(true); + expect(fetchImpl).toHaveBeenCalledTimes(1); + }); + + it("recovers after a failed concurrent read so the next check retries", async () => { + let attempt = 0; + const fetchImpl = vi.fn(async () => { + attempt++; + if (attempt === 1) throw new TypeError("fetch failed"); + return jsonResponse({ balance: "1500000" }); + }); + const monitor = new BalanceMonitor(ADDRESS, "arc", fetchImpl as typeof fetch); + + const [a, b] = await Promise.allSettled([monitor.checkBalance(), monitor.checkBalance()]); + expect(a.status).toBe("rejected"); + expect(b.status).toBe("rejected"); + expect(fetchImpl).toHaveBeenCalledTimes(1); + + const info = await monitor.checkBalance(); + expect(info.balance).toBe(1_500_000n); + expect(fetchImpl).toHaveBeenCalledTimes(2); + }); + + it("does not let a pre-invalidation in-flight read poison the cache", async () => { + const resolvers: Array<(res: Response) => void> = []; + const fetchImpl = vi.fn( + () => + new Promise((resolve) => { + resolvers.push(resolve); + }), + ); + const monitor = new BalanceMonitor(ADDRESS, "arc", fetchImpl as typeof fetch); + + const staleCall = monitor.checkBalance(); + expect(fetchImpl).toHaveBeenCalledTimes(1); + + // Payment failed mid-flight: invalidate and start a fresh check. + monitor.invalidate(); + const freshCall = monitor.checkBalance(); + expect(fetchImpl).toHaveBeenCalledTimes(2); + + // Resolve the fresh read first with the new lower balance, then the stale one. + resolvers[1]!(jsonResponse({ balance: "400000" })); + expect((await freshCall).balance).toBe(400_000n); + + resolvers[0]!(jsonResponse({ balance: "9000000" })); + await staleCall; + + // Cache must retain the post-invalidation balance, not the stale 9000000. + const cached = await monitor.checkBalance(); + expect(cached.balance).toBe(400_000n); + expect(fetchImpl).toHaveBeenCalledTimes(2); + }); }); diff --git a/src/balance.ts b/src/balance.ts index 742f9653..5a4bc9b6 100644 --- a/src/balance.ts +++ b/src/balance.ts @@ -109,6 +109,10 @@ export class BalanceMonitor { private cachedBalance: bigint | null = null; /** Timestamp when cache was last updated */ private cachedAt = 0; + /** Shared in-flight RPC read so concurrent checks do not stampede the RPC. */ + private inflightFetch: Promise | null = null; + /** Incremented on invalidate() so a superseded in-flight read cannot repopulate the cache. */ + private cacheEpoch = 0; constructor(walletAddress: string, chain: EvmBalanceChain = "base", fetchImpl?: typeof fetch) { this.walletAddress = walletAddress as `0x${string}`; @@ -146,13 +150,32 @@ export class BalanceMonitor { return this.buildInfo(this.cachedBalance); } - // Fetch from RPC - const balance = await this.fetchBalance(); - if (balance > 0n) { - this.cachedBalance = balance; - this.cachedAt = now; + // Fetch from RPC, coalescing concurrent callers into one in-flight read. + let pending = this.inflightFetch; + if (!pending) { + const epoch = this.cacheEpoch; + pending = this.fetchBalance() + .then((balance) => { + if (this.cacheEpoch === epoch) { + if (balance > 0n) { + this.cachedBalance = balance; + this.cachedAt = Date.now(); + } else { + this.cachedBalance = null; + this.cachedAt = 0; + } + } + return balance; + }) + .finally(() => { + if (this.inflightFetch === pending) { + this.inflightFetch = null; + } + }); + this.inflightFetch = pending; } + const balance = await pending; return this.buildInfo(balance); } @@ -193,8 +216,10 @@ export class BalanceMonitor { * Call this after a payment failure to get accurate balance. */ invalidate(): void { + this.cacheEpoch++; this.cachedBalance = null; this.cachedAt = 0; + this.inflightFetch = null; } /** diff --git a/src/solana-balance.test.ts b/src/solana-balance.test.ts new file mode 100644 index 00000000..66199c90 --- /dev/null +++ b/src/solana-balance.test.ts @@ -0,0 +1,90 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const getTokenAccountsByOwnerMock = vi.fn(); + +vi.mock("@solana/kit", () => ({ + address: (value: string) => value, + createSolanaRpc: () => ({ + getTokenAccountsByOwner: getTokenAccountsByOwnerMock, + }), +})); + +import { SolanaBalanceMonitor } from "./solana-balance.js"; + +const WALLET = "11111111111111111111111111111111"; + +function tokenAccountResponse(amount: string) { + return { + value: [ + { + account: { + data: { + parsed: { + info: { + tokenAmount: { amount }, + }, + }, + }, + }, + }, + ], + }; +} + +describe("SolanaBalanceMonitor singleflight and invalidation", () => { + beforeEach(() => { + getTokenAccountsByOwnerMock.mockReset(); + }); + + it("coalesces concurrent checkBalance calls into a single RPC read", async () => { + let resolveSend!: (val: unknown) => void; + getTokenAccountsByOwnerMock.mockImplementation(() => ({ + send: () => + new Promise((resolve) => { + resolveSend = resolve; + }), + })); + + const monitor = new SolanaBalanceMonitor(WALLET, "https://rpc.example"); + const p1 = monitor.checkBalance(); + const p2 = monitor.checkBalance(); + const p3 = monitor.checkSufficient(500_000n); + + expect(getTokenAccountsByOwnerMock).toHaveBeenCalledTimes(1); + resolveSend(tokenAccountResponse("3000000")); + + const [r1, r2, r3] = await Promise.all([p1, p2, p3]); + expect(r1.balance).toBe(3_000_000n); + expect(r2.balance).toBe(3_000_000n); + expect(r3.sufficient).toBe(true); + expect(getTokenAccountsByOwnerMock).toHaveBeenCalledTimes(1); + }); + + it("does not let a pre-invalidation in-flight read overwrite newer cache state", async () => { + const resolvers: Array<(val: unknown) => void> = []; + getTokenAccountsByOwnerMock.mockImplementation(() => ({ + send: () => + new Promise((resolve) => { + resolvers.push(resolve); + }), + })); + + const monitor = new SolanaBalanceMonitor(WALLET, "https://rpc.example"); + const staleCall = monitor.checkBalance(); + expect(getTokenAccountsByOwnerMock).toHaveBeenCalledTimes(1); + + monitor.invalidate(); + const freshCall = monitor.checkBalance(); + expect(getTokenAccountsByOwnerMock).toHaveBeenCalledTimes(2); + + resolvers[1]!(tokenAccountResponse("500000")); + expect((await freshCall).balance).toBe(500_000n); + + resolvers[0]!(tokenAccountResponse("8000000")); + await staleCall; + + const cached = await monitor.checkBalance(); + expect(cached.balance).toBe(500_000n); + expect(getTokenAccountsByOwnerMock).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/solana-balance.ts b/src/solana-balance.ts index 6a9e603e..07ea05a6 100644 --- a/src/solana-balance.ts +++ b/src/solana-balance.ts @@ -32,6 +32,8 @@ export class SolanaBalanceMonitor { private readonly walletAddress: string; private cachedBalance: bigint | null = null; private cachedAt = 0; + private inflightFetch: Promise | null = null; + private cacheEpoch = 0; constructor(walletAddress: string, rpcUrl?: string) { this.walletAddress = walletAddress; @@ -48,13 +50,34 @@ export class SolanaBalanceMonitor { ) { return this.buildInfo(this.cachedBalance); } - // Zero balance is never cached — always re-fetch so a funded wallet is + // Zero balance is never cached: always re-fetch so a funded wallet is // detected on the next request without waiting for cache expiry. - const balance = await this.fetchBalance(); - if (balance > 0n) { - this.cachedBalance = balance; - this.cachedAt = now; + // Coalesce concurrent callers into one in-flight RPC read. + let pending = this.inflightFetch; + if (!pending) { + const epoch = this.cacheEpoch; + pending = this.fetchBalance() + .then((balance) => { + if (this.cacheEpoch === epoch) { + if (balance > 0n) { + this.cachedBalance = balance; + this.cachedAt = Date.now(); + } else { + this.cachedBalance = null; + this.cachedAt = 0; + } + } + return balance; + }) + .finally(() => { + if (this.inflightFetch === pending) { + this.inflightFetch = null; + } + }); + this.inflightFetch = pending; } + + const balance = await pending; return this.buildInfo(balance); } @@ -65,8 +88,10 @@ export class SolanaBalanceMonitor { } invalidate(): void { + this.cacheEpoch++; this.cachedBalance = null; this.cachedAt = 0; + this.inflightFetch = null; } async refresh(): Promise {