taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit 6b51c999beb732e39b0b62a4d92ff3451d0234e8
parent f5979370fd5060e52121242c1a2ab74ad67d3b49
Author: Florian Dold <dold@taler.net>
Date:   Tue, 10 Nov 2026 16:59:18 +0100

wallet web UI: render peer receipts from snapshots after preparation

Keep preparation separate, then use snapshots as the sole source of receive
review fields. Share the push/pull confirmation lifecycle while retaining
explicit API calls and push progress cancellation. Cover delayed snapshots,
deletion, preparation cancellation and failed or cancelled confirmations.

Diffstat:
Mpackages/wallet-webui/src/routes/App.tsx | 362++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------
Mpackages/wallet-webui/src/routes/exchange-gate-model.ts | 17+++--------------
Mpackages/wallet-webui/src/screens/PeerReceiveScreen.tsx | 41++++++++++++++++++++++++-----------------
Apackages/wallet-webui/test/peer-credit-observation.test.tsx | 461+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/test/routing.test.ts | 14--------------
5 files changed, 710 insertions(+), 185 deletions(-)

diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -1,3 +1,5 @@ +import { peerCreditConfirmationView } from "./peer-credit-review-model.js"; +import { usePeerCreditObservation } from "../api/observations.js"; import { ConfirmPayResultType, Amounts, @@ -158,7 +160,6 @@ import { } from "./ManagementRoutes.js"; import { exchangeRouteId } from "./management-model.js"; import { - peerReceiveExchangeGate, peerRequestExchangeGate, type ExchangeActionGate, } from "./exchange-gate-model.js"; @@ -2195,45 +2196,32 @@ function PeerShareRoute() { ); } +type PreparedPeerPayment = + | { kind: "receive"; data: PreparePeerPushCreditResponse } + | { kind: "pay"; data: PreparePeerPullDebitResponse }; + function PeerReceiveRoute() { - const { connection, platform } = useServices(); - const { language } = useLanguage(); const [, params] = useRoute("/peer-receive/:actionId"); + const actionId = params?.actionId ?? ""; + return <PeerPreparation key={actionId} actionId={actionId} />; +} + +function PeerPreparation({ actionId }: { actionId: string }) { + const { connection, platform } = useServices(); const [, navigate] = useLocation(); const callMutation = useWalletMutation(connection); const { controller: progressRequest } = useWalletProgress(connection); - const durability = useDurability(); - const exchanges = useWalletQuery( - connection, - WalletApiOperation.ListExchanges, - {}, - ); - const actionId = params?.actionId ?? ""; - const [prepared, setPrepared] = useState<{ - kind: "receive" | "pay"; - data: PreparePeerPushCreditResponse | PreparePeerPullDebitResponse; - }>(); + const [prepared, setPrepared] = useState<PreparedPeerPayment>(); const [kind, setKind] = useState<"receive" | "pay">("receive"); const [loading, setLoading] = useState(true); - const [working, setWorking] = useState(false); const [cancelling, setCancelling] = useState(false); const [error, setError] = useState<ErrorPresentation>(); - const [requiredExchangeUrl, setRequiredExchangeUrl] = useState<string>(); - const [requiredKeyRecovery, setRequiredKeyRecovery] = - useState<ExchangeKeyRecovery>(); useEffect(() => { let active = true; - setPrepared(undefined); - setKind("receive"); - setLoading(true); - setWorking(false); - setCancelling(false); - setError(undefined); - setRequiredExchangeUrl(undefined); - setRequiredKeyRecovery(undefined); void (async () => { try { const entry = await platform.actionInbox.get(actionId); + if (!active) return; if (!entry) throw Error( /* Translators: Peer payments transfer digital cash between people using links. A shared link can offer money to receive or request money to be paid. */ i18n.str`This peer payment expired or was already completed.`, @@ -2247,32 +2235,39 @@ function PeerReceiveRoute() { throw Error( /* Translators: Peer payments transfer digital cash between people using links. A shared link can offer money to receive or request money to be paid. */ i18n.str`This is not a supported peer payment link.`, ); - const kind = - parsed.value.type === TalerUriAction.PayPush ? "receive" : "pay"; - if (active) setKind(kind); - const result = - kind === "receive" - ? await progressRequest.callAndInvalidate( - WalletApiOperation.PreparePeerPushCredit, - { talerUri: entry.uri }, - ["transactions", "exchanges"], - ) - : await progressRequest.callAndInvalidate( - WalletApiOperation.PreparePeerPullDebit, - { talerUri: entry.uri }, - ["transactions", "exchanges"], - ); - if (Result.isError(result)) { - if (active) + if (parsed.value.type === TalerUriAction.PayPush) { + setKind("receive"); + const result = await progressRequest.callAndInvalidate( + WalletApiOperation.PreparePeerPushCredit, + { talerUri: entry.uri }, + ["transactions", "exchanges"], + ); + if (!active) return; + if (Result.isError(result)) setError( walletErrorHint( result.detail, /* Translators: Peer payments transfer digital cash between people using links. A shared link can offer money to receive or request money to be paid. */ i18n.str`The wallet could not prepare this peer payment.`, ), ); - return; + else setPrepared({ kind: "receive", data: result.value }); + } else { + setKind("pay"); + const result = await progressRequest.callAndInvalidate( + WalletApiOperation.PreparePeerPullDebit, + { talerUri: entry.uri }, + ["transactions", "exchanges"], + ); + if (!active) return; + if (Result.isError(result)) + setError( + walletErrorHint( + result.detail, + /* Translators: Peer payments transfer digital cash between people using links. A shared link can offer money to receive or request money to be paid. */ i18n.str`The wallet could not prepare this peer payment.`, + ), + ); + else setPrepared({ kind: "pay", data: result.value }); } - if (active) setPrepared({ kind, data: result.value }); } catch (cause) { if (active && !isProgressRequestCancelled(cause)) setError( @@ -2326,124 +2321,211 @@ function PeerReceiveRoute() { } navigate("/"); }; + + const shared = { + actionId, + cancelling, + cancellationError: error, + onCancel: () => void cancel(), + }; + // Full contract terms remain owned by preparation for document use. The observed + // view receives only the transaction ID, never a second copy of display fields. + if (prepared?.kind === "receive") + return ( + <PeerPushReceiveReview + key={prepared.data.transactionId} + {...shared} + transactionId={prepared.data.transactionId} + /> + ); + if (prepared?.kind === "pay") + return ( + <PeerPullDebitReview + key={prepared.data.transactionId} + {...shared} + prepared={prepared.data} + /> + ); + return ( + <PeerReceiveScreen + kind={kind} + loading={loading} + working={false} + cancelling={cancelling} + error={error} + onConfirm={() => {}} + onCancel={shared.onCancel} + onWithdraw={() => navigate("/withdraw")} + /> + ); +} + +interface PeerReviewActions { + actionId: string; + cancelling: boolean; + cancellationError?: ErrorPresentation; + onCancel: () => void; +} + +function usePeerPaymentConfirmation( + actionId: string, + request: () => Promise<Result<{ transactionId: TransactionIdStr }, unknown>>, +) { + const { platform } = useServices(); + const [, navigate] = useLocation(); + const durability = useDurability(); + const [working, setWorking] = useState(false); + const [error, setError] = useState<ErrorPresentation>(); const confirm = async () => { - if (!prepared || gate || trustCheckPending) return; - if (!(await durability.guardValueOperation())) return; + if (working || !(await durability.guardValueOperation())) return; setWorking(true); setError(undefined); try { - const result = - prepared.kind === "receive" - ? await progressRequest.callAndInvalidate( - WalletApiOperation.ConfirmPeerPushCredit, - { transactionId: prepared.data.transactionId }, - ["balances", "transactions"], - ) - : await callMutation( - WalletApiOperation.ConfirmPeerPullDebit, - { transactionId: prepared.data.transactionId }, - ["balances", "transactions"], - ); - if (Result.isError(result)) { - const tosExchangeUrl = exchangeTosErrorUrl(result.detail); - const keyRecovery = exchangeKeyRecoveryFromError(result.detail); - if (prepared.kind === "receive" && keyRecovery) { - setRequiredKeyRecovery(keyRecovery); - } else if (prepared.kind === "receive" && tosExchangeUrl) { - setRequiredExchangeUrl(tosExchangeUrl); - } else { - setError( - walletErrorHint( - result.detail, - /* Translators: Peer payments transfer digital cash between people using links. A shared link can offer money to receive or request money to be paid. */ i18n.str`The wallet could not confirm this peer payment.`, - ), - ); - } - } else { + const result = await request(); + if (Result.isError(result)) + setError( + walletErrorHint( + result.detail, + /* Translators: Peer payments transfer digital cash between people using links. A shared link can offer money to receive or request money to be paid. */ i18n.str`The wallet could not confirm this peer payment.`, + ), + ); + else { navigate(`/transaction/${result.value.transactionId}`); void completeActionBestEffort(platform.actionInbox, actionId); } } catch (cause) { if (!isProgressRequestCancelled(cause)) setError( - errorFromException( - cause, - /* Translators: Peer payments transfer digital cash between people using links. A shared link can offer money to receive or request money to be paid. */ i18n.str`Peer payment confirmation failed`, - ), + errorFromException(cause, i18n.str`Peer payment confirmation failed`), ); } finally { setWorking(false); } }; - const expiration = prepared?.data.contractTerms.purse_expiration.t_s; - const expirationLabel = - typeof expiration === "number" - ? new Intl.DateTimeFormat(language, { - dateStyle: "medium", - timeStyle: "short", - }).format(new Date(expiration * 1000)) - : undefined; - const preparedExchangeUrl = prepared?.data.exchangeBaseUrl; - const managedExchange = preparedExchangeUrl - ? exchanges.data?.exchanges.find( - (exchange) => exchange.exchangeBaseUrl === preparedExchangeUrl, - ) + return { working, error, confirm }; +} + +function peerExpirationLabel( + expiration: TalerProtocolTimestamp | undefined, + language: string, +): string | undefined { + return typeof expiration?.t_s === "number" + ? new Intl.DateTimeFormat(language, { + dateStyle: "medium", + timeStyle: "short", + }).format(new Date(expiration.t_s * 1000)) : undefined; - const gate = requiredKeyRecovery - ? undefined - : prepared?.kind === "receive" - ? requiredExchangeUrl - ? peerReceiveExchangeGate(false, ExchangeTosStatus.Proposed) - : managedExchange - ? peerReceiveExchangeGate( - Boolean(managedExchange.unconfirmedKeyChange), - managedExchange.tosStatus, - ) - : undefined - : undefined; - const trustCheckPending = - prepared?.kind === "receive" && !requiredExchangeUrl && exchanges.isLoading; +} + +function PeerPushReceiveReview( + props: PeerReviewActions & { transactionId: TransactionIdStr }, +) { + const { connection } = useServices(); + const { language } = useLanguage(); + const [, navigate] = useLocation(); + const { controller: progressRequest } = useWalletProgress(connection); + const { state, retry } = usePeerCreditObservation( + connection, + props.transactionId, + ); + const snapshot = state.status === "deleted" ? undefined : state.snapshot; + const { working, error, confirm } = usePeerPaymentConfirmation( + props.actionId, + () => + progressRequest.callAndInvalidate( + WalletApiOperation.ConfirmPeerPushCredit, + { transactionId: props.transactionId }, + ["balances", "transactions"], + ), + ); + const confirmation = peerCreditConfirmationView( + state, + `/peer-receive/${props.actionId}`, + error, + ); return ( <PeerReceiveScreen - kind={prepared?.kind ?? kind} - loading={loading} + kind="receive" + loading={state.status === "loading" && !snapshot} working={working} - cancelling={cancelling} - error={error} - blockedReason={ - requiredKeyRecovery?.message ?? - gate?.reason ?? - (trustCheckPending - ? i18n.str`Checking this exchange's terms and signing keys…` + cancelling={props.cancelling} + confirmDisabled={!confirmation.enabled} + error={ + props.cancellationError ?? + error ?? + (state.status === "failed" + ? errorFromException( + state.error, + i18n.str`Transaction updates stopped.`, + ) : undefined) } - blockedActionLabel={requiredKeyRecovery?.actionLabel ?? gate?.label} - amountRaw={prepared?.data.amountRaw} - amountEffective={prepared?.data.amountEffective} - summary={prepared?.data.contractTerms.summary} - expiration={expirationLabel} - exchange={prepared?.data.exchangeBaseUrl} - onConfirm={() => void confirm()} + onRetryObservation={state.status === "failed" ? retry : undefined} + blockedReason={ + confirmation.enabled || (state.status === "loading" && !snapshot) + ? undefined + : confirmation.reason + } + blockedActionLabel={ + confirmation.enabled ? undefined : confirmation.recovery?.label + } onResolveBlock={ - requiredKeyRecovery - ? () => - navigate( - exchangeRecoveryRoute( - requiredKeyRecovery, - `/peer-receive/${actionId}`, - ), - ) - : gate && (requiredExchangeUrl ?? preparedExchangeUrl) - ? () => { - window.location.hash = exchangeGateRoute( - requiredExchangeUrl ?? preparedExchangeUrl!, - gate.route, - `/peer-receive/${actionId}`, - ); - } - : undefined + !confirmation.enabled && confirmation.recovery + ? () => navigate(confirmation.recovery!.href) + : undefined } - onCancel={() => void cancel()} + amountRaw={snapshot?.transaction.amountRaw} + amountEffective={snapshot?.transaction.amountEffective} + summary={snapshot?.transaction.info.summary} + exchange={snapshot?.transaction.exchangeBaseUrl} + expiration={peerExpirationLabel( + snapshot?.transaction.info.expiration, + language, + )} + onConfirm={() => { + if (confirmation.enabled && !props.cancelling) void confirm(); + }} + onCancel={props.onCancel} + onWithdraw={() => navigate("/withdraw")} + /> + ); +} + +function PeerPullDebitReview( + props: PeerReviewActions & { prepared: PreparePeerPullDebitResponse }, +) { + const { connection } = useServices(); + const { language } = useLanguage(); + const [, navigate] = useLocation(); + const callMutation = useWalletMutation(connection); + const { working, error, confirm } = usePeerPaymentConfirmation( + props.actionId, + () => + callMutation( + WalletApiOperation.ConfirmPeerPullDebit, + { transactionId: props.prepared.transactionId }, + ["balances", "transactions"], + ), + ); + return ( + <PeerReceiveScreen + kind="pay" + loading={false} + working={working} + cancelling={props.cancelling} + error={props.cancellationError ?? error} + amountRaw={props.prepared.amountRaw} + amountEffective={props.prepared.amountEffective} + summary={props.prepared.contractTerms.summary} + expiration={peerExpirationLabel( + props.prepared.contractTerms.purse_expiration, + language, + )} + exchange={props.prepared.exchangeBaseUrl} + onConfirm={() => { + if (!props.cancelling) void confirm(); + }} + onCancel={props.onCancel} onWithdraw={() => navigate("/withdraw")} /> ); diff --git a/packages/wallet-webui/src/routes/exchange-gate-model.ts b/packages/wallet-webui/src/routes/exchange-gate-model.ts @@ -10,15 +10,13 @@ export interface ExchangeActionGate { function exchangeActionGate( hasUnconfirmedKeyChange: boolean, tosStatus: ExchangeTosStatus | undefined, - action: "withdrawal" | "request" | "receive", + action: "withdrawal" | "request", ): ExchangeActionGate | undefined { if (hasUnconfirmedKeyChange) { const reason = action === "withdrawal" ? /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`This exchange changed its signing keys. Verify that change before withdrawing.` - : action === "request" - ? /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`This exchange changed its signing keys. Verify that change before creating this request.` - : /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`This exchange changed its signing keys. Verify that change before receiving this payment.`; + : /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`This exchange changed its signing keys. Verify that change before creating this request.`; return { reason, label: i18n.str`Verify key change`, @@ -33,9 +31,7 @@ function exchangeActionGate( const reason = action === "withdrawal" ? /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`Review and accept this exchange's terms of service before withdrawing.` - : action === "request" - ? /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`Review and accept this exchange's terms of service before creating this request.` - : /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`Review and accept this exchange's terms of service before receiving this payment.`; + : /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`Review and accept this exchange's terms of service before creating this request.`; return { reason, label: i18n.str`Review terms`, @@ -58,10 +54,3 @@ export function peerRequestExchangeGate( ): ExchangeActionGate | undefined { return exchangeActionGate(hasUnconfirmedKeyChange, tosStatus, "request"); } - -export function peerReceiveExchangeGate( - hasUnconfirmedKeyChange: boolean, - tosStatus: ExchangeTosStatus | undefined, -): ExchangeActionGate | undefined { - return exchangeActionGate(hasUnconfirmedKeyChange, tosStatus, "receive"); -} diff --git a/packages/wallet-webui/src/screens/PeerReceiveScreen.tsx b/packages/wallet-webui/src/screens/PeerReceiveScreen.tsx @@ -15,6 +15,8 @@ export function PeerReceiveScreen(props: { expiration?: string; exchange?: string; error?: ErrorPresentation; + onRetryObservation?: () => void; + confirmDisabled?: boolean; blockedReason?: string; blockedActionLabel?: string; onConfirm: () => void; @@ -57,6 +59,11 @@ export function PeerReceiveScreen(props: { )} {props.error && ( <ErrorCard error={props.error}> + {props.onRetryObservation && ( + <Button + onClick={props.onRetryObservation} + >{i18n.str`Retry updates`}</Button> + )} {!receive && ( <div class="mt-4"> <Button @@ -67,6 +74,21 @@ export function PeerReceiveScreen(props: { )} </ErrorCard> )} + {props.blockedReason && ( + <Card class="border-warning bg-warningContainer"> + <p role="alert" class="text-onWarningContainer"> + {props.blockedReason} + </p> + {props.onResolveBlock && ( + <div class="mt-4"> + <Button tone="secondary" onClick={props.onResolveBlock}> + {props.blockedActionLabel ?? + i18n.str`Resolve exchange requirement`} + </Button> + </div> + )} + </Card> + )} {!props.loading && props.amountEffective && ( <> <Card class="text-center"> @@ -101,21 +123,6 @@ export function PeerReceiveScreen(props: { )} </dl> </Card> - {props.blockedReason && ( - <Card class="border-warning bg-warningContainer"> - <p role="alert" class="text-onWarningContainer"> - {props.blockedReason} - </p> - {props.onResolveBlock && ( - <div class="mt-4"> - <Button tone="secondary" onClick={props.onResolveBlock}> - {props.blockedActionLabel ?? - i18n.str`Resolve exchange requirement`} - </Button> - </div> - )} - </Card> - )} <div class="flex justify-end gap-3"> <Button tone="secondary" @@ -129,8 +136,8 @@ export function PeerReceiveScreen(props: { disabled={ props.working || props.cancelling || - Boolean(props.error) || - Boolean(props.blockedReason) + (props.confirmDisabled ?? + (Boolean(props.error) || Boolean(props.blockedReason))) } > {props.working diff --git a/packages/wallet-webui/test/peer-credit-observation.test.tsx b/packages/wallet-webui/test/peer-credit-observation.test.tsx @@ -0,0 +1,461 @@ +/* + This file is part of GNU Taler + (C) 2026 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU Affero General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along + with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. + */ + +import assert from "node:assert/strict"; +import test from "node:test"; +import { register } from "node:module"; +import { Window } from "happy-dom"; +import { + NotificationType, + ExchangeTosStatus, + type PeerPushCreditSnapshotNotification, + type WalletNotification, + ObservationType, + Result, + TalerError, + TalerErrorCode, + type TransactionIdStr, +} from "@gnu-taler/taler-util"; +import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; +import { + createDemoServices, + demoActionUris, +} from "../src/testing/demo-wallet.js"; +import type { ActionEntry } from "../src/api/contracts.js"; + +// Match the browser bundle's React alias when rendering SWR-backed routes. +register( + `data:text/javascript,${encodeURIComponent(` + export async function resolve(specifier, context, nextResolve) { + if (specifier === "react" || specifier === "use-sync-external-store/shim/index.js") return { url: ${JSON.stringify(import.meta.resolve("preact/compat"))}, shortCircuit: true }; + return nextResolve(specifier, context); + } +`)}`, + import.meta.url, +); + +async function harness( + source: ActionEntry["source"], + mode: + | "normal" + | "failure" + | "delayed" + | "snapshot-delayed" + | "pull" = "normal", +) { + const dom = new Window({ url: "https://wallet.example/" }); + for (const key of [ + "window", + "document", + "navigator", + "location", + "history", + "localStorage", + "sessionStorage", + "HTMLElement", + "Element", + "Node", + "Event", + "MutationObserver", + ] as const) { + Object.defineProperty(globalThis, key, { + configurable: true, + writable: true, + value: key === "window" ? dom : dom[key], + }); + } + for (const key of [ + "addEventListener", + "removeEventListener", + "dispatchEvent", + ] as const) + Object.defineProperty(globalThis, key, { + configurable: true, + writable: true, + value: dom[key].bind(dom), + }); + const { render, cleanup, act } = await import("@testing-library/preact"); + const { SWRConfig } = await import("swr"); + const { App } = await import("../src/routes/App.js"); + const services = createDemoServices(); + const subscribe = services.connection.subscribeNotifications.bind( + services.connection, + ); + // Core may allow confirmation despite cached ToS status (e.g. ignore-ToS mode). + // The route must use core's blockers instead of reconstructing eligibility. + let holdSnapshots = mode === "snapshot-delayed"; + const pendingSnapshots: (() => void)[] = []; + let latest: PeerPushCreditSnapshotNotification | undefined; + const listeners = new Set<(n: WalletNotification) => void>(); + services.connection.subscribeNotifications = (listener) => { + listeners.add(listener); + const unsubscribe = subscribe((n) => { + if ( + n.type === NotificationType.ObservationSnapshot && + n.snapshot?.exchange + ) { + const value: PeerPushCreditSnapshotNotification = { + ...n, + snapshot: { + ...n.snapshot, + transaction: { + ...n.snapshot.transaction, + ...(mode === "snapshot-delayed" + ? { + amountEffective: "CHF:8", + info: { + ...n.snapshot.transaction.info, + summary: "Observed lunch", + }, + } + : {}), + }, + exchange: { + ...n.snapshot.exchange, + tosStatus: ExchangeTosStatus.Proposed, + }, + }, + }; + latest = value; + if (holdSnapshots) pendingSnapshots.push(() => listener(value)); + else listener(value); + } else listener(n); + }); + return () => { + listeners.delete(listener); + unsubscribe(); + }; + }; + const entry = await services.platform.actionInbox.put( + demoActionUris["peer-receive"], + source, + ); + if (mode === "pull") { + const get = services.platform.actionInbox.get.bind( + services.platform.actionInbox, + ); + services.platform.actionInbox.get = async (id) => { + const item = await get(id); + return item + ? { ...item, uri: item.uri.replace("pay-push", "pay-pull") } + : undefined; + }; + } + dom.location.hash = `#/peer-receive/${entry.id}`; + const calls: string[] = []; + const originalCall = services.connection.client.call; + services.connection.client.call = async (operation, request) => { + calls.push(operation); + return originalCall(operation, request); + }; + const mutations: string[] = []; + let prepares = 0; + let confirms = 0; + let release!: () => void; + const gate = new Promise<void>((resolve) => { + release = resolve; + }); + const original = services.connection.client.callForResult; + services.connection.client.callForResult = async (operation, request) => { + mutations.push(operation); + if ( + mode === "pull" && + operation === WalletApiOperation.PreparePeerPullDebit + ) { + prepares++; + return Result.of({ + transactionId: "txn:peer-pull-debit:test" as TransactionIdStr, + amountRaw: "CHF:3", + amountEffective: "CHF:3.1", + exchangeBaseUrl: "https://exchange.example/", + contractTerms: { + summary: "Requested lunch", + purse_expiration: { t_s: 2000000000 }, + }, + }) as never; + } + if ( + mode === "pull" && + operation === WalletApiOperation.ConfirmPeerPullDebit + ) { + confirms++; + return Result.of({ transactionId: "txn:peer-pull-debit:test" }) as never; + } + if (operation === WalletApiOperation.PreparePeerPushCredit) { + prepares++; + if (mode === "failure" && prepares === 1) + throw Error("preparation unavailable"); + if (mode === "delayed") await gate; + } + if (operation === WalletApiOperation.ConfirmPeerPushCredit) confirms++; + return original(operation, request); + }; + const view = render( + <SWRConfig value={{ provider: () => new Map(), shouldRetryOnError: false }}> + <App {...services} /> + </SWRConfig>, + ); + const waitFor = async (check: () => void) => { + for (let n = 0; ; n++) { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + }); + try { + check(); + return; + } catch (error) { + if (n >= 200) throw error; + } + } + }; + return { + view, + entry, + services, + calls, + mutations, + act, + waitFor, + release, + releaseSnapshots: () => { + holdSnapshots = false; + for (const send of pendingSnapshots.splice(0)) send(); + }, + failObserved: () => { + assert.ok(latest); + for (const listener of listeners) + listener({ + type: NotificationType.ObservationError, + observationType: ObservationType.PeerPushCredit, + observationId: latest.observationId, + error: { code: 1, hint: "read failed" }, + }); + }, + deleteObserved: () => { + assert.ok(latest); + for (const listener of listeners) + listener({ ...latest, revision: latest.revision + 1, snapshot: null }); + }, + counts: () => ({ prepares, confirms }), + dom, + close: async () => { + cleanup(); + services.connection.close(); + await dom.happyDOM.abort(); + }, + }; +} + +test("preparation values stay hidden until the first snapshot, and deletion never restores them", async () => { + const h = await harness("paste", "snapshot-delayed"); + try { + await h.waitFor(() => + assert(h.calls.includes(WalletApiOperation.ObservePeerPushCredit)), + ); + assert.equal(h.view.queryByText("CHF:7.00"), null); + assert.equal(h.view.queryByText("Shared lunch"), null); + assert(h.view.getByText("Loading payment details…")); + await h.act(async () => h.releaseSnapshots()); + await h.waitFor(() => assert(h.view.getByText("Observed lunch"))); + assert(h.view.getByText("CHF:8")); + await h.act(async () => h.deleteObserved()); + await h.waitFor(() => + assert(h.view.getByText("This peer payment no longer exists.")), + ); + assert.equal(h.view.queryByText("Observed lunch"), null); + assert.equal(h.view.queryByText("Shared lunch"), null); + assert.equal(h.view.queryByRole("button", { name: "Receive money" }), null); + } finally { + await h.close(); + } +}); + +test("preparation failure stays in preparation without registering an observer", async () => { + const h = await harness("paste", "failure"); + try { + await h.waitFor(() => assert.equal(h.counts().prepares, 1)); + await h.waitFor(() => assert(h.view.getByRole("alert"))); + assert.equal( + h.calls.includes(WalletApiOperation.ObservePeerPushCredit), + false, + ); + } finally { + await h.close(); + } +}); + +test("cancelling preparation ignores its late result", async () => { + const h = await harness("paste", "delayed"); + try { + await h.waitFor(() => assert.equal(h.counts().prepares, 1)); + await h.act(async () => + h.view.getByRole("button", { name: "Cancel peer payment" }).click(), + ); + await h.waitFor(() => + assert(!h.dom.location.hash.includes("peer-receive")), + ); + await h.act(async () => h.release()); + await h.waitFor(() => + assert.equal( + h.calls.includes(WalletApiOperation.CancelProgressToken), + true, + ), + ); + assert.equal( + h.calls.includes(WalletApiOperation.ObservePeerPushCredit), + false, + ); + assert.equal( + h.view.queryByRole("heading", { name: "Receive money" }), + null, + ); + } finally { + await h.close(); + } +}); + +test("cancelling a prepared receipt aborts the transaction and stops observation", async () => { + const h = await harness("paste"); + try { + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Receive money" })), + ); + await h.act(async () => + h.view.getByRole("button", { name: "Cancel", exact: true }).click(), + ); + await h.waitFor(() => + assert(!h.dom.location.hash.includes("peer-receive")), + ); + assert(h.calls.includes(WalletApiOperation.StopObservation)); + assert(h.mutations.includes(WalletApiOperation.AbortTransaction)); + } finally { + await h.close(); + } +}); + +test("peer-pull review keeps using its preparation response without an observation", async () => { + const h = await harness("paste", "pull"); + try { + await h.waitFor(() => assert(h.view.getByRole("button", { name: "Pay" }))); + assert(h.view.getByText("Requested lunch")); + assert(h.view.getByText("CHF:3.1")); + assert.equal( + h.calls.includes(WalletApiOperation.ObservePeerPushCredit), + false, + ); + await h.act(async () => + h.view.getByRole("button", { name: "Pay" }).click(), + ); + await h.waitFor(() => assert.equal(h.counts().confirms, 1)); + assert(h.mutations.includes(WalletApiOperation.ConfirmPeerPullDebit)); + await h.waitFor(() => + assert.equal( + h.dom.location.hash, + "#/transaction/txn:peer-pull-debit:test", + ), + ); + assert.equal( + await h.services.platform.actionInbox.get(h.entry.id), + undefined, + ); + } finally { + await h.close(); + } +}); + +for (const mode of ["normal", "pull"] as const) + for (const failure of ["wallet", "exception"] as const) + test(`${mode} confirmation ${failure} keeps the review and inbox action`, async () => { + const h = await harness("paste", mode); + try { + const name = mode === "normal" ? "Receive money" : "Pay"; + const operation = + mode === "normal" + ? WalletApiOperation.ConfirmPeerPushCredit + : WalletApiOperation.ConfirmPeerPullDebit; + const original = h.services.connection.client.callForResult; + h.services.connection.client.callForResult = async (op, request) => { + if (op !== operation) return original(op, request); + if (failure === "exception") throw Error("confirmation unavailable"); + return Result.errorWithDetail("network", { + code: TalerErrorCode.WALLET_NETWORK_ERROR, + }) as never; + }; + await h.waitFor(() => assert(h.view.getByRole("button", { name }))); + const route = h.dom.location.hash; + await h.act(async () => h.view.getByRole("button", { name }).click()); + await h.waitFor(() => assert(h.view.getByRole("alert"))); + assert.equal(h.dom.location.hash, route); + assert(await h.services.platform.actionInbox.get(h.entry.id)); + assert.equal( + h.view.queryByRole("button", { name: "Confirming…" }), + null, + ); + if (failure === "wallet") + assert(h.view.getByText("The wallet could not reach the service.")); + else assert(h.view.getByText("Peer payment confirmation failed")); + } finally { + await h.close(); + } + }); + +test("cancelled push confirmation can be retried without completing the inbox action", async () => { + const h = await harness("paste"); + try { + const original = h.services.connection.client.callForResult; + let cancelled = false; + h.services.connection.client.callForResult = async (operation, request) => { + if ( + operation === WalletApiOperation.ConfirmPeerPushCredit && + !cancelled + ) { + cancelled = true; + throw TalerError.fromDetail( + TalerErrorCode.WALLET_CORE_REQUEST_CANCELLED, + {}, + ); + } + return original(operation, request); + }; + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Receive money" })), + ); + const route = h.dom.location.hash; + await h.act(async () => + h.view.getByRole("button", { name: "Receive money" }).click(), + ); + await h.waitFor(() => { + assert(cancelled); + const button = h.view.getByRole("button", { + name: "Receive money", + }) as HTMLButtonElement; + assert.equal(button.disabled, false); + }); + assert.equal(h.view.queryByRole("alert"), null); + assert.equal(h.dom.location.hash, route); + assert(await h.services.platform.actionInbox.get(h.entry.id)); + await h.act(async () => + h.view.getByRole("button", { name: "Receive money" }).click(), + ); + await h.waitFor(() => assert(h.view.getAllByText("Completed").length)); + assert.equal( + await h.services.platform.actionInbox.get(h.entry.id), + undefined, + ); + } finally { + await h.close(); + } +}); diff --git a/packages/wallet-webui/test/routing.test.ts b/packages/wallet-webui/test/routing.test.ts @@ -3,7 +3,6 @@ import test from "node:test"; import { ExchangeTosStatus } from "@gnu-taler/taler-util"; import { hashQueryValue, walletRoutePath } from "../src/routes/App.js"; import { - peerReceiveExchangeGate, peerRequestExchangeGate, withdrawalExchangeGate, } from "../src/routes/exchange-gate-model.js"; @@ -19,19 +18,6 @@ test("hash route matching ignores flow query parameters", () => { assert.equal(walletRoutePath("/"), "/"); }); -test("peer receipt exchange gates ask for terms before accepting money", () => { - assert.equal( - peerReceiveExchangeGate(false, ExchangeTosStatus.Accepted), - undefined, - ); - assert.deepEqual(peerReceiveExchangeGate(false, ExchangeTosStatus.Proposed), { - reason: - "Review and accept this exchange's terms of service before receiving this payment.", - label: "Review terms", - route: "terms", - }); -}); - test("peer request exchange gates use request-specific recovery copy", () => { assert.equal( peerRequestExchangeGate(false, ExchangeTosStatus.Accepted),