Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions src/balance.arc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Response>((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<Response>((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);
});
});
35 changes: 30 additions & 5 deletions src/balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<bigint> | 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}`;
Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -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;
}

/**
Expand Down
90 changes: 90 additions & 0 deletions src/solana-balance.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
35 changes: 30 additions & 5 deletions src/solana-balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export class SolanaBalanceMonitor {
private readonly walletAddress: string;
private cachedBalance: bigint | null = null;
private cachedAt = 0;
private inflightFetch: Promise<bigint> | null = null;
private cacheEpoch = 0;

constructor(walletAddress: string, rpcUrl?: string) {
this.walletAddress = walletAddress;
Expand All @@ -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);
}

Expand All @@ -65,8 +88,10 @@ export class SolanaBalanceMonitor {
}

invalidate(): void {
this.cacheEpoch++;
this.cachedBalance = null;
this.cachedAt = 0;
this.inflightFetch = null;
}

async refresh(): Promise<SolanaBalanceInfo> {
Expand Down
Loading