Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
e30d3ee
feat(analytics): swap/send USD volume telemetry on terminal events
claude Aug 27, 2026
c27e8db
fix(analytics): review fixes for the volume telemetry emit path
JakeUrban Aug 28, 2026
8b8f388
refactor(analytics): drop requirements-doc citations from code comments
JakeUrban Aug 28, 2026
b8dc83a
docs(analytics): note classifyAssetIdentity's balance-freshness assum…
JakeUrban Aug 28, 2026
81aef36
docs(analytics): state what SubmitFail does, not just what it stopped…
JakeUrban Aug 28, 2026
d643c96
Merge remote-tracking branch 'origin/master' into claude/amplitude-sw…
claude Aug 28, 2026
c7ed993
fix(analytics): adapt transactionResult XDR usage to stellar-sdk v17
claude Aug 28, 2026
b4dee37
fix(analytics): address Copilot review findings on telemetry PR
claude Aug 28, 2026
9b3a3cc
revert(analytics): drop two Copilot fixes per author review feedback
claude Aug 28, 2026
c651aaa
fix(analytics): don't gate usd_slippage_pct on the rounded source value
claude Aug 28, 2026
203ef6a
fix(analytics): classify source-side trustline failures, not just des…
claude Aug 28, 2026
9f0b937
revert(analytics): restore the rounded-value gate on usd_slippage_pct
claude Aug 28, 2026
73bc325
fix(analytics): guard classifyAssetIdentity against LP balance entries
claude Aug 31, 2026
c5ec0a2
fix(test): stop asserting the transient loading frame in SubmitTransa…
claude Aug 31, 2026
d486db9
Merge branch 'master' into claude/amplitude-swap-send-volume-k973lt
JakeUrban Aug 31, 2026
ee08f71
refactor(analytics): reuse existing balance helpers per piyalbasu's r…
claude Aug 31, 2026
833f8ab
refactor(analytics): enums over union types, narrowing over non-null …
claude Aug 31, 2026
6f69a4e
Suppress volume telemetry for custom-network submissions
claude Aug 31, 2026
4dd8502
fix: don't require a prepared transaction to submit a classic payment
claude Aug 31, 2026
a9cd6a5
style(analytics): SCREAMING_SNAKE members on the five new enums
claude Sep 1, 2026
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
17 changes: 17 additions & 0 deletions @shared/api/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,12 @@ export const getTokenPrices = async (
// release. A default silently opts new callers into v2 and defeats the
// kill switch.
useV2: boolean,
// Cancels the request when the caller no longer needs the answer (e.g. the
// confirmation price snapshot's terminal-status deadline). A true network
// abort on the v1 path; the v2 request runs in the background service
// worker across a message boundary the signal cannot cross, so there it
// only skips a not-yet-sent request and rejects a no-longer-wanted result.
signal?: AbortSignal,
Comment thread
JakeUrban marked this conversation as resolved.
): Promise<ApiTokenPrices> => {
// NOTE: API does not accept LP IDs or custom tokens
const filteredTokens = tokens.filter((tokenId) => {
Expand Down Expand Up @@ -758,6 +764,10 @@ export const getTokenPrices = async (
return {};
}

if (signal?.aborted) {
throw new DOMException("token-prices request aborted", "AbortError");
}

// Query lives in the path so callBackendV2 signs the JWT's methodAndPath
// over the server's full request-target (path + query) — see #2879.
const { status, body } = await fetchBackendV2({
Expand All @@ -766,6 +776,12 @@ export const getTokenPrices = async (
body: requestBody,
});

// The background request cannot be cancelled mid-flight (see `signal`
// param doc); reject a result nobody wants instead of returning it.
if (signal?.aborted) {
throw new DOMException("token-prices request aborted", "AbortError");
}

// Mirror getDiscoverData: a 200 without a `data` payload is still a
// failure — returning undefined would violate the Promise<ApiTokenPrices>
// contract (the caller's try/catch only handles throws, not bad returns).
Expand All @@ -789,6 +805,7 @@ export const getTokenPrices = async (
"Content-Type": "application/json",
},
body: requestBody,
signal,
};
const response = await fetch(url.href, options);
const parsedResponse = (await response.json()) as { data: ApiTokenPrices };
Expand Down
203 changes: 203 additions & 0 deletions extension/src/helpers/confirmationPriceSnapshot.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import * as ApiInternal from "@shared/api/internal";
import { ApiTokenPrices } from "@shared/api/types";
import { TESTNET_NETWORK_DETAILS } from "@shared/constants/stellar";
import {
PriceFreshness,
PriceSource,
startConfirmationPriceSnapshot,
} from "./confirmationPriceSnapshot";

const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0));

describe("startConfirmationPriceSnapshot", () => {
afterEach(() => {
jest.restoreAllMocks();
});

it("uses the freshly fetched prices once the fetch has settled (confirmation_fetch)", async () => {
jest
.spyOn(ApiInternal, "getTokenPrices")
.mockResolvedValue({ native: { currentPrice: "0.5" } });

const handle = startConfirmationPriceSnapshot({
canonicalIds: ["native"],
networkDetails: TESTNET_NETWORK_DETAILS,
useV2: true,
cachedDisplayPrices: { native: { currentPrice: "0.1" } },
});

await flushMicrotasks();

expect(handle.resolve()).toEqual({
pricesById: { native: { currentPrice: "0.5" } },
freshness: PriceFreshness.CONFIRMATION_FETCH,
source: PriceSource.TOKEN_PRICES_V2,
});
});

it("falls back wholesale to the display cache when the fetch only covers some of the requested ids", async () => {
// A 200 that omits the swap destination (e.g. a non-held token
// /token-prices has no entry for) - a partial result isn't trusted even
// for the ids it does cover.
jest
.spyOn(ApiInternal, "getTokenPrices")
.mockResolvedValue({ native: { currentPrice: "0.5" } });

const handle = startConfirmationPriceSnapshot({
canonicalIds: ["native", "USDC:ISSUER"],
networkDetails: TESTNET_NETWORK_DETAILS,
useV2: true,
cachedDisplayPrices: { native: { currentPrice: "0.1" } },
});

await flushMicrotasks();

expect(handle.resolve()).toEqual({
pricesById: { native: { currentPrice: "0.1" } },
freshness: PriceFreshness.CACHED_DISPLAY,
source: PriceSource.TOKEN_PRICES_V2,
});
});

it("falls back to the cached display prices when the fetch hasn't settled yet (cached_display)", () => {
// Never resolves within this test — resolve() is called before any await.
jest
.spyOn(ApiInternal, "getTokenPrices")
.mockImplementation(() => new Promise(() => {}));

const handle = startConfirmationPriceSnapshot({
canonicalIds: ["native"],
networkDetails: TESTNET_NETWORK_DETAILS,
useV2: false,
cachedDisplayPrices: { native: { currentPrice: "0.1" } },
});

expect(handle.resolve()).toEqual({
pricesById: { native: { currentPrice: "0.1" } },
freshness: PriceFreshness.CACHED_DISPLAY,
source: PriceSource.TOKEN_PRICES_V1,
});
});

it("falls back to the cached display prices when the fetch rejects", async () => {
jest
.spyOn(ApiInternal, "getTokenPrices")
.mockRejectedValue(new Error("network down"));

const handle = startConfirmationPriceSnapshot({
canonicalIds: ["native"],
networkDetails: TESTNET_NETWORK_DETAILS,
useV2: true,
cachedDisplayPrices: { native: { currentPrice: "0.1" } },
});

await flushMicrotasks();

// A rejected fetch degrades exactly like a still-pending one: coverage
// takes priority over freshness, and the degradation is visible via
// `cached_display` rather than reported as unpriced legs.
expect(handle.resolve()).toEqual({
pricesById: { native: { currentPrice: "0.1" } },
freshness: PriceFreshness.CACHED_DISPLAY,
source: PriceSource.TOKEN_PRICES_V2,
});
});

it("degrades to a null snapshot (not a throw) when the fetch rejects and no display price is cached", async () => {
jest
.spyOn(ApiInternal, "getTokenPrices")
.mockRejectedValue(new Error("network down"));

const handle = startConfirmationPriceSnapshot({
canonicalIds: ["native"],
networkDetails: TESTNET_NETWORK_DETAILS,
useV2: true,
cachedDisplayPrices: null,
});

await flushMicrotasks();

expect(handle.resolve()).toEqual({
pricesById: null,
freshness: PriceFreshness.CACHED_DISPLAY,
source: PriceSource.TOKEN_PRICES_V2,
});
});

it("aborts a still-pending fetch at resolve() so the request cannot outlive the flow", () => {
let capturedSignal: AbortSignal | undefined;
jest
.spyOn(ApiInternal, "getTokenPrices")
.mockImplementation((_tokens, _network, _useV2, signal) => {
capturedSignal = signal;
return new Promise(() => {});
});

const handle = startConfirmationPriceSnapshot({
canonicalIds: ["native"],
networkDetails: TESTNET_NETWORK_DETAILS,
useV2: false,
cachedDisplayPrices: null,
});

expect(capturedSignal?.aborted).toBe(false);
handle.resolve();
expect(capturedSignal?.aborted).toBe(true);
});

it("cancel() aborts the fetch without producing a snapshot (pre-submission failure)", () => {
let capturedSignal: AbortSignal | undefined;
jest
.spyOn(ApiInternal, "getTokenPrices")
.mockImplementation((_tokens, _network, _useV2, signal) => {
capturedSignal = signal;
return new Promise(() => {});
});

const handle = startConfirmationPriceSnapshot({
canonicalIds: ["native"],
networkDetails: TESTNET_NETWORK_DETAILS,
useV2: false,
cachedDisplayPrices: null,
});

handle.cancel();
expect(capturedSignal?.aborted).toBe(true);
// Idempotent, and safe to combine with a later resolve().
handle.cancel();
expect(handle.resolve().freshness).toBe(PriceFreshness.CACHED_DISPLAY);
});

it("never consults a late-arriving result after resolve() already ran", async () => {
let resolveFetch!: (value: ApiTokenPrices) => void;
jest.spyOn(ApiInternal, "getTokenPrices").mockImplementation(
() =>
new Promise((resolve) => {
resolveFetch = resolve;
}),
);

const handle = startConfirmationPriceSnapshot({
canonicalIds: ["native"],
networkDetails: TESTNET_NETWORK_DETAILS,
useV2: true,
cachedDisplayPrices: { native: { currentPrice: "0.2" } },
});

// Not settled yet — this is the snapshot the terminal event uses.
const frozen = handle.resolve();
expect(frozen.freshness).toBe(PriceFreshness.CACHED_DISPLAY);

// The fetch resolves only after the snapshot was already frozen.
resolveFetch({ native: { currentPrice: "999" } });
await flushMicrotasks();

// Calling resolve() again would now see it as settled — proving the
// *first* frozen snapshot (already returned above) never changes.
expect(frozen).toEqual({
pricesById: { native: { currentPrice: "0.2" } },
freshness: PriceFreshness.CACHED_DISPLAY,
source: PriceSource.TOKEN_PRICES_V2,
});
});
});
121 changes: 121 additions & 0 deletions extension/src/helpers/confirmationPriceSnapshot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { getTokenPrices } from "@shared/api/internal";
import { ApiTokenPrices } from "@shared/api/types";
import { NetworkDetails } from "@shared/constants/stellar";

export enum PriceSource {
TOKEN_PRICES_V1 = "token_prices_v1",
TOKEN_PRICES_V2 = "token_prices_v2",
}

export enum PriceFreshness {
CONFIRMATION_FETCH = "confirmation_fetch",
CACHED_DISPLAY = "cached_display",
}

export interface ConfirmationPriceSnapshot {
/** Prices by canonical id. `null` when no snapshot could be produced. */
pricesById: ApiTokenPrices | null;
freshness: PriceFreshness;
source: PriceSource;
}

export interface ConfirmationSnapshotHandle {
/**
* Freezes and returns the snapshot for a terminal event. Call exactly once,
* at terminal status. If the fetch already succeeded, uses its result
* (`confirmation_fetch`); otherwise — still pending, rejected, or cancelled
* — the fetch is aborted and its result, even if it lands later, is never
* consulted again, and this falls back to the prices already cached for the
* on-screen display estimate (`cached_display`).
*/
resolve(): ConfirmationPriceSnapshot;
/**
* Aborts the fetch and discards its result without producing a snapshot.
* For a confirmation attempt that ends before submission — no terminal
* event will consume the snapshot, so the request is cancelled immediately.
* Idempotent, and safe after `resolve()`.
*/
cancel(): void;
}

/**
* Issues ONE price fetch covering every leg's canonical id, started at
* confirmation and never blocking signing/submission — callers do not await
* this. `cachedDisplayPrices` is the price map already held for the on-screen
* fiat estimate, captured by the caller at this same moment: it must reflect
* "the price already shown to the user for this transaction", not whatever
* the cache holds later when `resolve()` is called.
*
* Cancellation is a real network abort on the v1 endpoint (a direct fetch).
* The v2 endpoint runs in the background service worker across a message
* boundary the AbortSignal cannot cross, so there cancellation is best-effort:
* the request is skipped if already aborted, and a result that arrives after
* abort is discarded even though the HTTP itself ran to completion.
*/
export const startConfirmationPriceSnapshot = ({
canonicalIds,
networkDetails,
useV2,
cachedDisplayPrices,
}: {
canonicalIds: string[];
networkDetails: NetworkDetails;
useV2: boolean;
cachedDisplayPrices: ApiTokenPrices | null;
}): ConfirmationSnapshotHandle => {
const source: PriceSource = useV2
? PriceSource.TOKEN_PRICES_V2
: PriceSource.TOKEN_PRICES_V1;

const controller = new AbortController();
let succeeded = false;
let fetchedPrices: ApiTokenPrices | null = null;

// Never an unhandled rejection: a failed fetch degrades to cached_display
// exactly like one that's merely still pending at resolve() time.
getTokenPrices(canonicalIds, networkDetails, useV2, controller.signal)
.then((result) => {
// A result landing after abort is discarded, never consulted.
if (!controller.signal.aborted) {
fetchedPrices = result;
succeeded = true;
}
})
.catch(() => {
// Rejected (network error, non-2xx, or aborted): fall back to the
// display-cache price at resolve() time rather than reporting the legs
// unpriced — coverage takes priority over freshness.
succeeded = false;
});

return {
resolve: () => {
// A 200 can still omit a requested id (e.g. a non-held destination
// token /token-prices has no entry for). A partial result isn't
// trustworthy enough to use even for the ids it does cover, so it's
// treated the same as no result at all: fall back to the display
// cache wholesale rather than merging.
const isComplete =
succeeded && canonicalIds.every((id) => fetchedPrices?.[id] != null);
if (isComplete) {
return {
pricesById: fetchedPrices,
Comment thread
JakeUrban marked this conversation as resolved.
freshness: PriceFreshness.CONFIRMATION_FETCH,
source,
};
}
// Pending, rejected, incomplete, or cancelled: abort so the request
// cannot outlive the flow that needed it, and close on the display
// cache.
controller.abort();
return {
pricesById: cachedDisplayPrices,
freshness: PriceFreshness.CACHED_DISPLAY,
source,
};
},
cancel: () => {
controller.abort();
},
};
};
Loading
Loading