From 0f74f3a461660b5a4d28d191272e14d89372a0f2 Mon Sep 17 00:00:00 2001
From: MFrancis-dev
Date: Sat, 21 Nov 2026 17:12:27 +0100
Subject: [PATCH 1/7] fix(frontend): associate the dashboard settings template
input with a label (#632)
The settings-tab "Create Stream" panel named its only control with `aria-label`,
so there was no label element to anchor and no id for tests to target. Give the
input an id plus an sr-only sibling label so the accessible name comes from a
real association, with no layout change.
The issue cites `dashboard-view.tsx:879` and recipient/token/amount at 922-934.
That wizard moved and already pairs htmlFor with ids; the template-name input is
the gap that remains in this form.
---
.../dashboard/DashboardSettings.test.tsx | 61 +++++++++++++++++++
.../dashboard/DashboardSettings.tsx | 5 +-
2 files changed, 65 insertions(+), 1 deletion(-)
create mode 100644 frontend/src/components/dashboard/DashboardSettings.test.tsx
diff --git a/frontend/src/components/dashboard/DashboardSettings.test.tsx b/frontend/src/components/dashboard/DashboardSettings.test.tsx
new file mode 100644
index 00000000..91246949
--- /dev/null
+++ b/frontend/src/components/dashboard/DashboardSettings.test.tsx
@@ -0,0 +1,61 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { DashboardSettings } from "./DashboardSettings";
+import type { WalletSession } from "@/lib/wallet";
+
+const session: WalletSession = {
+ walletId: "freighter",
+ walletName: "Freighter",
+ publicKey: "GABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABC",
+ connectedAt: "2026-11-21T00:00:00.000Z",
+ network: "testnet",
+ mocked: false,
+};
+
+function renderSettings() {
+ return render( );
+}
+
+describe("DashboardSettings form labeling (#632)", () => {
+ it("associates the template name input with a label via id + htmlFor", () => {
+ const { container } = renderSettings();
+
+ const input = screen.getByLabelText("Template name");
+ expect(input).toBeInTheDocument();
+ expect(input.tagName).toBe("INPUT");
+ expect(input).toHaveAttribute("id", "stream-template-name");
+
+ const label = container.querySelector(
+ 'label[for="stream-template-name"]',
+ );
+ expect(label).not.toBeNull();
+ expect(label?.textContent?.trim()).toBe("Template name");
+ });
+
+ it("keeps the label visually hidden so the layout is unchanged", () => {
+ const { container } = renderSettings();
+
+ const label = container.querySelector('label[for="stream-template-name"]');
+ expect(label?.getAttribute("class")).toContain("sr-only");
+ });
+
+ it("gives every form control an id and a programmatic label", () => {
+ const { container } = renderSettings();
+
+ const controls = container.querySelectorAll(
+ "input, textarea, select",
+ );
+ expect(controls.length).toBeGreaterThan(0);
+
+ for (const control of controls) {
+ expect(control.id, `${control.tagName} is missing an id`).not.toBe("");
+ expect(
+ container.querySelector(`label[for="${CSS.escape(control.id)}"]`),
+ `${control.id} has no label targeting it`,
+ ).not.toBeNull();
+ }
+
+ // Each control must resolve through its accessible name, not just markup.
+ expect(screen.getAllByLabelText("Template name")).toHaveLength(1);
+ });
+});
diff --git a/frontend/src/components/dashboard/DashboardSettings.tsx b/frontend/src/components/dashboard/DashboardSettings.tsx
index fcf8adf3..bd74f37a 100644
--- a/frontend/src/components/dashboard/DashboardSettings.tsx
+++ b/frontend/src/components/dashboard/DashboardSettings.tsx
@@ -22,9 +22,12 @@ export function DashboardSettings({ session, onDisconnect }: DashboardSettingsPr
+
+ Template name
+
From 9ac94e474c55a8aaec32d21b988c7a1fe3ce48de Mon Sep 17 00:00:00 2001
From: MFrancis-dev
Date: Sat, 21 Nov 2026 17:14:17 +0100
Subject: [PATCH 2/7] feat(frontend): add useAsyncPageData and use it on
activity and incoming (#1085)
Page shells duplicated a chain of ad-hoc booleans (hydrated? connected?
loading? error? empty?) and each page ordered them slightly differently,
so a finished-but-errored query could render the empty state. One hook
derives the five mutually exclusive states in a documented priority order
and the two pages that had drifted now consume it.
---
.../src/app/activity/activity-content.tsx | 15 +-
.../__tests__/incoming-content.test.tsx | 145 ++++++++++++++++++
.../src/app/incoming/incoming-content.tsx | 28 ++--
frontend/src/hooks/useAsyncPageData.test.tsx | 129 ++++++++++++++++
frontend/src/hooks/useAsyncPageData.ts | 65 ++++++++
5 files changed, 367 insertions(+), 15 deletions(-)
create mode 100644 frontend/src/app/incoming/__tests__/incoming-content.test.tsx
create mode 100644 frontend/src/hooks/useAsyncPageData.test.tsx
create mode 100644 frontend/src/hooks/useAsyncPageData.ts
diff --git a/frontend/src/app/activity/activity-content.tsx b/frontend/src/app/activity/activity-content.tsx
index be228794..ce549f01 100644
--- a/frontend/src/app/activity/activity-content.tsx
+++ b/frontend/src/app/activity/activity-content.tsx
@@ -9,6 +9,7 @@ import { Loader2, Download } from "lucide-react";
import { formatAmount } from "@/utils/amount";
import { downloadCSV } from "@/utils/csvExport";
import { getApiBaseUrl } from "@/lib/api/_shared";
+import { useAsyncPageData } from "@/hooks/useAsyncPageData";
import { logger } from "@/lib/logger";
const PAGE_SIZE = 10;
@@ -91,6 +92,14 @@ export default function ActivityContent() {
fetchActivity(nextPage, activeTab, true);
};
+ const view = useAsyncPageData({
+ enabled: status === "connected",
+ isLoading: loading,
+ isError: error !== null,
+ isEmpty: events.length === 0,
+ error,
+ });
+
const handleExportCSV = () => {
const csvData = events.map(event => ({
'Stream ID': event.streamId,
@@ -103,7 +112,7 @@ export default function ActivityContent() {
downloadCSV(csvData, `flowfi-activity-${Date.now()}.csv`);
};
- if (status !== "connected") {
+ if (!view.isEnabled) {
return (
Access Denied
@@ -157,9 +166,9 @@ export default function ActivityContent() {
- {error && (
+ {view.isError && (
-
{error}
+
{view.error}
{
diff --git a/frontend/src/app/incoming/__tests__/incoming-content.test.tsx b/frontend/src/app/incoming/__tests__/incoming-content.test.tsx
new file mode 100644
index 00000000..428d0886
--- /dev/null
+++ b/frontend/src/app/incoming/__tests__/incoming-content.test.tsx
@@ -0,0 +1,145 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { render, screen } from "@testing-library/react";
+import React from "react";
+
+// The incoming page now derives its loading / error / empty / ready branches
+// from `useAsyncPageData` (#1085). These tests pin the rendered result of each
+// branch so the shared hook cannot silently change what the page shows.
+
+const wallet = vi.hoisted(() => ({
+ current: {
+ session: { publicKey: "GAAAA", network: "testnet" } as Record | null,
+ status: "connected" as string,
+ isHydrated: true,
+ },
+}));
+
+vi.mock("@/context/wallet-context", () => ({
+ useWallet: () => wallet.current,
+}));
+
+vi.mock("@/components/TransactionTracker", () => ({
+ default: () => null,
+ useTransactionTracker: () => ({
+ status: "idle",
+ txHash: null,
+ error: null,
+ start: vi.fn(),
+ submit: vi.fn(),
+ confirm: vi.fn(),
+ fail: vi.fn(),
+ succeed: vi.fn(),
+ }),
+}));
+
+const query = vi.hoisted(() => ({
+ current: {
+ data: undefined as unknown,
+ isLoading: false,
+ isError: false,
+ error: null as unknown,
+ },
+}));
+
+vi.mock("@/hooks/useIncomingStreams", () => ({
+ useIncomingStreams: () => query.current,
+ useWithdrawIncomingStream: () => ({
+ isPending: false,
+ variables: undefined,
+ mutateAsync: vi.fn(),
+ }),
+}));
+
+vi.mock("@/components/streams/IncomingStreamCard", () => ({
+ IncomingStreamCard: ({ stream }: { stream: { id: string } }) => (
+ {stream.id}
+ ),
+}));
+
+import IncomingContent from "@/app/incoming/incoming-content";
+
+function setWallet(overrides: Partial = {}) {
+ wallet.current = { ...wallet.current, ...overrides };
+}
+
+beforeEach(() => {
+ setWallet({
+ session: { publicKey: "GAAAA", network: "testnet" },
+ status: "connected",
+ isHydrated: true,
+ });
+ query.current = { data: [], isLoading: false, isError: false, error: null };
+});
+
+describe("IncomingContent page states (#1085)", () => {
+ it("shows skeletons before hydration has resolved the wallet", () => {
+ setWallet({ isHydrated: false });
+ render( );
+
+ expect(screen.getByText(/Streams paying into your wallet/i)).toBeInTheDocument();
+ expect(screen.queryByText(/Connect a wallet to view incoming streams/i)).toBeNull();
+ expect(screen.queryByTestId("stream-card")).toBeNull();
+ });
+
+ it("asks for a wallet once hydrated but still disconnected", () => {
+ setWallet({ isHydrated: true, status: "disconnected", session: null });
+ render( );
+
+ expect(screen.getByText(/Connect a wallet to view incoming streams/i)).toBeInTheDocument();
+ });
+
+ it("renders the query error message when the fetch failed", () => {
+ query.current = {
+ data: undefined,
+ isLoading: false,
+ isError: true,
+ error: new Error("upstream exploded"),
+ };
+ render( );
+
+ expect(screen.getByText(/We couldn.t load your incoming streams/i)).toBeInTheDocument();
+ expect(screen.getByText("upstream exploded")).toBeInTheDocument();
+ });
+
+ it("prefers the error branch while a retry is already in flight", () => {
+ query.current = {
+ data: undefined,
+ isLoading: true,
+ isError: true,
+ error: new Error("upstream exploded"),
+ };
+ render( );
+
+ expect(screen.getByText(/We couldn.t load your incoming streams/i)).toBeInTheDocument();
+ });
+
+ it("falls back to a generic message when the error is not an Error", () => {
+ query.current = { data: undefined, isLoading: false, isError: true, error: "nope" };
+ render( );
+
+ expect(screen.getByText("Please try again in a moment.")).toBeInTheDocument();
+ });
+
+ it("shows the empty state once loaded with no streams", () => {
+ query.current = { data: [], isLoading: false, isError: false, error: null };
+ render( );
+
+ expect(screen.getByText(/No incoming streams yet/i)).toBeInTheDocument();
+ });
+
+ it("renders one card per stream when ready", () => {
+ query.current = {
+ data: [
+ { id: "s1", streamId: 1, withdrawn: 0 },
+ { id: "s2", streamId: 2, withdrawn: 0 },
+ ],
+ isLoading: false,
+ isError: false,
+ error: null,
+ };
+ render( );
+
+ expect(screen.getAllByTestId("stream-card")).toHaveLength(2);
+ expect(screen.queryByText(/No incoming streams yet/i)).toBeNull();
+ });
+});
diff --git a/frontend/src/app/incoming/incoming-content.tsx b/frontend/src/app/incoming/incoming-content.tsx
index e249209d..cbdbb908 100644
--- a/frontend/src/app/incoming/incoming-content.tsx
+++ b/frontend/src/app/incoming/incoming-content.tsx
@@ -16,6 +16,7 @@ import {
useIncomingStreams,
useWithdrawIncomingStream,
} from "@/hooks/useIncomingStreams";
+import { useAsyncPageData } from "@/hooks/useAsyncPageData";
function LoadingCard() {
return (
@@ -77,10 +78,17 @@ export default function IncomingContent() {
}
};
- const isLoading =
- !isHydrated ||
- (status === "connected" && incomingStreamsQuery.isLoading);
const streams = incomingStreamsQuery.data ?? [];
+ const view = useAsyncPageData({
+ enabled: isHydrated && status === "connected",
+ isLoading: incomingStreamsQuery.isLoading,
+ isError: incomingStreamsQuery.isError,
+ isEmpty: streams.length === 0,
+ error:
+ incomingStreamsQuery.error instanceof Error
+ ? incomingStreamsQuery.error.message
+ : "Please try again in a moment.",
+ });
return (
@@ -116,7 +124,7 @@ export default function IncomingContent() {
- ) : status !== "connected" ? (
+ ) : !view.isEnabled ? (
Connect a wallet to view incoming streams
@@ -126,24 +134,20 @@ export default function IncomingContent() {
where you are the recipient and keep the claimable balance fresh.
- ) : incomingStreamsQuery.isError ? (
+ ) : view.isError ? (
We couldn't load your incoming streams
-
- {incomingStreamsQuery.error instanceof Error
- ? incomingStreamsQuery.error.message
- : "Please try again in a moment."}
-
+ {view.error}
- ) : isLoading ? (
+ ) : view.isLoading ? (
- ) : streams.length === 0 ? (
+ ) : view.isEmpty ? (
No incoming streams yet
diff --git a/frontend/src/hooks/useAsyncPageData.test.tsx b/frontend/src/hooks/useAsyncPageData.test.tsx
new file mode 100644
index 00000000..ce378fa5
--- /dev/null
+++ b/frontend/src/hooks/useAsyncPageData.test.tsx
@@ -0,0 +1,129 @@
+import { describe, expect, it } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { useAsyncPageData, type AsyncPageDataInput } from "./useAsyncPageData";
+
+const base: AsyncPageDataInput = {
+ enabled: true,
+ isLoading: false,
+ isError: false,
+ isEmpty: false,
+ error: null,
+};
+
+/** The precedence the hook is supposed to implement, written independently. */
+function expectedState({
+ isLoading,
+ isError,
+ isEmpty,
+}: Pick) {
+ if (isError) return "error";
+ if (isLoading) return "loading";
+ if (isEmpty) return "empty";
+ return "ready";
+}
+
+function renderView(overrides: Partial = {}) {
+ return renderHook(() => useAsyncPageData({ ...base, ...overrides })).result
+ .current;
+}
+
+describe("useAsyncPageData", () => {
+ it("is awaiting while the page has no data source yet", () => {
+ const view = renderView({ enabled: false, isLoading: true, isError: true });
+
+ expect(view.state).toBe("awaiting");
+ expect(view.isEnabled).toBe(false);
+ expect(view.isError).toBe(false);
+ expect(view.isLoading).toBe(false);
+ expect(view.isReady).toBe(false);
+ });
+
+ it("resolves to ready once enabled with data present", () => {
+ const view = renderView();
+
+ expect(view.state).toBe("ready");
+ expect(view.isReady).toBe(true);
+ });
+
+ it("reports loading before there is any data", () => {
+ const view = renderView({ isLoading: true, isEmpty: true });
+
+ expect(view.state).toBe("loading");
+ expect(view.isLoading).toBe(true);
+ expect(view.isEmpty).toBe(false);
+ });
+
+ it("reports empty when the load finished with nothing to show", () => {
+ const view = renderView({ isEmpty: true });
+
+ expect(view.state).toBe("empty");
+ expect(view.isEmpty).toBe(true);
+ expect(view.isReady).toBe(false);
+ });
+
+ it("surfaces the error message", () => {
+ const view = renderView({ isError: true, error: "Failed to fetch activity. Please try again." });
+
+ expect(view.state).toBe("error");
+ expect(view.error).toBe("Failed to fetch activity. Please try again.");
+ });
+
+ it("defaults the message to null when no error is provided", () => {
+ const { error } = renderHook(() =>
+ useAsyncPageData({ enabled: true, isLoading: false, isError: false, isEmpty: false }),
+ ).result.current;
+
+ expect(error).toBeNull();
+ });
+
+ describe("precedence", () => {
+ it("keeps an error visible while a background refetch is loading", () => {
+ expect(renderView({ isError: true, isLoading: true, error: "boom" }).state).toBe("error");
+ });
+
+ it("prefers loading over empty while the first page is in flight", () => {
+ expect(renderView({ isLoading: true, isEmpty: true }).state).toBe("loading");
+ });
+
+ it("prefers empty over ready", () => {
+ expect(renderView({ isEmpty: true }).state).toBe("empty");
+ });
+
+ it("yields exactly one active state for every combination of inputs", () => {
+ for (const enabled of [true, false]) {
+ for (const isLoading of [true, false]) {
+ for (const isError of [true, false]) {
+ for (const isEmpty of [true, false]) {
+ const view = renderView({ enabled, isLoading, isError, isEmpty });
+ const label = JSON.stringify({ enabled, isLoading, isError, isEmpty });
+ const active = [
+ !view.isEnabled,
+ view.isError,
+ view.isLoading,
+ view.isEmpty,
+ view.isReady,
+ ].filter(Boolean);
+
+ expect(active, label).toHaveLength(1);
+ expect(view.state, label).toBe(enabled ? expectedState({ isLoading, isError, isEmpty }) : "awaiting");
+ }
+ }
+ }
+ }
+ });
+ });
+
+ it("recomputes the state when the inputs change", () => {
+ const view = renderHook(
+ ({ isLoading, isEmpty }: { isLoading: boolean; isEmpty: boolean }) =>
+ useAsyncPageData({ ...base, isLoading, isEmpty }),
+ { initialProps: { isLoading: true, isEmpty: true } },
+ );
+
+ expect(view.result.current.state).toBe("loading");
+ view.rerender({ isLoading: false, isEmpty: true });
+ expect(view.result.current.state).toBe("empty");
+ view.rerender({ isLoading: false, isEmpty: false });
+ expect(view.result.current.state).toBe("ready");
+ });
+});
diff --git a/frontend/src/hooks/useAsyncPageData.ts b/frontend/src/hooks/useAsyncPageData.ts
new file mode 100644
index 00000000..cccf4919
--- /dev/null
+++ b/frontend/src/hooks/useAsyncPageData.ts
@@ -0,0 +1,65 @@
+"use client";
+
+import { useMemo } from "react";
+
+/**
+ * The state a page-level data view can be in, in priority order.
+ *
+ * `awaiting` means the page has no data source yet (wallet not connected, or
+ * hydration still pending) and should render whatever "not mine yet" looks like
+ * for that page. The remaining four are mutually exclusive and resolved by
+ * `useAsyncPageData`.
+ */
+export type AsyncPageState = "awaiting" | "error" | "loading" | "empty" | "ready";
+
+export interface AsyncPageDataInput {
+ /** False until the page has something to load (connected / hydrated). */
+ enabled: boolean;
+ isLoading: boolean;
+ isError: boolean;
+ isEmpty: boolean;
+ /** Message to surface in the error state; `null` when there is none. */
+ error?: string | null;
+}
+
+export interface AsyncPageData {
+ state: AsyncPageState;
+ isEnabled: boolean;
+ isError: boolean;
+ isLoading: boolean;
+ isEmpty: boolean;
+ isReady: boolean;
+ error: string | null;
+}
+
+/**
+ * Single source of truth for the loading / error / empty / ready scaffolding
+ * that every page-level data view repeats.
+ *
+ * The precedence — error before loading before empty before ready — lives here
+ * so an edge-case fix (a refetch in flight must not hide a failure, say) lands
+ * once instead of per page. Pages keep their own markup and their own fetching
+ * library; this only decides which branch is showing.
+ */
+export function useAsyncPageData(input: AsyncPageDataInput): AsyncPageData {
+ const { enabled, isLoading, isError, isEmpty, error = null } = input;
+
+ return useMemo(() => {
+ let state: AsyncPageState;
+ if (!enabled) state = "awaiting";
+ else if (isError) state = "error";
+ else if (isLoading) state = "loading";
+ else if (isEmpty) state = "empty";
+ else state = "ready";
+
+ return {
+ state,
+ isEnabled: enabled,
+ isError: state === "error",
+ isLoading: state === "loading",
+ isEmpty: state === "empty",
+ isReady: state === "ready",
+ error,
+ };
+ }, [enabled, isError, isLoading, isEmpty, error]);
+}
From 0e703f9936631152b23a9334fe5dc8eb0de2f4a5 Mon Sep 17 00:00:00 2001
From: MFrancis-dev
Date: Sat, 21 Nov 2026 17:14:27 +0100
Subject: [PATCH 3/7] test(backend): cover stream_topped_up rate math, dedup
and payload guards (#1761)
The top-up handler recomputes the deposit, the derived end time and the
pause-adjusted duration in one expression, and nothing tested the
arithmetic: a regression in the divisor, the pause term or the i128
decode would have silently extended or shortened live streams. These
tests drive processEvent, so they also pin the dedup guard, the
missing-field rejections, the transaction rollback and the exact SSE
payload.
---
backend/tests/stream-topped-up-rate.test.ts | 516 ++++++++++++++++++++
1 file changed, 516 insertions(+)
create mode 100644 backend/tests/stream-topped-up-rate.test.ts
diff --git a/backend/tests/stream-topped-up-rate.test.ts b/backend/tests/stream-topped-up-rate.test.ts
new file mode 100644
index 00000000..d1a03843
--- /dev/null
+++ b/backend/tests/stream-topped-up-rate.test.ts
@@ -0,0 +1,516 @@
+/**
+ * Issue #1761 — top-up rate accounting in the Soroban event worker.
+ *
+ * These are characterization tests for `handleStreamToppedUp`, reached through
+ * the public `processEvent` dispatch. They pin the documented success path
+ * (derived `endTime`, stored-rate semantics, i128 precision), the failure
+ * contract (`missing body fields`), dependency failures (missing `Stream` row)
+ * and replay behaviour (event-row dedup keyed on `transactionHash`+`eventType`).
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { rpc } from '@stellar/stellar-sdk';
+
+// ─── In-memory fake of the tables the top-up path touches ────────────────────
+interface FakeStream {
+ streamId: bigint;
+ ratePerSecond: string;
+ depositedAmount: string;
+ withdrawnAmount: string;
+ startTime: bigint;
+ endTime: bigint | null;
+ lastUpdateTime: bigint;
+ isActive: boolean;
+ totalPausedDuration: number;
+}
+
+interface FakeStreamEvent {
+ id: number;
+ streamId: bigint;
+ eventType: string;
+ amount: string;
+ transactionHash: string;
+ ledgerSequence: number;
+ timestamp: number;
+ metadata: string;
+}
+
+const fake = vi.hoisted(() => {
+ const streams = new Map>();
+ const events = new Map>();
+ const rowKey = (hash: string, type: string) => `${hash}|${type}`;
+ let nextEventId = 1;
+
+ const notFound = () => {
+ const error = new Error('An operation failed because it depends on one or more records that were required but not found.');
+ (error as Error & { code?: string }).code = 'P2025';
+ return error;
+ };
+
+ const tx = {
+ stream: {
+ findUniqueOrThrow: vi.fn(async (args: { where: { streamId: bigint } }) => {
+ const row = streams.get(BigInt(args.where.streamId));
+ if (!row) throw notFound();
+ return { ...row };
+ }),
+ update: vi.fn(async (args: { where: { streamId: bigint }; data: Record }) => {
+ const row = streams.get(BigInt(args.where.streamId));
+ if (!row) throw notFound();
+ Object.assign(row, args.data);
+ return row;
+ }),
+ },
+ streamEvent: {
+ findUnique: vi.fn(
+ async (args: { where: { transactionHash_eventType: { transactionHash: string; eventType: string } } }) => {
+ const { transactionHash, eventType } = args.where.transactionHash_eventType;
+ const row = events.get(rowKey(transactionHash, eventType));
+ return row ? { id: row.id } : null;
+ },
+ ),
+ upsert: vi.fn(
+ async (args: {
+ where: { transactionHash_eventType: { transactionHash: string; eventType: string } };
+ create: Record;
+ update: Record;
+ }) => {
+ const { transactionHash, eventType } = args.where.transactionHash_eventType;
+ const key = rowKey(transactionHash, eventType);
+ const existing = events.get(key);
+ if (existing) {
+ Object.assign(existing, args.update);
+ return existing;
+ }
+ const created = { id: nextEventId++, ...args.create };
+ events.set(key, created);
+ return created;
+ },
+ ),
+ },
+ };
+
+ return {
+ streams,
+ events,
+ tx,
+ // Same call shape as `prisma.$transaction`, including rollback of the
+ // in-memory rows so a mid-transaction throw cannot leave a partial write.
+ $transaction: vi.fn(async (cb: (client: typeof tx) => Promise) => {
+ const streamBackup = new Map([...streams].map(([id, row]) => [id, { ...row }]));
+ const eventBackup = new Map([...events].map(([key, row]) => [key, { ...row }]));
+ const restore = () => {
+ streams.clear();
+ events.clear();
+ for (const [id, row] of streamBackup) streams.set(id, row);
+ for (const [key, row] of eventBackup) events.set(key, row);
+ };
+ try {
+ return await cb(tx);
+ } catch (error) {
+ restore();
+ throw error;
+ }
+ }),
+ stream(id: bigint, overrides: Partial = {}): FakeStream {
+ const row: FakeStream = {
+ streamId: id,
+ ratePerSecond: '10',
+ depositedAmount: '1000',
+ withdrawnAmount: '0',
+ startTime: 1700000000n,
+ endTime: 1700000100n,
+ lastUpdateTime: 1700000000n,
+ isActive: true,
+ totalPausedDuration: 0,
+ ...overrides,
+ };
+ streams.set(id, row as unknown as Record);
+ return row;
+ },
+ reset() {
+ streams.clear();
+ events.clear();
+ nextEventId = 1;
+ vi.clearAllMocks();
+ },
+ };
+});
+
+vi.mock('../src/lib/prisma.js', () => ({
+ default: { $transaction: fake.$transaction },
+ prisma: { $transaction: fake.$transaction },
+}));
+
+vi.mock('../src/services/sse.service.js', () => ({
+ sseService: {
+ broadcastToStream: vi.fn(),
+ broadcast: vi.fn(),
+ broadcastToAdmin: vi.fn(),
+ },
+}));
+
+vi.mock('../src/services/sentinel.service.js', () => ({
+ sentinelService: {
+ recordWithdrawal: vi.fn(),
+ recordStreamCreation: vi.fn(),
+ },
+}));
+
+vi.mock('../src/logger.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+ };
+});
+
+import { SorobanEventWorker } from '../src/workers/soroban-event-worker.js';
+import { sseService } from '../src/services/sse.service.js';
+import logger from '../src/logger.js';
+
+// ─── ScVal fixtures (property-shaped, matching the on-chain XDR surface) ─────
+const sym = (name: string) => ({ sym: { toString: () => name } });
+const u64 = (value: number | bigint | string) => ({ u64: { toString: () => String(value) } });
+const i128 = (hi: number | bigint | string, lo: number | bigint | string) => ({
+ i128: { hi: { toString: () => String(hi) }, lo: { toString: () => String(lo) } },
+});
+const accountAddress = (bytes = Buffer.alloc(32, 7)) => ({
+ address: { type: 'scAddressTypeAccount', accountId: { ed25519: { value: bytes } } },
+});
+const entry = (key: string, val: unknown) => ({ key: sym(key), val });
+const mapOf = (entries: unknown[]) => ({ map: entries });
+
+const START = 1700000000n;
+
+interface TopUpBody {
+ amount?: [number | string, number | string];
+ newDeposited?: [number | string, number | string];
+ newEndTime?: number | string;
+ sender?: unknown;
+}
+
+/** `stream_topped_up` payload as the contract emits it (`StreamToppedUpEvent`). */
+function topUpEvent(opts: { streamId?: number; txHash?: string; ledger?: number; body?: TopUpBody }) {
+ const body: TopUpBody = opts.body ?? {};
+ const entries: unknown[] = [entry('sender', body.sender ?? accountAddress())];
+ if (body.amount) entries.push(entry('amount', i128(body.amount[0], body.amount[1])));
+ if (body.newDeposited) entries.push(entry('new_deposited_amount', i128(body.newDeposited[0], body.newDeposited[1])));
+ if (body.newEndTime !== undefined) entries.push(entry('new_end_time', u64(body.newEndTime)));
+
+ return {
+ id: `${opts.txHash ?? 'tx-topup'}-0`,
+ type: 'contract',
+ ledger: opts.ledger ?? 1234,
+ ledgerClosedAt: '1700000500',
+ txHash: opts.txHash ?? 'tx-topup',
+ transactionIndex: 0,
+ operationIndex: 0,
+ inSuccessfulContractCall: true,
+ topic: [sym('stream_topped_up'), u64(opts.streamId ?? 42)],
+ value: mapOf(entries),
+ } as unknown as rpc.Api.EventResponse;
+}
+
+const defaultBody: TopUpBody = { amount: [0, 1100], newDeposited: [0, 2100], newEndTime: 1800000000 };
+
+function toppedUpRow(streamId = 42n) {
+ return fake.streams.get(streamId);
+}
+function eventRows() {
+ return [...fake.events.values()] as unknown as FakeStreamEvent[];
+}
+function broadcastCalls() {
+ return (sseService.broadcastToStream as ReturnType).mock.calls;
+}
+
+describe('SorobanEventWorker — stream_topped_up rate accounting (#1761)', () => {
+ let worker: SorobanEventWorker;
+
+ beforeEach(() => {
+ fake.reset();
+ vi.useFakeTimers();
+ vi.setSystemTime(Date.UTC(2025, 0, 1, 0, 0, 0));
+ worker = new SorobanEventWorker();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ describe('documented success path', () => {
+ it('derives endTime from startTime + deposited/rate and stores the new deposit', async () => {
+ fake.stream(42n);
+
+ await worker.processEvent(topUpEvent({ body: defaultBody }));
+
+ // 1700000000 + 2100/10 + 0 paused
+ expect(toppedUpRow()).toMatchObject({
+ depositedAmount: '2100',
+ endTime: START + 210n,
+ });
+ });
+
+ it('writes exactly one TOPPED_UP StreamEvent keyed on txHash + eventType', async () => {
+ fake.stream(42n);
+
+ await worker.processEvent(topUpEvent({ txHash: '0xabc', ledger: 555, body: defaultBody }));
+
+ const [event] = eventRows();
+ expect(eventRows()).toHaveLength(1);
+ expect(event).toMatchObject({
+ streamId: 42n,
+ eventType: 'TOPPED_UP',
+ amount: '1100',
+ transactionHash: '0xabc',
+ ledgerSequence: 555,
+ });
+ expect(JSON.parse(event.metadata)).toEqual({ newDepositedAmount: '2100' });
+ });
+
+ it('adds totalPausedDuration back onto the derived endTime', async () => {
+ fake.stream(42n, { totalPausedDuration: 120 });
+
+ await worker.processEvent(topUpEvent({ body: defaultBody }));
+
+ expect(toppedUpRow()?.endTime).toBe(START + 210n + 120n);
+ });
+
+ it('broadcasts stream.topped_up with the decoded i128 strings', async () => {
+ fake.stream(42n);
+
+ await worker.processEvent(topUpEvent({ txHash: '0xabc', ledger: 555, body: defaultBody }));
+
+ expect(broadcastCalls()).toEqual([
+ [
+ '42',
+ 'stream.topped_up',
+ {
+ streamId: 42n,
+ amount: '1100',
+ newDepositedAmount: '2100',
+ transactionHash: '0xabc',
+ ledger: 555,
+ timestamp: 1735689600,
+ },
+ ],
+ ]);
+ });
+ });
+
+ describe('rate boundary inputs', () => {
+ it('stores a null endTime when the stored rate is zero', async () => {
+ fake.stream(42n, { ratePerSecond: '0' });
+
+ await worker.processEvent(topUpEvent({ body: defaultBody }));
+
+ expect(toppedUpRow()).toMatchObject({ endTime: null, depositedAmount: '2100' });
+ });
+
+ it('truncates fractional runway toward zero', async () => {
+ // 10 / 3 = 3 seconds of runway, not 3.333 and not 4.
+ fake.stream(42n, { ratePerSecond: '3' });
+
+ await worker.processEvent(topUpEvent({ body: { amount: [0, 1], newDeposited: [0, 10] } }));
+
+ expect(toppedUpRow()?.endTime).toBe(START + 3n);
+ });
+
+ it('keeps full integer precision above Number.MAX_SAFE_INTEGER', async () => {
+ const beyondSafe = 9007199254740993n; // 2^53 + 1
+ fake.stream(42n, { ratePerSecond: '1' });
+
+ await worker.processEvent(
+ topUpEvent({ body: { amount: [0, beyondSafe.toString()], newDeposited: [0, beyondSafe.toString()] } }),
+ );
+
+ expect(toppedUpRow()?.endTime).toBe(START + beyondSafe);
+ expect(toppedUpRow()?.depositedAmount).toBe(beyondSafe.toString());
+ });
+
+ it('decodes an i128 amount that spans both 64-bit halves', async () => {
+ fake.stream(42n);
+
+ await worker.processEvent(
+ topUpEvent({ body: { amount: [1, 0], newDeposited: [1, 0] } }),
+ );
+
+ expect(eventRows()[0].amount).toBe('18446744073709551616');
+ expect(toppedUpRow()?.depositedAmount).toBe('18446744073709551616');
+ });
+
+ it('accepts a zero-amount top-up and still refreshes the deposit', async () => {
+ fake.stream(42n);
+
+ await worker.processEvent(topUpEvent({ body: { amount: [0, 0], newDeposited: [0, 2100] } }));
+
+ expect(toppedUpRow()).toMatchObject({ depositedAmount: '2100', endTime: START + 210n });
+ expect(eventRows()[0].amount).toBe('0');
+ });
+
+ it('never rewrites ratePerSecond — the stored rate is the only input', async () => {
+ fake.stream(42n, { ratePerSecond: '10' });
+
+ await worker.processEvent(topUpEvent({ body: defaultBody }));
+
+ const updateCall = (fake.tx.stream.update as ReturnType).mock.calls[0][0] as {
+ data: Record;
+ };
+ expect(Object.keys(updateCall.data).sort()).toEqual(['depositedAmount', 'endTime', 'lastUpdateTime']);
+ expect(toppedUpRow()?.ratePerSecond).toBe('10');
+ });
+
+ it('ignores the chain-authoritative new_end_time in favour of the derived value', async () => {
+ // The contract ships `new_end_time` on this very event; the worker's
+ // derivation wins, so a stale stored rate silently propagates here.
+ fake.stream(42n, { ratePerSecond: '10' });
+
+ await worker.processEvent(topUpEvent({ body: { ...defaultBody, newEndTime: 1800000000 } }));
+
+ expect(toppedUpRow()?.endTime).toBe(START + 210n);
+ expect(toppedUpRow()?.endTime).not.toBe(1800000000n);
+ });
+
+ it('leaves the rate untouched when the contract emits stream_rate_modified', async () => {
+ const row = fake.stream(42n, { ratePerSecond: '10' });
+
+ await worker.processEvent({
+ id: 'rate-1',
+ ledger: 1235,
+ ledgerClosedAt: '1700000600',
+ txHash: 'tx-rate',
+ topic: [sym('stream_rate_modified'), u64(42)],
+ value: mapOf([entry('new_rate_per_second', i128(0, 99)), entry('new_end_time', u64(1900000000))]),
+ } as unknown as rpc.Api.EventResponse);
+
+ expect(row.ratePerSecond).toBe('10');
+ expect(fake.$transaction).not.toHaveBeenCalled();
+ expect(broadcastCalls()).toHaveLength(0);
+ });
+ });
+
+ describe('failure contract', () => {
+ it('rejects when amount is absent from the event body', async () => {
+ fake.stream(42n);
+
+ await expect(
+ worker.processEvent(topUpEvent({ body: { newDeposited: [0, 2100] } })),
+ ).rejects.toThrow('StreamToppedUp #42: missing body fields');
+
+ expect(fake.tx.stream.update).not.toHaveBeenCalled();
+ expect(eventRows()).toHaveLength(0);
+ expect(broadcastCalls()).toHaveLength(0);
+ });
+
+ it('rejects when new_deposited_amount is absent from the event body', async () => {
+ fake.stream(42n);
+
+ await expect(
+ worker.processEvent(topUpEvent({ body: { amount: [0, 1100] } })),
+ ).rejects.toThrow('StreamToppedUp #42: missing body fields');
+
+ expect(fake.tx.stream.update).not.toHaveBeenCalled();
+ });
+
+ it('propagates P2025 and writes nothing when the Stream row is missing', async () => {
+ await expect(worker.processEvent(topUpEvent({ body: defaultBody }))).rejects.toMatchObject({
+ code: 'P2025',
+ });
+
+ expect(fake.tx.stream.update).not.toHaveBeenCalled();
+ expect(eventRows()).toHaveLength(0);
+ expect(broadcastCalls()).toHaveLength(0);
+ });
+
+ it('propagates a transaction failure raised by the event-row write', async () => {
+ fake.stream(42n);
+ (fake.tx.streamEvent.upsert as ReturnType).mockRejectedValueOnce(
+ new Error('connection terminated'),
+ );
+
+ await expect(worker.processEvent(topUpEvent({ body: defaultBody }))).rejects.toThrow(
+ 'connection terminated',
+ );
+
+ // The fake rolls back like `prisma.$transaction`, so the deposit is intact.
+ expect(toppedUpRow()?.depositedAmount).toBe('1000');
+ expect(broadcastCalls()).toHaveLength(0);
+ });
+
+ it('ignores a top-up event that carries no stream id topic', async () => {
+ fake.stream(42n);
+
+ await worker.processEvent({
+ id: 'truncated',
+ ledger: 1236,
+ ledgerClosedAt: '1700000700',
+ txHash: 'tx-truncated',
+ topic: [sym('stream_topped_up')],
+ value: mapOf([entry('amount', i128(0, 1)), entry('new_deposited_amount', i128(0, 2))]),
+ } as unknown as rpc.Api.EventResponse);
+
+ expect(fake.$transaction).not.toHaveBeenCalled();
+ expect(broadcastCalls()).toHaveLength(0);
+ });
+ });
+
+ describe('replay idempotency', () => {
+ it('skips the second delivery of the same txHash without re-applying the top-up', async () => {
+ fake.stream(42n);
+ const event = topUpEvent({ txHash: '0xdead', body: defaultBody });
+
+ await worker.processEvent(event);
+ await worker.processEvent(event);
+
+ expect(eventRows()).toHaveLength(1);
+ expect(toppedUpRow()).toMatchObject({ depositedAmount: '2100', endTime: START + 210n });
+ expect(fake.tx.stream.update).toHaveBeenCalledTimes(1);
+ expect(logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining('Duplicate StreamEvent skipped: txHash=0xdead type=TOPPED_UP'),
+ );
+ });
+
+ it('re-broadcasts SSE for a replayed event even though the write is skipped', async () => {
+ fake.stream(42n);
+ const event = topUpEvent({ txHash: '0xdead', body: defaultBody });
+
+ await worker.processEvent(event);
+ await worker.processEvent(event);
+
+ expect(broadcastCalls()).toHaveLength(2);
+ });
+
+ it('treats the same stream id in a different transaction as a fresh top-up', async () => {
+ fake.stream(42n);
+
+ await worker.processEvent(topUpEvent({ txHash: '0x1', body: { amount: [0, 100], newDeposited: [0, 1100] } }));
+ await worker.processEvent(topUpEvent({ txHash: '0x2', body: { amount: [0, 1000], newDeposited: [0, 2100] } }));
+
+ expect(eventRows()).toHaveLength(2);
+ expect(toppedUpRow()?.endTime).toBe(START + 210n);
+ });
+ });
+
+ describe('timestamp semantics', () => {
+ it('stamps lastUpdateTime with processing time, not the ledger close time', async () => {
+ // The event's ledgerClosedAt decodes to 1700000500; this handler is the
+ // only one of the family that ignores it.
+ fake.stream(42n);
+
+ await worker.processEvent(topUpEvent({ body: defaultBody }));
+
+ expect(toppedUpRow()?.lastUpdateTime).toBe(1735689600);
+ expect(eventRows()[0].timestamp).toBe(1735689600);
+ });
+
+ it('advances the stamp when a later top-up is processed in a later wall-clock second', async () => {
+ fake.stream(42n);
+
+ await worker.processEvent(topUpEvent({ txHash: '0x1', body: { amount: [0, 1], newDeposited: [0, 1001] } }));
+ vi.setSystemTime(Date.UTC(2025, 0, 1, 0, 1, 0));
+ await worker.processEvent(topUpEvent({ txHash: '0x2', body: { amount: [0, 1], newDeposited: [0, 1002] } }));
+
+ expect(toppedUpRow()?.lastUpdateTime).toBe(1735689660);
+ expect(eventRows().map((row) => row.timestamp)).toEqual([1735689600, 1735689660]);
+ });
+ });
+});
From 827b845ec572b0971b198c3dc57b510d8f0b558e Mon Sep 17 00:00:00 2001
From: MFrancis-dev
Date: Sat, 21 Nov 2026 17:14:32 +0100
Subject: [PATCH 4/7] test(backend): cover stream_completed total, dedup
ordering and ledger time (#1763)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Completion writes the chain's total instead of accumulating withdrawals,
which is the only place the two can disagree — and the dedup guard runs
after the stream update, so a redelivery re-writes the row. Both
behaviours were undocumented. These tests pin the override, the
ledger-close timestamp precedence with its wall-clock fallback, and the
sentinel failure that must not fail the event.
---
backend/tests/stream-completed-event.test.ts | 555 +++++++++++++++++++
1 file changed, 555 insertions(+)
create mode 100644 backend/tests/stream-completed-event.test.ts
diff --git a/backend/tests/stream-completed-event.test.ts b/backend/tests/stream-completed-event.test.ts
new file mode 100644
index 00000000..c7668e6c
--- /dev/null
+++ b/backend/tests/stream-completed-event.test.ts
@@ -0,0 +1,555 @@
+/**
+ * Issue #1763 — completion events arriving before / after the final withdrawal,
+ * and replay of a completion, in the Soroban event worker.
+ *
+ * Characterization tests for `handleStreamCompleted` reached through the public
+ * `processEvent` dispatch, including the documented failure contract
+ * (`missing body fields`), the dependency failure where the `Stream` row is
+ * gone, and how the completion's authoritative `withdrawnAmount` interacts with
+ * the incrementing `tokens_withdrawn` handler.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { rpc, StrKey } from '@stellar/stellar-sdk';
+
+interface FakeStream {
+ streamId: bigint;
+ ratePerSecond: string;
+ depositedAmount: string;
+ withdrawnAmount: string;
+ tokenAddress: string;
+ startTime: bigint;
+ endTime: bigint | null;
+ lastUpdateTime: bigint;
+ isActive: boolean;
+ totalPausedDuration: number;
+}
+
+interface FakeStreamEvent {
+ id: number;
+ streamId: bigint;
+ eventType: string;
+ amount: string;
+ transactionHash: string;
+ ledgerSequence: number;
+ timestamp: number;
+ metadata: string;
+}
+
+const fake = vi.hoisted(() => {
+ const streams = new Map>();
+ const events = new Map>();
+ const rowKey = (hash: string, type: string) => `${hash}|${type}`;
+ let nextEventId = 1;
+
+ const notFound = () => {
+ const error = new Error('An operation failed because it depends on one or more records that were required but not found.');
+ (error as Error & { code?: string }).code = 'P2025';
+ return error;
+ };
+
+ const tx = {
+ stream: {
+ findUniqueOrThrow: vi.fn(async (args: { where: { streamId: bigint } }) => {
+ const row = streams.get(BigInt(args.where.streamId));
+ if (!row) throw notFound();
+ return { ...row };
+ }),
+ update: vi.fn(async (args: { where: { streamId: bigint }; data: Record }) => {
+ const row = streams.get(BigInt(args.where.streamId));
+ if (!row) throw notFound();
+ Object.assign(row, args.data);
+ return row;
+ }),
+ },
+ streamEvent: {
+ findUnique: vi.fn(
+ async (args: { where: { transactionHash_eventType: { transactionHash: string; eventType: string } } }) => {
+ const { transactionHash, eventType } = args.where.transactionHash_eventType;
+ const row = events.get(rowKey(transactionHash, eventType));
+ return row ? { id: row.id } : null;
+ },
+ ),
+ upsert: vi.fn(
+ async (args: {
+ where: { transactionHash_eventType: { transactionHash: string; eventType: string } };
+ create: Record;
+ update: Record;
+ }) => {
+ const { transactionHash, eventType } = args.where.transactionHash_eventType;
+ const key = rowKey(transactionHash, eventType);
+ const existing = events.get(key);
+ if (existing) {
+ Object.assign(existing, args.update);
+ return existing;
+ }
+ const created = { id: nextEventId++, ...args.create };
+ events.set(key, created);
+ return created;
+ },
+ ),
+ },
+ };
+
+ return {
+ streams,
+ events,
+ tx,
+ // Mirrors `prisma.$transaction`, including rollback, so a throw inside the
+ // handler cannot leave a half-applied stream state behind.
+ $transaction: vi.fn(async (cb: (client: typeof tx) => Promise) => {
+ const streamBackup = new Map([...streams].map(([id, row]) => [id, { ...row }]));
+ const eventBackup = new Map([...events].map(([key, row]) => [key, { ...row }]));
+ const restore = () => {
+ streams.clear();
+ events.clear();
+ for (const [id, row] of streamBackup) streams.set(id, row);
+ for (const [key, row] of eventBackup) events.set(key, row);
+ };
+ try {
+ return await cb(tx);
+ } catch (error) {
+ restore();
+ throw error;
+ }
+ }),
+ stream(id: bigint, overrides: Partial = {}): FakeStream {
+ const row: FakeStream = {
+ streamId: id,
+ ratePerSecond: '10',
+ depositedAmount: '1000',
+ withdrawnAmount: '0',
+ tokenAddress: 'CACTTKDP3Y6FMIWSJCMZOPRHGB3KGLFPSHKJZ4AQB6M33EOJCSRGEDR6',
+ startTime: 1700000000n,
+ endTime: 1700000100n,
+ lastUpdateTime: 1700000000n,
+ isActive: true,
+ totalPausedDuration: 0,
+ ...overrides,
+ };
+ streams.set(id, row as unknown as Record);
+ return row;
+ },
+ reset() {
+ streams.clear();
+ events.clear();
+ nextEventId = 1;
+ vi.clearAllMocks();
+ },
+ };
+});
+
+vi.mock('../src/lib/prisma.js', () => ({
+ default: { $transaction: fake.$transaction },
+ prisma: { $transaction: fake.$transaction },
+}));
+
+vi.mock('../src/services/sse.service.js', () => ({
+ sseService: {
+ broadcastToStream: vi.fn(),
+ broadcast: vi.fn(),
+ broadcastToAdmin: vi.fn(),
+ },
+}));
+
+const sentinelRecordWithdrawal = vi.hoisted(() => vi.fn());
+
+vi.mock('../src/services/sentinel.service.js', () => ({
+ sentinelService: {
+ recordWithdrawal: sentinelRecordWithdrawal,
+ recordStreamCreation: vi.fn(),
+ },
+}));
+
+vi.mock('../src/logger.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+ };
+});
+
+import { SorobanEventWorker } from '../src/workers/soroban-event-worker.js';
+import { sseService } from '../src/services/sse.service.js';
+import logger from '../src/logger.js';
+
+// ─── ScVal fixtures ──────────────────────────────────────────────────────────
+const sym = (name: string) => ({ sym: { toString: () => name } });
+const u64 = (value: number | bigint | string) => ({ u64: { toString: () => String(value) } });
+const i128 = (hi: number | bigint | string, lo: number | bigint | string) => ({
+ i128: { hi: { toString: () => String(hi) }, lo: { toString: () => String(lo) } },
+});
+const recipientBytes = Buffer.alloc(32, 11);
+const accountScVal = (bytes: Buffer) => ({
+ address: { type: 'scAddressTypeAccount', accountId: { ed25519: { value: bytes } } },
+});
+const entry = (key: string, val: unknown) => ({ key: sym(key), val });
+const mapOf = (entries: unknown[]) => ({ map: entries });
+
+const RECIPIENT = StrKey.encodeEd25519PublicKey(recipientBytes);
+
+interface EventOverrides {
+ streamId?: number;
+ txHash?: string;
+ ledger?: number;
+ ledgerClosedAt?: string;
+}
+
+/** `stream_completed` payload as the contract emits it (`StreamCompletedEvent`). */
+function completionEvent(
+ overrides: EventOverrides & { totalWithdrawn?: [number | bigint, number | bigint]; includeRecipient?: boolean },
+) {
+ const entries: unknown[] = [];
+ if (overrides.includeRecipient !== false) entries.push(entry('recipient', accountScVal(recipientBytes)));
+ if (overrides.totalWithdrawn) entries.push(entry('total_withdrawn', i128(overrides.totalWithdrawn[0], overrides.totalWithdrawn[1])));
+
+ return {
+ id: `${overrides.txHash ?? 'tx-complete'}-0`,
+ type: 'contract',
+ ledger: overrides.ledger ?? 2000,
+ ledgerClosedAt: overrides.ledgerClosedAt ?? '1700001000',
+ txHash: overrides.txHash ?? 'tx-complete',
+ transactionIndex: 0,
+ operationIndex: 0,
+ inSuccessfulContractCall: true,
+ topic: [sym('stream_completed'), u64(overrides.streamId ?? 7)],
+ value: mapOf(entries),
+ } as unknown as rpc.Api.EventResponse;
+}
+
+/** `tokens_withdrawn` payload — the incrementing sibling handler. */
+function withdrawalEvent(overrides: EventOverrides & { amount?: [number | bigint, number | bigint]; at?: number }) {
+ return {
+ id: `${overrides.txHash ?? 'tx-withdraw'}-0`,
+ type: 'contract',
+ ledger: overrides.ledger ?? 1999,
+ ledgerClosedAt: overrides.ledgerClosedAt ?? '1700000900',
+ txHash: overrides.txHash ?? 'tx-withdraw',
+ transactionIndex: 0,
+ operationIndex: 0,
+ inSuccessfulContractCall: true,
+ topic: [sym('tokens_withdrawn'), u64(overrides.streamId ?? 7)],
+ value: mapOf([
+ entry('recipient', accountScVal(recipientBytes)),
+ entry('amount', i128((overrides.amount ?? [0, 600])[0], (overrides.amount ?? [0, 600])[1])),
+ entry('timestamp', u64(overrides.at ?? 1700000900)),
+ ]),
+ } as unknown as rpc.Api.EventResponse;
+}
+
+const completedEvent = completionEvent({ totalWithdrawn: [0, 1000] });
+
+function streamRow(id = 7n) {
+ return fake.streams.get(id);
+}
+function eventRows() {
+ return [...fake.events.values()] as unknown as FakeStreamEvent[];
+}
+function rowsOfType(eventType: string) {
+ return eventRows().filter((row) => row.eventType === eventType);
+}
+function broadcastCalls() {
+ return (sseService.broadcastToStream as ReturnType).mock.calls;
+}
+
+describe('SorobanEventWorker — stream_completed ordering and replay (#1763)', () => {
+ let worker: SorobanEventWorker;
+
+ beforeEach(() => {
+ fake.reset();
+ vi.useFakeTimers();
+ vi.setSystemTime(Date.UTC(2025, 0, 1, 0, 0, 0));
+ sentinelRecordWithdrawal.mockResolvedValue(undefined);
+ worker = new SorobanEventWorker();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ describe('completion after the final withdrawal', () => {
+ it('overwrites withdrawnAmount with the chain-authoritative total instead of adding to it', async () => {
+ fake.stream(7n, { withdrawnAmount: '1000' });
+
+ await worker.processEvent(completionEvent({ totalWithdrawn: [0, 1000] }));
+
+ expect(streamRow()).toMatchObject({ isActive: false, withdrawnAmount: '1000' });
+ const updateArg = (fake.tx.stream.update as ReturnType).mock.calls[0][0] as {
+ data: Record;
+ };
+ expect(updateArg.data).not.toHaveProperty('depositedAmount');
+ });
+
+ it('matches the running total when every withdrawal was indexed first', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent(withdrawalEvent({ txHash: '0xw1', amount: [0, 400] }));
+ await worker.processEvent(withdrawalEvent({ txHash: '0xw2', amount: [0, 600] }));
+ await worker.processEvent(completionEvent({ totalWithdrawn: [0, 1000] }));
+
+ expect(streamRow()?.withdrawnAmount).toBe('1000');
+ expect(rowsOfType('WITHDRAWN')).toHaveLength(2);
+ expect(rowsOfType('COMPLETED')).toHaveLength(1);
+ });
+
+ it('closes the stream even when the on-chain total is below the indexed withdrawals', async () => {
+ // Refunds / fee accounting can leave the chain total lower than what the
+ // indexer accumulated; the completion is still authoritative.
+ fake.stream(7n, { withdrawnAmount: '1200' });
+
+ await worker.processEvent(completionEvent({ totalWithdrawn: [0, 1000] }));
+
+ expect(streamRow()).toMatchObject({ isActive: false, withdrawnAmount: '1000' });
+ });
+
+ it('records one COMPLETED row keyed on txHash + eventType with the cumulative amount', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent(completionEvent({ txHash: '0xc1', ledger: 2100, totalWithdrawn: [0, 1000] }));
+
+ const [event] = rowsOfType('COMPLETED');
+ expect(rowsOfType('COMPLETED')).toHaveLength(1);
+ expect(event).toMatchObject({
+ streamId: 7n,
+ eventType: 'COMPLETED',
+ amount: '1000',
+ transactionHash: '0xc1',
+ ledgerSequence: 2100,
+ });
+ expect(JSON.parse(event.metadata)).toEqual({ recipient: RECIPIENT });
+ });
+
+ it('broadcasts stream.completed with the decoded recipient and total', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent(completionEvent({ txHash: '0xc1', ledger: 2100, totalWithdrawn: [0, 1000] }));
+
+ expect(broadcastCalls()).toEqual([
+ [
+ '7',
+ 'stream.completed',
+ {
+ streamId: 7n,
+ recipient: RECIPIENT,
+ totalWithdrawn: '1000',
+ transactionHash: '0xc1',
+ ledger: 2100,
+ timestamp: 1700001000,
+ },
+ ],
+ ]);
+ });
+ });
+
+ describe('completion before the final withdrawal', () => {
+ it('lets a later withdrawal increment past the authoritative total', async () => {
+ // Ordering is observable: the completion assigns 1000, the withdrawal
+ // handler then adds its own amount to whatever is stored.
+ fake.stream(7n);
+
+ await worker.processEvent(completionEvent({ totalWithdrawn: [0, 1000] }));
+ await worker.processEvent(withdrawalEvent({ txHash: '0xw3', amount: [0, 600] }));
+
+ expect(streamRow()?.withdrawnAmount).toBe('1600');
+ expect(Number(streamRow()?.withdrawnAmount)).toBeGreaterThan(Number('1000'));
+ });
+
+ it('re-activates nothing: isActive stays false after a trailing withdrawal', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent(completionEvent({ totalWithdrawn: [0, 1000] }));
+ await worker.processEvent(withdrawalEvent({ txHash: '0xw3', amount: [0, 600] }));
+
+ expect(streamRow()?.isActive).toBe(false);
+ });
+
+ it('is idempotent when the trailing withdrawal is itself replayed', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent(completionEvent({ totalWithdrawn: [0, 1000] }));
+ const withdrawal = withdrawalEvent({ txHash: '0xw3', amount: [0, 600] });
+ await worker.processEvent(withdrawal);
+ await worker.processEvent(withdrawal);
+
+ expect(streamRow()?.withdrawnAmount).toBe('1600');
+ expect(rowsOfType('WITHDRAWN')).toHaveLength(1);
+ });
+ });
+
+ describe('replay of the same completion event', () => {
+ it('does not duplicate the COMPLETED row', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent(completedEvent);
+ await worker.processEvent(completedEvent);
+
+ expect(rowsOfType('COMPLETED')).toHaveLength(1);
+ expect(logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining('Duplicate StreamEvent skipped: txHash=tx-complete type=COMPLETED'),
+ );
+ });
+
+ it('re-applies the stream update because the guard runs after it', async () => {
+ fake.stream(7n, { withdrawnAmount: '0', isActive: true, lastUpdateTime: 1n });
+
+ await worker.processEvent(completedEvent);
+ await worker.processEvent(completedEvent);
+
+ expect(fake.tx.stream.update).toHaveBeenCalledTimes(2);
+ expect(fake.tx.streamEvent.findUnique).toHaveBeenCalledTimes(2);
+ expect(streamRow()).toMatchObject({ isActive: false, withdrawnAmount: '1000' });
+ });
+
+ it('re-broadcasts stream.completed to SSE for the replayed event', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent(completedEvent);
+ await worker.processEvent(completedEvent);
+
+ expect(broadcastCalls()).toHaveLength(2);
+ });
+
+ it('keeps the ledger timestamp stable across the replay', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent(completedEvent);
+ const firstStamp = streamRow()?.lastUpdateTime;
+ vi.setSystemTime(Date.UTC(2025, 0, 2, 0, 0, 0));
+ await worker.processEvent(completedEvent);
+
+ expect(firstStamp).toBe(1700001000);
+ expect(streamRow()?.lastUpdateTime).toBe(1700001000);
+ });
+ });
+
+ describe('failure contract', () => {
+ it('rejects when recipient is absent from the event body', async () => {
+ fake.stream(7n);
+
+ await expect(
+ worker.processEvent(completionEvent({ includeRecipient: false, totalWithdrawn: [0, 1000] })),
+ ).rejects.toThrow('StreamCompleted #7: missing body fields');
+
+ expect(fake.tx.stream.update).not.toHaveBeenCalled();
+ expect(rowsOfType('COMPLETED')).toHaveLength(0);
+ expect(broadcastCalls()).toHaveLength(0);
+ });
+
+ it('rejects when total_withdrawn is absent from the event body', async () => {
+ fake.stream(7n);
+
+ await expect(worker.processEvent(completionEvent({}))).rejects.toThrow(
+ 'StreamCompleted #7: missing body fields',
+ );
+
+ expect(fake.tx.stream.update).not.toHaveBeenCalled();
+ });
+
+ it('rejects before the dedup guard when the Stream row is gone', async () => {
+ // The update precedes the lookup, so a completion replayed against a
+ // pruned stream surfaces P2025 instead of being skipped as a duplicate.
+ await expect(worker.processEvent(completedEvent)).rejects.toMatchObject({ code: 'P2025' });
+
+ expect(fake.tx.streamEvent.findUnique).not.toHaveBeenCalled();
+ expect(rowsOfType('COMPLETED')).toHaveLength(0);
+ expect(broadcastCalls()).toHaveLength(0);
+ });
+
+ it('ignores a completion event that carries no stream id topic', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent({
+ id: 'truncated',
+ ledger: 2001,
+ ledgerClosedAt: '1700001100',
+ txHash: 'tx-truncated',
+ topic: [sym('stream_completed')],
+ value: mapOf([entry('recipient', accountScVal(recipientBytes)), entry('total_withdrawn', i128(0, 1))]),
+ } as unknown as rpc.Api.EventResponse);
+
+ expect(fake.$transaction).not.toHaveBeenCalled();
+ expect(broadcastCalls()).toHaveLength(0);
+ });
+
+ it('rolls back the whole transaction when the event-row write fails', async () => {
+ fake.stream(7n, { withdrawnAmount: '0', isActive: true });
+ (fake.tx.streamEvent.upsert as ReturnType).mockRejectedValueOnce(
+ new Error('deadlock detected'),
+ );
+
+ await expect(worker.processEvent(completedEvent)).rejects.toThrow('deadlock detected');
+
+ expect(streamRow()).toMatchObject({ isActive: true, withdrawnAmount: '0' });
+ expect(broadcastCalls()).toHaveLength(0);
+ });
+ });
+
+ describe('boundary inputs', () => {
+ it('handles a zero total_withdrawn completion (nothing was ever claimed)', async () => {
+ fake.stream(7n, { withdrawnAmount: '0' });
+
+ await worker.processEvent(completionEvent({ totalWithdrawn: [0, 0] }));
+
+ expect(streamRow()).toMatchObject({ isActive: false, withdrawnAmount: '0' });
+ expect(rowsOfType('COMPLETED')[0].amount).toBe('0');
+ });
+
+ it('handles a total that spans both halves of the i128', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent(completionEvent({ totalWithdrawn: [1, 5] }));
+
+ const expected = (1n << 64n) | 5n;
+ expect(streamRow()?.withdrawnAmount).toBe(expected.toString());
+ expect(rowsOfType('COMPLETED')[0].amount).toBe(expected.toString());
+ });
+
+ it('stamps the ledger close time rather than the processing time', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent(completionEvent({ ledgerClosedAt: '1700001000', totalWithdrawn: [0, 1000] }));
+
+ expect(streamRow()?.lastUpdateTime).toBe(1700001000);
+ expect(rowsOfType('COMPLETED')[0].timestamp).toBe(1700001000);
+ });
+
+ it('falls back to the wall clock when ledgerClosedAt is not an epoch number', async () => {
+ fake.stream(7n);
+
+ await worker.processEvent(
+ completionEvent({ ledgerClosedAt: '2024-01-01T00:00:00.000Z', totalWithdrawn: [0, 1000] }),
+ );
+
+ expect(streamRow()?.lastUpdateTime).toBe(1735689600);
+ expect(rowsOfType('COMPLETED')[0].timestamp).toBe(1735689600);
+ });
+ });
+
+ describe('dependency failures around the withdrawal leg', () => {
+ it('swallows a sentinel analysis failure so the withdrawal is still indexed', async () => {
+ fake.stream(7n);
+ sentinelRecordWithdrawal.mockRejectedValueOnce(new Error('redis unavailable'));
+
+ await worker.processEvent(withdrawalEvent({ txHash: '0xw1', amount: [0, 400] }));
+
+ expect(streamRow()?.withdrawnAmount).toBe('400');
+ expect(rowsOfType('WITHDRAWN')).toHaveLength(1);
+ expect(logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining('Sentinel withdrawal analysis failed for #7:'),
+ expect.any(Error),
+ );
+ await worker.processEvent(completionEvent({ totalWithdrawn: [0, 400] }));
+ expect(streamRow()).toMatchObject({ isActive: false, withdrawnAmount: '400' });
+ });
+
+ it('does not index a withdrawal whose stream row is missing, so completion cannot stack on it', async () => {
+ await expect(worker.processEvent(withdrawalEvent({ txHash: '0xw1', amount: [0, 400] }))).rejects.toMatchObject({
+ code: 'P2025',
+ });
+
+ expect(rowsOfType('WITHDRAWN')).toHaveLength(0);
+
+ await expect(worker.processEvent(completedEvent)).rejects.toMatchObject({ code: 'P2025' });
+ expect(streamRow(7n)).toBeUndefined();
+ });
+ });
+});
From fd60a09afcae3ca2ef1a4e0708686085dec0baa5 Mon Sep 17 00:00:00 2001
From: MFrancis-dev
Date: Sat, 21 Nov 2026 17:28:47 +0100
Subject: [PATCH 5/7] test: satisfy the strict index and unused-import checks
in the new tests
backend/tsconfig.json compiles tests/ with noUncheckedIndexedAccess and the
frontend build type-checks its test files, so an unchecked [0] read and an
unused React import each fail `npm run build` rather than the test run.
---
backend/tests/stream-completed-event.test.ts | 12 ++++++------
backend/tests/stream-topped-up-rate.test.ts | 10 +++++-----
.../app/incoming/__tests__/incoming-content.test.tsx | 1 -
3 files changed, 11 insertions(+), 12 deletions(-)
diff --git a/backend/tests/stream-completed-event.test.ts b/backend/tests/stream-completed-event.test.ts
index c7668e6c..0bdd1f4e 100644
--- a/backend/tests/stream-completed-event.test.ts
+++ b/backend/tests/stream-completed-event.test.ts
@@ -273,7 +273,7 @@ describe('SorobanEventWorker — stream_completed ordering and replay (#1763)',
await worker.processEvent(completionEvent({ totalWithdrawn: [0, 1000] }));
expect(streamRow()).toMatchObject({ isActive: false, withdrawnAmount: '1000' });
- const updateArg = (fake.tx.stream.update as ReturnType).mock.calls[0][0] as {
+ const updateArg = (fake.tx.stream.update as ReturnType).mock.calls[0]?.[0] as {
data: Record;
};
expect(updateArg.data).not.toHaveProperty('depositedAmount');
@@ -315,7 +315,7 @@ describe('SorobanEventWorker — stream_completed ordering and replay (#1763)',
transactionHash: '0xc1',
ledgerSequence: 2100,
});
- expect(JSON.parse(event.metadata)).toEqual({ recipient: RECIPIENT });
+ expect(JSON.parse(event!.metadata)).toEqual({ recipient: RECIPIENT });
});
it('broadcasts stream.completed with the decoded recipient and total', async () => {
@@ -490,7 +490,7 @@ describe('SorobanEventWorker — stream_completed ordering and replay (#1763)',
await worker.processEvent(completionEvent({ totalWithdrawn: [0, 0] }));
expect(streamRow()).toMatchObject({ isActive: false, withdrawnAmount: '0' });
- expect(rowsOfType('COMPLETED')[0].amount).toBe('0');
+ expect(rowsOfType('COMPLETED')[0]?.amount).toBe('0');
});
it('handles a total that spans both halves of the i128', async () => {
@@ -500,7 +500,7 @@ describe('SorobanEventWorker — stream_completed ordering and replay (#1763)',
const expected = (1n << 64n) | 5n;
expect(streamRow()?.withdrawnAmount).toBe(expected.toString());
- expect(rowsOfType('COMPLETED')[0].amount).toBe(expected.toString());
+ expect(rowsOfType('COMPLETED')[0]?.amount).toBe(expected.toString());
});
it('stamps the ledger close time rather than the processing time', async () => {
@@ -509,7 +509,7 @@ describe('SorobanEventWorker — stream_completed ordering and replay (#1763)',
await worker.processEvent(completionEvent({ ledgerClosedAt: '1700001000', totalWithdrawn: [0, 1000] }));
expect(streamRow()?.lastUpdateTime).toBe(1700001000);
- expect(rowsOfType('COMPLETED')[0].timestamp).toBe(1700001000);
+ expect(rowsOfType('COMPLETED')[0]?.timestamp).toBe(1700001000);
});
it('falls back to the wall clock when ledgerClosedAt is not an epoch number', async () => {
@@ -520,7 +520,7 @@ describe('SorobanEventWorker — stream_completed ordering and replay (#1763)',
);
expect(streamRow()?.lastUpdateTime).toBe(1735689600);
- expect(rowsOfType('COMPLETED')[0].timestamp).toBe(1735689600);
+ expect(rowsOfType('COMPLETED')[0]?.timestamp).toBe(1735689600);
});
});
diff --git a/backend/tests/stream-topped-up-rate.test.ts b/backend/tests/stream-topped-up-rate.test.ts
index d1a03843..674cae68 100644
--- a/backend/tests/stream-topped-up-rate.test.ts
+++ b/backend/tests/stream-topped-up-rate.test.ts
@@ -264,7 +264,7 @@ describe('SorobanEventWorker — stream_topped_up rate accounting (#1761)', () =
transactionHash: '0xabc',
ledgerSequence: 555,
});
- expect(JSON.parse(event.metadata)).toEqual({ newDepositedAmount: '2100' });
+ expect(JSON.parse(event!.metadata)).toEqual({ newDepositedAmount: '2100' });
});
it('adds totalPausedDuration back onto the derived endTime', async () => {
@@ -334,7 +334,7 @@ describe('SorobanEventWorker — stream_topped_up rate accounting (#1761)', () =
topUpEvent({ body: { amount: [1, 0], newDeposited: [1, 0] } }),
);
- expect(eventRows()[0].amount).toBe('18446744073709551616');
+ expect(eventRows()[0]?.amount).toBe('18446744073709551616');
expect(toppedUpRow()?.depositedAmount).toBe('18446744073709551616');
});
@@ -344,7 +344,7 @@ describe('SorobanEventWorker — stream_topped_up rate accounting (#1761)', () =
await worker.processEvent(topUpEvent({ body: { amount: [0, 0], newDeposited: [0, 2100] } }));
expect(toppedUpRow()).toMatchObject({ depositedAmount: '2100', endTime: START + 210n });
- expect(eventRows()[0].amount).toBe('0');
+ expect(eventRows()[0]?.amount).toBe('0');
});
it('never rewrites ratePerSecond — the stored rate is the only input', async () => {
@@ -352,7 +352,7 @@ describe('SorobanEventWorker — stream_topped_up rate accounting (#1761)', () =
await worker.processEvent(topUpEvent({ body: defaultBody }));
- const updateCall = (fake.tx.stream.update as ReturnType).mock.calls[0][0] as {
+ const updateCall = (fake.tx.stream.update as ReturnType).mock.calls[0]?.[0] as {
data: Record;
};
expect(Object.keys(updateCall.data).sort()).toEqual(['depositedAmount', 'endTime', 'lastUpdateTime']);
@@ -499,7 +499,7 @@ describe('SorobanEventWorker — stream_topped_up rate accounting (#1761)', () =
await worker.processEvent(topUpEvent({ body: defaultBody }));
expect(toppedUpRow()?.lastUpdateTime).toBe(1735689600);
- expect(eventRows()[0].timestamp).toBe(1735689600);
+ expect(eventRows()[0]?.timestamp).toBe(1735689600);
});
it('advances the stamp when a later top-up is processed in a later wall-clock second', async () => {
diff --git a/frontend/src/app/incoming/__tests__/incoming-content.test.tsx b/frontend/src/app/incoming/__tests__/incoming-content.test.tsx
index 428d0886..323fb621 100644
--- a/frontend/src/app/incoming/__tests__/incoming-content.test.tsx
+++ b/frontend/src/app/incoming/__tests__/incoming-content.test.tsx
@@ -1,6 +1,5 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
-import React from "react";
// The incoming page now derives its loading / error / empty / ready branches
// from `useAsyncPageData` (#1085). These tests pin the rendered result of each
From 6bf450ce23832e793237f9ee75a99007ded42646 Mon Sep 17 00:00:00 2001
From: MFrancis-dev
Date: Sat, 21 Nov 2026 17:35:56 +0100
Subject: [PATCH 6/7] test(backend): adapt the top-up suite to the
single-writer refactor
#1932 moved the top-up writes behind applyToppedUpEvent, which takes the
stream row lock through $executeRaw and selects only the columns it needs,
and started storing the event timestamp as a BigInt. The fake client has to
mirror that seam or the suite describes a shape the worker no longer has.
---
backend/tests/stream-topped-up-rate.test.ts | 29 +++++++++++++++++----
1 file changed, 24 insertions(+), 5 deletions(-)
diff --git a/backend/tests/stream-topped-up-rate.test.ts b/backend/tests/stream-topped-up-rate.test.ts
index 674cae68..b75ad627 100644
--- a/backend/tests/stream-topped-up-rate.test.ts
+++ b/backend/tests/stream-topped-up-rate.test.ts
@@ -30,7 +30,8 @@ interface FakeStreamEvent {
amount: string;
transactionHash: string;
ledgerSequence: number;
- timestamp: number;
+ /** `StreamEvent.timestamp` is a BigInt column; the writer passes `BigInt(...)`. */
+ timestamp: bigint;
metadata: string;
}
@@ -47,6 +48,12 @@ const fake = vi.hoisted(() => {
};
const tx = {
+ // `lockStreamForUpdate` (issue #1932) takes the row lock through raw SQL
+ // before touching any amount. Tagged-template call, so the bound values
+ // arrive after the strings array.
+ $executeRaw: vi.fn(async (_strings: unknown, ...values: unknown[]) =>
+ streams.has(BigInt(values[0] as bigint)) ? 1 : 0,
+ ),
stream: {
findUniqueOrThrow: vi.fn(async (args: { where: { streamId: bigint } }) => {
const row = streams.get(BigInt(args.where.streamId));
@@ -62,10 +69,19 @@ const fake = vi.hoisted(() => {
},
streamEvent: {
findUnique: vi.fn(
- async (args: { where: { transactionHash_eventType: { transactionHash: string; eventType: string } } }) => {
+ async (args: {
+ where: { transactionHash_eventType: { transactionHash: string; eventType: string } };
+ select?: Record;
+ }) => {
const { transactionHash, eventType } = args.where.transactionHash_eventType;
const row = events.get(rowKey(transactionHash, eventType));
- return row ? { id: row.id } : null;
+ if (!row) return null;
+ // Mirror Prisma's `select`: only the requested columns come back, so a
+ // handler that reads a field it never asked for fails here, not in prod.
+ const selected = args.select ?? { id: true };
+ return Object.fromEntries(
+ Object.keys(selected).map((field) => [field, row[field]]),
+ );
},
),
upsert: vi.fn(
@@ -248,6 +264,9 @@ describe('SorobanEventWorker — stream_topped_up rate accounting (#1761)', () =
depositedAmount: '2100',
endTime: START + 210n,
});
+ // The single-writer contract (#1932): the row lock is taken before the
+ // amount is read back, so a concurrent top-up cannot interleave.
+ expect(fake.tx.$executeRaw).toHaveBeenCalledTimes(1);
});
it('writes exactly one TOPPED_UP StreamEvent keyed on txHash + eventType', async () => {
@@ -499,7 +518,7 @@ describe('SorobanEventWorker — stream_topped_up rate accounting (#1761)', () =
await worker.processEvent(topUpEvent({ body: defaultBody }));
expect(toppedUpRow()?.lastUpdateTime).toBe(1735689600);
- expect(eventRows()[0]?.timestamp).toBe(1735689600);
+ expect(eventRows()[0]?.timestamp).toBe(1735689600n);
});
it('advances the stamp when a later top-up is processed in a later wall-clock second', async () => {
@@ -510,7 +529,7 @@ describe('SorobanEventWorker — stream_topped_up rate accounting (#1761)', () =
await worker.processEvent(topUpEvent({ txHash: '0x2', body: { amount: [0, 1], newDeposited: [0, 1002] } }));
expect(toppedUpRow()?.lastUpdateTime).toBe(1735689660);
- expect(eventRows().map((row) => row.timestamp)).toEqual([1735689600, 1735689660]);
+ expect(eventRows().map((row) => row.timestamp)).toEqual([1735689600n, 1735689660n]);
});
});
});
From 2731d1e2d1aec72b2d6de395bf0013c2c66614f8 Mon Sep 17 00:00:00 2001
From: MFrancis-dev
Date: Sat, 21 Nov 2026 17:47:38 +0100
Subject: [PATCH 7/7] test(backend): cover the top-up marker reconciliation
added in #1932
The API writer and the indexer share one dedup key, and the marker row the
API leaves behind (ledgerSequence 0) is the only case where the indexer
writes through a skip. Nothing pinned which of the two branches a given
existing row takes.
---
backend/tests/stream-topped-up-rate.test.ts | 79 +++++++++++++++++++++
1 file changed, 79 insertions(+)
diff --git a/backend/tests/stream-topped-up-rate.test.ts b/backend/tests/stream-topped-up-rate.test.ts
index b75ad627..a76dd6f1 100644
--- a/backend/tests/stream-topped-up-rate.test.ts
+++ b/backend/tests/stream-topped-up-rate.test.ts
@@ -108,6 +108,7 @@ const fake = vi.hoisted(() => {
return {
streams,
events,
+ eventKey: rowKey,
tx,
// Same call shape as `prisma.$transaction`, including rollback of the
// in-memory rows so a mid-transaction throw cannot leave a partial write.
@@ -239,6 +240,31 @@ function broadcastCalls() {
return (sseService.broadcastToStream as ReturnType).mock.calls;
}
+/**
+ * The row `applyTopUpOnce` leaves behind when this API process confirms a
+ * top-up before the indexer sees it: the real dedup key with the
+ * `ledgerSequence = 0` marker meaning "chain position not known yet".
+ */
+function seedApiMarkerRow(opts: {
+ txHash: string;
+ amount: string;
+ timestamp?: bigint;
+ ledgerSequence?: number;
+}) {
+ const row: FakeStreamEvent = {
+ id: 900,
+ streamId: 42n,
+ eventType: 'TOPPED_UP',
+ amount: opts.amount,
+ transactionHash: opts.txHash,
+ ledgerSequence: opts.ledgerSequence ?? 0,
+ timestamp: opts.timestamp ?? 1735689600n,
+ metadata: '{}',
+ };
+ fake.events.set(fake.eventKey(opts.txHash, 'TOPPED_UP'), row as unknown as Record);
+ return row;
+}
+
describe('SorobanEventWorker — stream_topped_up rate accounting (#1761)', () => {
let worker: SorobanEventWorker;
@@ -509,6 +535,59 @@ describe('SorobanEventWorker — stream_topped_up rate accounting (#1761)', () =
});
});
+ describe('reconciling the marker row the API writer leaves behind', () => {
+ it('assigns the chain total instead of adding its own delta on top of it', async () => {
+ // `applyTopUpOnce` already credited 2100 and stored the top-up with
+ // ledgerSequence 0; re-applying the 1100 delta here would overcount the
+ // stream permanently.
+ fake.stream(42n, { depositedAmount: '2100', endTime: START + 210n });
+ seedApiMarkerRow({ txHash: '0xapi', amount: '1100' });
+
+ await worker.processEvent(topUpEvent({ txHash: '0xapi', ledger: 555, body: defaultBody }));
+
+ expect(toppedUpRow()).toMatchObject({ depositedAmount: '2100', endTime: START + 210n });
+ expect(fake.tx.stream.update).toHaveBeenCalledTimes(1);
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining('Reconciling API-applied top-up against chain: txHash=0xapi'),
+ );
+ });
+
+ it('overwrites the deposit with the chain value when the two disagree', async () => {
+ fake.stream(42n, { depositedAmount: '2100' });
+ seedApiMarkerRow({ txHash: '0xapi', amount: '1100' });
+
+ await worker.processEvent(
+ topUpEvent({ txHash: '0xapi', ledger: 555, body: { amount: [0, 1050], newDeposited: [0, 2050] } }),
+ );
+
+ expect(toppedUpRow()?.depositedAmount).toBe('2050');
+ expect(toppedUpRow()?.endTime).toBe(START + 205n);
+ });
+
+ it('fills the ledger position into the existing row instead of writing a second one', async () => {
+ fake.stream(42n, { depositedAmount: '2100' });
+ const marker = seedApiMarkerRow({ txHash: '0xapi', amount: '1100' });
+
+ await worker.processEvent(topUpEvent({ txHash: '0xapi', ledger: 555, body: defaultBody }));
+
+ expect(eventRows()).toHaveLength(1);
+ expect(marker.ledgerSequence).toBe(555);
+ });
+
+ it('still skips a row the indexer itself wrote, which is any non-zero ledger position', async () => {
+ fake.stream(42n, { depositedAmount: '2100' });
+ seedApiMarkerRow({ txHash: '0xapi', amount: '1100', ledgerSequence: 444 });
+
+ await worker.processEvent(
+ topUpEvent({ txHash: '0xapi', ledger: 555, body: { amount: [0, 9000], newDeposited: [0, 9999] } }),
+ );
+
+ expect(fake.tx.stream.update).not.toHaveBeenCalled();
+ expect(toppedUpRow()).toMatchObject({ depositedAmount: '2100' });
+ expect(eventRows()[0]?.ledgerSequence).toBe(444);
+ });
+ });
+
describe('timestamp semantics', () => {
it('stamps lastUpdateTime with processing time, not the ledger close time', async () => {
// The event's ledgerClosedAt decodes to 1700000500; this handler is the