-
Notifications
You must be signed in to change notification settings - Fork 60
Add volume telemetry for swaps and payments with USD pricing #2984
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
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 c27e8db
fix(analytics): review fixes for the volume telemetry emit path
JakeUrban 8b8f388
refactor(analytics): drop requirements-doc citations from code comments
JakeUrban b8dc83a
docs(analytics): note classifyAssetIdentity's balance-freshness assum…
JakeUrban 81aef36
docs(analytics): state what SubmitFail does, not just what it stopped…
JakeUrban d643c96
Merge remote-tracking branch 'origin/master' into claude/amplitude-sw…
claude c7ed993
fix(analytics): adapt transactionResult XDR usage to stellar-sdk v17
claude b4dee37
fix(analytics): address Copilot review findings on telemetry PR
claude 9b3a3cc
revert(analytics): drop two Copilot fixes per author review feedback
claude c651aaa
fix(analytics): don't gate usd_slippage_pct on the rounded source value
claude 203ef6a
fix(analytics): classify source-side trustline failures, not just des…
claude 9f0b937
revert(analytics): restore the rounded-value gate on usd_slippage_pct
claude 73bc325
fix(analytics): guard classifyAssetIdentity against LP balance entries
claude c5ec0a2
fix(test): stop asserting the transient loading frame in SubmitTransa…
claude d486db9
Merge branch 'master' into claude/amplitude-swap-send-volume-k973lt
JakeUrban ee08f71
refactor(analytics): reuse existing balance helpers per piyalbasu's r…
claude 833f8ab
refactor(analytics): enums over union types, narrowing over non-null …
claude 6f69a4e
Suppress volume telemetry for custom-network submissions
claude 4dd8502
fix: don't require a prepared transaction to submit a classic payment
claude a9cd6a5
style(analytics): SCREAMING_SNAKE members on the five new enums
claude File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
203 changes: 203 additions & 0 deletions
203
extension/src/helpers/confirmationPriceSnapshot.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
|
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(); | ||
| }, | ||
| }; | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.