taler-typescript-core

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

commit 9412b54c7eade1da709cf8effbf8b2f75d5d42c5
parent bf2e571a281b1cec26f5921077b0d7fa79703539
Author: Florian Dold <dold@taler.net>
Date:   Wed, 11 Nov 2026 11:38:57 +0100

wallet-webui: observe transaction details

Diffstat:
Mpackages/wallet-webui/src/api/observations.ts | 176++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mpackages/wallet-webui/src/platform/observation-owner.ts | 2+-
Mpackages/wallet-webui/src/routes/App.tsx | 637+++++++++++++++++++++++++------------------------------------------------------
Mpackages/wallet-webui/src/routes/exchange-key-recovery-model.ts | 9+++++++--
Apackages/wallet-webui/src/routes/payment-actions.ts | 330+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/routes/payment-model.ts | 30++++++++++++------------------
Mpackages/wallet-webui/src/routes/peer-credit-review-model.ts | 28++++++++++++++++++++++------
Mpackages/wallet-webui/src/routes/transaction-model.ts | 46+++++++++++++++++++---------------------------
Mpackages/wallet-webui/src/routes/withdrawal-model.ts | 8++++----
Mpackages/wallet-webui/src/screens/PaymentScreen.tsx | 37+++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/src/screens/PeerShareScreen.tsx | 18++++++++++++++++++
Mpackages/wallet-webui/src/screens/TransactionDetailScreen.tsx | 23+++++++++++++++++++++--
Mpackages/wallet-webui/src/testing/demo-wallet.ts | 135+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Mpackages/wallet-webui/test/observations-hook.test.tsx | 233+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mpackages/wallet-webui/test/observations.test.ts | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mpackages/wallet-webui/test/payment-model.test.ts | 34+++++++++++++++++-----------------
Mpackages/wallet-webui/test/peer-credit-observation.test.tsx | 243+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mpackages/wallet-webui/test/peer-credit-review-model.test.ts | 41++++++++++++++++++++++++++++++++++++++---
Mpackages/wallet-webui/test/transaction-model.test.ts | 90+++++++++++++++++++++++++++++++++----------------------------------------------
Apackages/wallet-webui/test/transaction-observation-routes.test.tsx | 586+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
20 files changed, 2139 insertions(+), 685 deletions(-)

diff --git a/packages/wallet-webui/src/api/observations.ts b/packages/wallet-webui/src/api/observations.ts @@ -6,7 +6,10 @@ import { NotificationType, - type PeerPushCreditSnapshot, + type TransactionSnapshot, + TransactionType, + type ObservedPaymentTransaction, + type MerchantContractTerms, type TransactionIdStr, } from "@gnu-taler/taler-util"; import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; @@ -14,16 +17,16 @@ import { useEffect, useRef, useState } from "preact/hooks"; import type { WalletConnection } from "./contracts.js"; import { i18n } from "../i18n/runtime.js"; -export type PeerCreditObservationState = - | { status: "loading"; snapshot?: PeerPushCreditSnapshot } - | { status: "ready"; snapshot: PeerPushCreditSnapshot } - | { status: "disconnected"; snapshot?: PeerPushCreditSnapshot } - | { status: "failed"; error: Error; snapshot?: PeerPushCreditSnapshot } +export type TransactionObservationState = + | { status: "loading"; snapshot?: TransactionSnapshot } + | { status: "ready"; snapshot: TransactionSnapshot } + | { status: "disconnected"; snapshot?: TransactionSnapshot } + | { status: "failed"; error: Error; snapshot?: TransactionSnapshot } | { status: "deleted" }; /** Owns one UI subscription; registration acknowledgements never carry state. */ -export class PeerCreditObservation { - state: PeerCreditObservationState = { status: "loading" }; +export class TransactionObservation { + state: TransactionObservationState = { status: "loading" }; private id?: string; private revision = 0; private connected = false; @@ -34,7 +37,7 @@ export class PeerCreditObservation { constructor( private connection: WalletConnection, private transactionId: TransactionIdStr, - private changed: (state: PeerCreditObservationState) => void, + private changed: (state: TransactionObservationState) => void, private newId: () => string = () => crypto.randomUUID(), ) { this.unsubscribeNotifications = connection.subscribeNotifications((n) => { @@ -47,7 +50,7 @@ export class PeerCreditObservation { return; if ( n.type === NotificationType.ObservationSnapshot && - n.observationType === "peer-push-credit" + n.observationType === "transaction" ) { if ( n.transactionId !== this.transactionId || @@ -91,7 +94,7 @@ export class PeerCreditObservation { return this.state.status === "deleted" ? undefined : this.state.snapshot; } - private update(state: PeerCreditObservationState) { + private update(state: TransactionObservationState) { this.state = state; if (!this.disposed) this.changed(state); } @@ -113,7 +116,7 @@ export class PeerCreditObservation { this.revision = 0; this.update({ status: "loading", snapshot: this.snapshot() }); void this.connection.client - .call(WalletApiOperation.ObservePeerPushCredit, { + .call(WalletApiOperation.ObserveTransaction, { transactionId: this.transactionId, observationId: id, }) @@ -144,18 +147,29 @@ export class PeerCreditObservation { } } -export function usePeerCreditObservation( +export interface TransactionObservationView { + state: TransactionObservationState; + snapshot?: TransactionSnapshot; + error?: Error; + ready: boolean; + loading: boolean; + canRetry: boolean; + retry: () => void; +} + +export function useTransactionObservation( connection: WalletConnection, - transactionId: TransactionIdStr, -) { + transactionId: TransactionIdStr | undefined, +): TransactionObservationView { const [value, setValue] = useState<{ connection: WalletConnection; transactionId: TransactionIdStr; - state: PeerCreditObservationState; + state: TransactionObservationState; }>(); - const controller = useRef<PeerCreditObservation>(); + const controller = useRef<TransactionObservation>(); useEffect(() => { - const instance = new PeerCreditObservation( + if (!transactionId) return; + const instance = new TransactionObservation( connection, transactionId, (state) => setValue({ connection, transactionId, state }), @@ -166,9 +180,131 @@ export function usePeerCreditObservation( controller.current = undefined; }; }, [connection, transactionId]); - const state: PeerCreditObservationState = + const state: TransactionObservationState = value?.connection === connection && value.transactionId === transactionId ? value.state : { status: "loading" }; - return { state, retry: () => controller.current?.retry() }; + const snapshot = "snapshot" in state ? state.snapshot : undefined; + const error = + state.status === "failed" + ? state.error + : state.status === "deleted" + ? new Error(i18n.str`This transaction no longer exists.`) + : state.status === "disconnected" + ? new Error(i18n.str`Waiting for the wallet connection…`) + : undefined; + return { + state, + snapshot, + error, + ready: state.status === "ready", + loading: state.status === "loading" && !snapshot, + canRetry: state.status === "failed", + retry: () => controller.current?.retry(), + }; +} + +export interface PaymentContractView { + terms?: MerchantContractTerms; + error?: Error; + loading: boolean; + retry: () => void; +} + +/** Load only the document; transaction state always comes from the snapshot. */ +export function usePaymentContract( + connection: WalletConnection, + payment: ObservedPaymentTransaction | undefined, + ready: boolean, +): PaymentContractView { + const transactionId = payment?.transactionId; + const hash = payment?.info?.contractTermsHash; + const [document, setDocument] = useState<{ + connection: WalletConnection; + transactionId: string; + hash: string; + terms?: MerchantContractTerms; + error?: Error; + }>(); + const [documentAttempt, setDocumentAttempt] = useState(0); + const [connectionEpoch, setConnectionEpoch] = useState(0); + useEffect(() => { + if (!transactionId) return; + let connected: boolean | undefined; + return connection.subscribeStatus((status) => { + const next = status.state === "connected"; + if (next && connected === false) setConnectionEpoch((n) => n + 1); + connected = next; + }); + }, [connection, transactionId]); + useEffect(() => { + if (!transactionId || !hash || !ready) return; + if ( + document?.connection === connection && + document.transactionId === transactionId && + document.hash === hash && + document.terms + ) + return; + let active = true; + const target = { connection, transactionId, hash }; + setDocument({ ...target }); + void connection.client + .call(WalletApiOperation.GetTransactionById, { + transactionId, + includeContractTerms: true, + }) + .then( + (t) => { + if ( + active && + t.type === TransactionType.Payment && + t.transactionId === transactionId && + t.contractTerms && + t.info?.contractTermsHash === hash + ) + setDocument({ + ...target, + terms: t.contractTerms, + }); + else if (active) + setDocument({ + ...target, + error: new Error( + i18n.str`The payment contract details are unavailable.`, + ), + }); + }, + (error) => { + if (active) + setDocument({ + ...target, + error: error instanceof Error ? error : new Error(String(error)), + }); + }, + ); + return () => { + active = false; + }; + }, [ + connection, + transactionId, + hash, + documentAttempt, + connectionEpoch, + ready, + ]); + const current = + document && + document.connection === connection && + document.transactionId === transactionId && + document.hash === hash + ? document + : undefined; + return { + terms: current?.terms, + error: current?.error, + loading: !!hash && !current?.terms && !current?.error, + retry: () => setDocumentAttempt((n) => n + 1), + }; } diff --git a/packages/wallet-webui/src/platform/observation-owner.ts b/packages/wallet-webui/src/platform/observation-owner.ts @@ -25,7 +25,7 @@ export class ObservationOwner { const id = typeof args?.observationId === "string" ? args.observationId : undefined; const registering = - request.operation === WalletApiOperation.ObservePeerPushCredit && + request.operation === WalletApiOperation.ObserveTransaction && id !== undefined; const response = await this.dispatch(request); if (registering && response.type !== "error") { diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -1,5 +1,10 @@ +import { usePaymentActions } from "./payment-actions.js"; import { peerCreditConfirmationView } from "./peer-credit-review-model.js"; -import { usePeerCreditObservation } from "../api/observations.js"; +import { + useTransactionObservation, + usePaymentContract, + type TransactionObservationView, +} from "../api/observations.js"; import { ConfirmPayResultType, Amounts, @@ -18,23 +23,16 @@ import { } from "@gnu-taler/taler-util"; import type { AcceptManualWithdrawalResult, + PrepareBankIntegratedWithdrawalResponse, + TransactionPayment, AmountString, CheckDepositResponse, - PrepareBankIntegratedWithdrawalResponse, - PreparePeerPullDebitResponse, - PreparePeerPushCreditResponse, ScopeInfo, TalerProtocolTimestamp, TemplateParams, TransactionIdStr, - TransactionPayment, - TransactionPeerPullCredit, - TransactionPeerPushDebit, } from "@gnu-taler/taler-util"; -import { - WalletApiOperation, - parseTransactionIdentifier, -} from "@gnu-taler/taler-wallet-core"; +import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; import { useCallback, useEffect, useMemo, useState } from "preact/hooks"; import { useRef } from "preact/hooks"; import jsQR, * as jsQrTypes from "jsqr"; @@ -125,19 +123,19 @@ import { connectionStatus } from "../stores/ui.js"; import { activePaymentChoiceIndex, paymentConfirmationRequest, + paymentReviewView, paymentRepurchaseTarget, paymentResultState, - paymentReviewView, safeWebUrl, } from "./payment-model.js"; import { usePaymentFulfillment } from "./payment-fulfillment.js"; import { depositKycAuthWireOptions, + shouldPollIntegratedWithdrawal, + wireOptions, integratedWithdrawalView, isIntegratedWithdrawalTerminal, - shouldPollIntegratedWithdrawal, transactionWireOptions, - wireOptions, } from "./withdrawal-model.js"; import { transactionDetailView, @@ -2078,20 +2076,18 @@ function PeerShareRoute() { const [, navigate] = useLocation(); const transactionId = (params?.transactionId ?? "") as TransactionIdStr; const mode = params?.mode === "request" ? "request" : "send"; - const query = useWalletQuery( + const view = useTransactionObservation( connection, - WalletApiOperation.GetTransactionById, - { transactionId, includeContractTerms: false }, + transactionId as TransactionIdStr, ); - const transaction = query.data; + const transaction = view.snapshot?.transaction; const [actionError, setActionError] = useState<ErrorPresentation>(); const [retrying, setRetrying] = useState(false); const uri = transaction && (transaction.type === TransactionType.PeerPushDebit || transaction.type === TransactionType.PeerPullCredit) - ? (transaction as TransactionPeerPushDebit | TransactionPeerPullCredit) - .talerUri + ? transaction.talerUri : undefined; const terminalWithoutUri = transaction && @@ -2116,9 +2112,9 @@ function PeerShareRoute() { ); const error = actionError ? actionError - : query.error + : view.error ? errorFromException( - query.error, + view.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`The peer share link could not be loaded.`, ) : transaction && @@ -2132,7 +2128,10 @@ function PeerShareRoute() { /* 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 link is no longer available.`, ) : transactionProblem; - const loading = query.isLoading || (!uri && !error); + const preparingLink = + transaction?.txState.major === TransactionMajorState.Pending && + transaction.txState.minor === TransactionMinorState.CreatePurse; + const loading = view.loading || (!uri && !error && preparingLink); const [delayed, setDelayed] = useState(false); useEffect(() => { setDelayed(false); @@ -2171,9 +2170,15 @@ function PeerShareRoute() { }; return ( <PeerShareScreen + onRetryObservation={view.canRetry ? view.retry : undefined} mode={mode} uri={uri} loading={loading} + status={ + transaction && !uri && !loading && !error + ? transactionStateView(transaction) + : undefined + } delayed={delayed} error={error} retryable={retryable} @@ -2199,9 +2204,10 @@ function PeerShareRoute() { ); } -type PreparedPeerPayment = - | { kind: "receive"; data: PreparePeerPushCreditResponse } - | { kind: "pay"; data: PreparePeerPullDebitResponse }; +interface PreparedPeerPayment { + kind: "receive" | "pay"; + transactionId: TransactionIdStr; +} function PeerReceiveRoute() { const [, params] = useRoute("/peer-receive/:actionId"); @@ -2253,7 +2259,11 @@ function PeerPreparation({ actionId }: { actionId: string }) { /* 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: "receive", data: result.value }); + else + setPrepared({ + kind: "receive", + transactionId: result.value.transactionId, + }); } else { setKind("pay"); const result = await progressRequest.callAndInvalidate( @@ -2269,7 +2279,11 @@ function PeerPreparation({ actionId }: { actionId: string }) { /* 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 }); + else + setPrepared({ + kind: "pay", + transactionId: result.value.transactionId, + }); } } catch (cause) { if (active && !isProgressRequestCancelled(cause)) @@ -2297,7 +2311,7 @@ function PeerPreparation({ actionId }: { actionId: string }) { () => callMutation( WalletApiOperation.AbortTransaction, - { transactionId: prepared.data.transactionId }, + { transactionId: prepared.transactionId }, ["transactions"], ), () => void completeActionBestEffort(platform.actionInbox, actionId), @@ -2331,22 +2345,13 @@ function PeerPreparation({ actionId }: { actionId: string }) { 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") + if (prepared) return ( - <PeerPullDebitReview - key={prepared.data.transactionId} + <PeerPaymentReview + key={prepared.transactionId} {...shared} - prepared={prepared.data} + kind={prepared.kind} + transactionId={prepared.transactionId} /> ); return ( @@ -2420,61 +2425,72 @@ function peerExpirationLabel( : undefined; } -function PeerPushReceiveReview( - props: PeerReviewActions & { transactionId: TransactionIdStr }, -) { +function PeerPaymentReview(props: PeerReviewActions & PreparedPeerPayment) { 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 callMutation = useWalletMutation(connection); + const view = useTransactionObservation(connection, props.transactionId); + const expectedType = + props.kind === "receive" + ? TransactionType.PeerPushCredit + : TransactionType.PeerPullDebit; + const snapshot = + view.snapshot?.type === expectedType ? view.snapshot : undefined; + const unexpectedType = view.snapshot && !snapshot; const { working, error, confirm } = usePeerPaymentConfirmation( props.actionId, () => - progressRequest.callAndInvalidate( - WalletApiOperation.ConfirmPeerPushCredit, - { transactionId: props.transactionId }, - ["balances", "transactions"], - ), + props.kind === "receive" + ? progressRequest.callAndInvalidate( + WalletApiOperation.ConfirmPeerPushCredit, + { transactionId: props.transactionId }, + ["balances", "transactions"], + ) + : callMutation( + WalletApiOperation.ConfirmPeerPullDebit, + { transactionId: props.transactionId }, + ["balances", "transactions"], + ), ); const confirmation = peerCreditConfirmationView( - state, + view.state, `/peer-receive/${props.actionId}`, error, ); + const canConfirm = !!snapshot && confirmation.enabled; return ( <PeerReceiveScreen - kind="receive" - loading={state.status === "loading" && !snapshot} + kind={props.kind} + loading={view.loading} working={working} cancelling={props.cancelling} - confirmDisabled={!confirmation.enabled} + confirmDisabled={!canConfirm} error={ props.cancellationError ?? error ?? - (state.status === "failed" - ? errorFromException( - state.error, - i18n.str`Transaction updates stopped.`, - ) - : undefined) + (unexpectedType + ? localError(i18n.str`This is not a supported peer payment link.`) + : view.error + ? errorFromException( + view.error, + i18n.str`Transaction updates stopped.`, + ) + : undefined) } - onRetryObservation={state.status === "failed" ? retry : undefined} + onRetryObservation={view.canRetry ? view.retry : undefined} blockedReason={ - confirmation.enabled || (state.status === "loading" && !snapshot) - ? undefined - : confirmation.reason + confirmation.enabled || view.loading ? undefined : confirmation.reason } blockedActionLabel={ confirmation.enabled ? undefined : confirmation.recovery?.label } onResolveBlock={ !confirmation.enabled && confirmation.recovery - ? () => navigate(confirmation.recovery!.href) + ? () => { + window.location.hash = confirmation.recovery!.href; + } : undefined } amountRaw={snapshot?.transaction.amountRaw} @@ -2486,47 +2502,7 @@ function PeerPushReceiveReview( 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(); + if (canConfirm && !props.cancelling) void confirm(); }} onCancel={props.onCancel} onWithdraw={() => navigate("/withdraw")} @@ -4556,7 +4532,7 @@ function PaymentDialog(props: { () => choicesQuery.data ? paymentReviewView( - props.transaction, + choicesQuery.data.contractTerms, choicesQuery.data, donauQuery.data?.currentDonauInfo, language, @@ -5038,351 +5014,121 @@ function useTransactionActions(transactionId: TransactionIdStr) { function TransactionDetailRoute() { const [, params] = useRoute("/transaction/:transactionId"); const transactionId = (params?.transactionId ?? "") as TransactionIdStr; - return parseTransactionIdentifier(transactionId)?.tag === - TransactionType.PeerPushCredit ? ( - <PeerPushCreditDetailRoute - key={transactionId} - transactionId={transactionId} - /> - ) : ( - <QueriedTransactionDetailRoute + return ( + <ObservedTransactionDetailRoute key={transactionId} transactionId={transactionId} + showTransferInstructions={hashQueryValue("transfer") === "1"} /> ); } -function PeerPushCreditDetailRoute({ +function ObservedTransactionDetailRoute({ transactionId, + showTransferInstructions = false, }: { transactionId: TransactionIdStr; + showTransferInstructions?: boolean; }) { - const { connection, platform } = useServices(); - const { language } = useLanguage(); - const [, navigate] = useLocation(); - const { state, retry } = usePeerCreditObservation(connection, transactionId); - const snapshot = state.status === "deleted" ? undefined : state.snapshot; - const actions = useTransactionActions(transactionId); - const recovery = - exchangeKeyRecoveryFromError(actions.error?.detail) ?? - exchangeKeyRecoveryFromError(snapshot?.transaction.error); - const observationError = - state.status === "failed" - ? errorFromException(state.error, i18n.str`Transaction updates stopped.`) - : state.status === "disconnected" - ? localError(i18n.str`Waiting for the wallet connection…`) - : state.status === "deleted" - ? localError(i18n.str`This peer payment no longer exists.`) - : undefined; + const { connection } = useServices(); + const view = useTransactionObservation(connection, transactionId); return ( - <TransactionDetailScreen - transaction={ - snapshot - ? transactionDetailView(snapshot.transaction, language) - : undefined - } - loading={state.status === "loading" && !snapshot} - error={actions.error ?? observationError} - message={ - state.status === "loading" && snapshot - ? i18n.str`Waiting for current payment information…` - : actions.message - } - onRetryObservation={state.status === "failed" ? retry : undefined} - workingAction={actions.workingAction} - onBack={() => navigate("/transactions")} - onAction={(action) => void actions.runAction(action)} - onOpenExternal={(url) => void platform.openExternal(url)} - recoveryActionLabel={recovery?.actionLabel} - onRecoveryAction={ - recovery - ? () => - navigate( - exchangeRecoveryRoute( - recovery, - `/transaction/${transactionId}`, - ), - ) - : undefined - } + <TransactionDetailView + transactionId={transactionId} + view={view} + showTransferInstructions={showTransferInstructions} /> ); } -function QueriedTransactionDetailRoute({ +function TransactionDetailView({ transactionId, + view, + showTransferInstructions = false, }: { transactionId: TransactionIdStr; + view: TransactionObservationView; + showTransferInstructions?: boolean; }) { const { connection, platform } = useServices(); const { language } = useLanguage(); const [, navigate] = useLocation(); - const callMutation = useWalletMutation(connection); - const { controller: unclaimRequest } = useWalletProgress(connection, { - visible: false, - }); - const durability = useDurability(); - const query = useWalletQuery( + const snapshot = view.snapshot; + const observed = snapshot?.transaction; + const paymentSnapshot = + snapshot?.type === TransactionType.Payment ? snapshot : undefined; + const contract = usePaymentContract( connection, - WalletApiOperation.GetTransactionById, - { transactionId, includeContractTerms: true }, - ); - const exchanges = useWalletQuery( - connection, - WalletApiOperation.ListExchanges, - {}, + paymentSnapshot?.transaction, + view.ready, ); const paymentDialog = - query.data?.type === TransactionType.Payment && - query.data.txState.major === TransactionMajorState.Dialog && - query.data.txState.minor !== TransactionMinorState.WaitingForOtherWallet - ? query.data + observed?.type === TransactionType.Payment && + observed.txState.major === TransactionMajorState.Dialog && + observed.txState.minor !== TransactionMinorState.WaitingForOtherWallet + ? observed : undefined; - const paymentChoicesQuery = useWalletQuery( - connection, - WalletApiOperation.GetChoicesForPayment, - { transactionId }, - { enabled: paymentDialog !== undefined }, - ); - const paymentDonauQuery = useWalletQuery( - connection, - WalletApiOperation.GetDonau, - {}, - { enabled: paymentDialog !== undefined }, - ); const { workingAction, error, setError, message, setMessage, runAction } = useTransactionActions(transactionId); - const [continuingTransfer, setContinuingTransfer] = useState(false); - const [selectedPaymentChoice, setSelectedPaymentChoice] = useState<number>(); - const [useDonau, setUseDonau] = useState(false); - const [confirmingPayment, setConfirmingPayment] = useState(false); - const [unclaimingPayment, setUnclaimingPayment] = useState(false); - const [reclaimingPayment, setReclaimingPayment] = useState(false); - const [localHandoffUri, setLocalHandoffUri] = useState<string>(); - const handoffTarget = useRef<"other" | "current">("other"); - const reclaimingPaymentRef = useRef(false); + const [continuingTransfer, setContinuingTransfer] = useState( + showTransferInstructions, + ); + const actions = usePaymentActions(view, contract, error, setError); + const { review: paymentReview, recovery } = actions; useEffect(() => { setError(undefined); setMessage(undefined); - setContinuingTransfer(false); - setSelectedPaymentChoice(undefined); - setUseDonau(false); - setConfirmingPayment(false); - setUnclaimingPayment(false); - setReclaimingPayment(false); - setLocalHandoffUri(undefined); - handoffTarget.current = "other"; - reclaimingPaymentRef.current = false; + setContinuingTransfer(showTransferInstructions); }, [transactionId]); + useEffect(() => { + if (actions.confirming || actions.unclaiming || actions.reclaiming) + setMessage(undefined); + }, [actions.confirming, actions.unclaiming, actions.reclaiming]); const transaction = useMemo( () => - query.data ? transactionDetailView(query.data, language) : undefined, - [language, query.data], - ); - const paymentReview = useMemo( - () => - paymentDialog && paymentChoicesQuery.data - ? paymentReviewView( - paymentDialog, - paymentChoicesQuery.data, - paymentDonauQuery.data?.currentDonauInfo, - language, - ) + observed + ? transactionDetailView(observed, language, contract.terms) : undefined, - [ - language, - paymentChoicesQuery.data, - paymentDialog, - paymentDonauQuery.data?.currentDonauInfo, - ], + [language, observed, contract.terms], ); - const activePaymentChoice = activePaymentChoiceIndex( - paymentReview, - selectedPaymentChoice, - ); - const recovery = - exchangeKeyRecoveryFromError(error?.detail) ?? - exchangeKeyRecoveryFromError(query.data?.error) ?? - exchangeKeyRecoveryFromInsufficientBalance( - paymentReview?.choices.find( - (candidate) => candidate.index === activePaymentChoice, - )?.balanceDetails, - exchanges.data?.exchanges, - ); - useEffect(() => setUseDonau(false), [activePaymentChoice]); - const confirmPayment = async (collectDonationReceipt = useDonau) => { - if (!paymentDialog || !paymentReview || activePaymentChoice === undefined) - return; - if (!(await durability.guardValueOperation())) return; - setConfirmingPayment(true); - setError(undefined); - setMessage(undefined); - try { - const choice = paymentReview.choices.find( - (candidate) => candidate.index === activePaymentChoice, - ); - const result = await callMutation( - WalletApiOperation.ConfirmPay, - paymentConfirmationRequest( - transactionId, - activePaymentChoice, - choice, - collectDonationReceipt, - ), - ["balances", "transactions"], - ); - if (Result.isError(result)) { - setError( - walletCoreError( - result.detail, - i18n.str`Wallet-core could not confirm this payment.`, - ), - ); - return; - } - setMessage( - result.value.type === ConfirmPayResultType.Done - ? i18n.str`Payment complete` - : i18n.str`Payment submitted`, - ); - } catch (cause) { - setError( - errorFromException(cause, i18n.str`Payment confirmation failed`), - ); - } finally { - setConfirmingPayment(false); - } - }; - const reclaimPayment = async () => { - if (reclaimingPaymentRef.current) return; - reclaimingPaymentRef.current = true; - setReclaimingPayment(true); - setError(undefined); - setMessage(undefined); - try { - const result = await callMutation( - WalletApiOperation.ReclaimPayment, - { transactionId }, - ["transactions"], - ); - if (Result.isError(result)) { - setError( - walletCoreError( - result.detail, - i18n.str`The payment could not continue with this wallet.`, - ), - ); - return; - } - setLocalHandoffUri(undefined); - setMessage(i18n.str`The payment is continuing with this wallet.`); - } catch (cause) { - setError( - errorFromException( - cause, - i18n.str`Continuing the payment with this wallet failed.`, - ), - ); - } finally { - reclaimingPaymentRef.current = false; - setReclaimingPayment(false); - } - }; - const keepPaymentHere = () => { - if (!unclaimingPayment || handoffTarget.current === "current") return; - handoffTarget.current = "current"; - setReclaimingPayment(true); - void unclaimRequest.cancel().catch((cause) => { - setError( - errorFromException( - cause, - i18n.str`Cancelling the payment handoff failed.`, - ), - ); - }); - }; - const wantsCurrentWallet = () => handoffTarget.current === "current"; - const unclaimPayment = async () => { - if (!paymentDialog || unclaimingPayment) return; - handoffTarget.current = "other"; - setUnclaimingPayment(true); - setError(undefined); - setMessage(undefined); - let reclaimAfterward = false; - try { - const result = await unclaimRequest.callAndInvalidate( - WalletApiOperation.UnclaimPayment, - { transactionId }, - ["transactions"], - ); - if (wantsCurrentWallet()) { - reclaimAfterward = true; - } else if (Result.isError(result)) { - setError( - walletCoreError( - result.detail, - i18n.str`The payment could not be handed off to another wallet.`, - ), - ); - return; - } else { - setLocalHandoffUri(result.value.talerPayUri); - } - } catch (cause) { - if (wantsCurrentWallet()) { - reclaimAfterward = true; - } else if (!isProgressRequestCancelled(cause)) { - setError(errorFromException(cause, i18n.str`Payment handoff failed`)); - } - } finally { - setUnclaimingPayment(false); - } - if (reclaimAfterward) await reclaimPayment(); - }; - if (continuingTransfer && query.data?.type === TransactionType.Withdrawal) { - const current = transactionDetailView(query.data, language); - const outcome = current.pending - ? undefined - : { - title: - current.state === "Completed" - ? i18n.str`Withdrawal completed` - : // Translators: Outcome heading; %1$s is an already translated withdrawal status. - i18n.str`Withdrawal: ${current.state}`, - detail: - current.state === "Completed" - ? i18n.str`${current.amount} is now reflected in your wallet balance.` - : current.statusDetail, - success: current.tone === "success", - }; + if ( + continuingTransfer && + view.ready && + !error && + !observed?.error && + transaction?.continuationAction?.kind === "withdrawal-transfer" && + observed?.type === TransactionType.Withdrawal + ) { return ( <WireTransferScreen - amountRaw={query.data.amountRaw} - amountEffective={query.data.amountEffective} - exchange={query.data.exchangeBaseUrl ?? i18n.str`Exchange`} - options={transactionWireOptions(query.data, [language])} - outcome={outcome} + amountRaw={observed.amountRaw} + amountEffective={observed.amountEffective} + exchange={observed.exchangeBaseUrl ?? i18n.str`Exchange`} + options={transactionWireOptions(observed, [language])} onCopy={(value) => void navigator.clipboard.writeText(value)} onOpenExternal={(uri) => void platform.openExternal(uri)} onDone={() => setContinuingTransfer(false)} - onViewWallet={() => navigate("/")} /> ); } if ( continuingTransfer && - query.data?.type === TransactionType.Deposit && - query.data.kycAuthTransferInfo + view.ready && + !error && + !observed?.error && + transaction?.continuationAction?.kind === "deposit-kyc-auth" && + observed?.type === TransactionType.Deposit && + observed.kycAuthTransferInfo ) { return ( <WireTransferScreen - purpose={`deposit-kyc-auth`} - amountRaw={query.data.amountRaw} - amountEffective={query.data.amountEffective} - exchange="" - debitPaytoUri={query.data.kycAuthTransferInfo.debitPaytoUri} - accountPub={query.data.kycAuthTransferInfo.accountPub} - options={depositKycAuthWireOptions(query.data, [language])} + amountRaw={observed.amountRaw} + amountEffective={observed.amountEffective} + exchange={transaction.title} + purpose="deposit-kyc-auth" + debitPaytoUri={observed.kycAuthTransferInfo.debitPaytoUri} + accountPub={observed.kycAuthTransferInfo.accountPub} + options={depositKycAuthWireOptions(observed, [language])} onCopy={(value) => void navigator.clipboard.writeText(value)} onOpenExternal={(uri) => void platform.openExternal(uri)} onDone={() => setContinuingTransfer(false)} @@ -5392,15 +5138,30 @@ function QueriedTransactionDetailRoute({ return ( <TransactionDetailScreen transaction={transaction} - loading={query.isLoading} - error={ - error ?? - (query.error + loading={view.loading} + contractLoading={contract.loading} + contractError={ + contract.error ? errorFromException( - query.error, - i18n.str`The transaction could not be loaded.`, + contract.error, + i18n.str`The payment contract details are unavailable.`, ) - : undefined) + : undefined + } + onRetryContract={ + view.ready && contract.error ? contract.retry : undefined + } + onRetryObservation={view.canRetry ? view.retry : undefined} + error={ + error ?? + (view.state.status === "deleted" + ? localError(i18n.str`This transaction no longer exists.`) + : view.error + ? errorFromException( + view.error, + i18n.str`The transaction could not be loaded.`, + ) + : undefined) } message={message} workingAction={workingAction} @@ -5409,48 +5170,52 @@ function QueriedTransactionDetailRoute({ onOpenExternal={(url) => void platform.openExternal(url)} onContinue={() => setContinuingTransfer(true)} paymentReview={ - query.data?.type === TransactionType.Payment && - query.data.txState.major === TransactionMajorState.Dialog && - (query.data.unclaimedPayUri ?? localHandoffUri) + observed?.type === TransactionType.Payment && + observed.txState.major === TransactionMajorState.Dialog && + observed.unclaimedPayUri ? { state: "handoff", - talerPayUri: query.data.unclaimedPayUri ?? localHandoffUri!, - reclaiming: reclaimingPayment, + talerPayUri: observed.unclaimedPayUri, + reclaiming: actions.reclaiming, } : paymentDialog - ? paymentChoicesQuery.error + ? view.error ? { state: "error", error: errorFromException( - paymentChoicesQuery.error, + view.error, i18n.str`Payment options could not be loaded.`, ), } - : !paymentDialog.contractTerms + : contract.error ? { state: "error", - error: localError( + error: errorFromException( + contract.error, i18n.str`The payment contract details are unavailable.`, ), } : !paymentReview ? { state: "loading" } : { - state: confirmingPayment ? "paying" : "ready", + state: actions.confirming ? "paying" : "ready", + confirmDisabled: !actions.canConfirm || !!workingAction, choices: paymentReview.choices, - selectedChoice: activePaymentChoice, - useDonau, - unclaiming: unclaimingPayment, - reclaiming: reclaimingPayment, + selectedChoice: actions.selectedChoice, + useDonau: actions.useDonau, + unclaiming: actions.unclaiming, + reclaiming: actions.reclaiming, } : undefined } - onSelectPaymentChoice={setSelectedPaymentChoice} - onConfirmPayment={(collect) => void confirmPayment(collect)} - onUnclaimPayment={paymentDialog ? () => void unclaimPayment() : undefined} - onKeepPaymentHere={keepPaymentHere} - onReclaimPayment={() => void reclaimPayment()} - onToggleDonau={setUseDonau} + onSelectPaymentChoice={actions.selectChoice} + onConfirmPayment={(collect) => void actions.confirm(collect)} + onUnclaimPayment={ + paymentDialog ? () => void actions.unclaim() : undefined + } + onKeepPaymentHere={actions.keepHere} + onReclaimPayment={() => void actions.reclaim()} + onToggleDonau={actions.setUseDonau} onConfigureDonau={(baseUrl) => navigate( `/donations?suggested=${encodeURIComponent(baseUrl)}&returnTo=${encodeURIComponent(`/transaction/${transactionId}`)}`, diff --git a/packages/wallet-webui/src/routes/exchange-key-recovery-model.ts b/packages/wallet-webui/src/routes/exchange-key-recovery-model.ts @@ -1,7 +1,7 @@ import { CoinSelectionFailureReasonType, TalerErrorCode, - type ExchangeListItem, + type ExchangeKeyChangeInfo, type PaymentInsufficientBalanceDetails, } from "@gnu-taler/taler-util"; import { i18n } from "../i18n/runtime.js"; @@ -40,7 +40,12 @@ function supersededExchangeUrls( export function exchangeKeyRecoveryFromInsufficientBalance( detail: PaymentInsufficientBalanceDetails | undefined, - exchanges: ExchangeListItem[] | undefined, + exchanges: + | { + exchangeBaseUrl: string; + unconfirmedKeyChange?: ExchangeKeyChangeInfo; + }[] + | undefined, ): ExchangeKeyRecovery | undefined { const affected = supersededExchangeUrls(detail); if (affected.length === 0) return undefined; diff --git a/packages/wallet-webui/src/routes/payment-actions.ts b/packages/wallet-webui/src/routes/payment-actions.ts @@ -0,0 +1,330 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { + Result, + TransactionMajorState, + TransactionMinorState, + TransactionType, +} from "@gnu-taler/taler-util"; +import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; +import { useEffect, useMemo, useRef, useState } from "preact/hooks"; +import type { + PaymentContractView, + TransactionObservationView, +} from "../api/observations.js"; +import { + isProgressRequestCancelled, + useWalletProgress, +} from "../api/progress.js"; +import { useWalletMutation } from "../api/wallet.js"; +import { useLanguage } from "../i18n/LanguageProvider.js"; +import { i18n } from "../i18n/runtime.js"; +import { useDurability } from "../platform/durability.js"; +import { + errorFromException, + walletCoreError, + type ErrorPresentation, +} from "../ui/error.js"; +import { useServices } from "./context.js"; +import { + exchangeKeyRecoveryFromError, + exchangeKeyRecoveryFromInsufficientBalance, + type ExchangeKeyRecovery, +} from "./exchange-key-recovery-model.js"; +import { + activePaymentChoiceIndex, + paymentConfirmationRequest, + paymentReviewView, + type PaymentReviewView, +} from "./payment-model.js"; + +interface PaymentRequest { + kind: "confirm" | "unclaim" | "reclaim"; + acknowledged: boolean; + keepHere: boolean; +} + +export interface PaymentActions { + review?: PaymentReviewView; + selectedChoice?: number; + selectChoice: (index: number) => void; + useDonau: boolean; + setUseDonau: (enabled: boolean) => void; + canConfirm: boolean; + confirming: boolean; + unclaiming: boolean; + reclaiming: boolean; + recovery?: ExchangeKeyRecovery; + confirm: (collectDonationReceipt?: boolean) => Promise<void>; + unclaim: () => Promise<void>; + reclaim: () => Promise<void>; + keepHere: () => void; +} + +/** Shared payment actions; transaction status and handoff links come from snapshots. */ +export function usePaymentActions( + view: TransactionObservationView, + contract: PaymentContractView, + error: ErrorPresentation | undefined, + setError: (error: ErrorPresentation | undefined) => void, + options: { automatic?: boolean } = {}, +): PaymentActions { + const { connection } = useServices(); + const { language } = useLanguage(); + const durability = useDurability(); + const callMutation = useWalletMutation(connection); + const { controller: unclaimRequest } = useWalletProgress(connection, { + visible: false, + }); + const snapshot = + view.snapshot?.type === TransactionType.Payment ? view.snapshot : undefined; + const transactionId = snapshot?.transaction.transactionId; + const review = useMemo( + () => + snapshot?.payment && contract.terms + ? paymentReviewView( + contract.terms, + snapshot.payment, + snapshot.currentDonauInfo, + language, + ) + : undefined, + [snapshot, contract.terms, language], + ); + const [selectedChoice, setSelectedChoice] = useState<number>(); + const [useDonau, setUseDonau] = useState(false); + const [request, setRequest] = useState<PaymentRequest>(); + const active = useRef<PaymentRequest>(); + const automaticStarted = useRef(false); + const canConfirm = + view.ready && + !!review && + snapshot?.confirmation.unavailableReasons.length === 0; + const latest = useRef({ snapshot, canConfirm, review }); + latest.current = { snapshot, canConfirm, review }; + const choiceIndex = activePaymentChoiceIndex(review, selectedChoice); + const recovery = + exchangeKeyRecoveryFromError(error?.detail) ?? + exchangeKeyRecoveryFromError(snapshot?.transaction.error) ?? + exchangeKeyRecoveryFromInsufficientBalance( + review?.choices.find((choice) => choice.index === choiceIndex) + ?.balanceDetails, + snapshot?.exchanges, + ); + + useEffect(() => { + setSelectedChoice(undefined); + setUseDonau(false); + setRequest(undefined); + automaticStarted.current = false; + return () => { + active.current = undefined; + }; + }, [transactionId]); + useEffect(() => setUseDonau(false), [choiceIndex]); + // An acknowledgement can precede its snapshot. Keep the action busy until + // the observed state reflects it, without inventing a transaction status. + useEffect(() => { + const current = active.current; + if (!current?.acknowledged || !view.ready || !snapshot) return; + const state = snapshot.transaction.txState; + const reflected = + current.kind === "confirm" + ? state.major !== TransactionMajorState.Dialog + : current.kind === "unclaim" + ? state.minor === TransactionMinorState.WaitingForOtherWallet || + state.major !== TransactionMajorState.Dialog + : state.minor !== TransactionMinorState.WaitingForOtherWallet; + if (reflected) { + active.current = undefined; + setRequest(undefined); + } + }, [request, snapshot, view.ready]); + + const isActive = (request: PaymentRequest) => active.current === request; + const begin = (kind: PaymentRequest["kind"]) => { + const next: PaymentRequest = { kind, acknowledged: false, keepHere: false }; + active.current = next; + setRequest(next); + setError(undefined); + return next; + }; + const finish = (current: PaymentRequest, success: boolean) => { + if (!isActive(current)) return; + current.acknowledged = success; + if (success) setRequest({ ...current }); + else { + active.current = undefined; + setRequest(undefined); + } + }; + const confirm = async (collect = useDonau, index = choiceIndex) => { + if (active.current || !canConfirm || !transactionId || index === undefined) + return; + const current = begin("confirm"); + let success = false; + try { + if (!(await durability.guardValueOperation())) return; + const latestView = latest.current; + if ( + !isActive(current) || + !latestView.canConfirm || + latestView.snapshot?.transaction.transactionId !== transactionId + ) + return; + const choice = latestView.review?.choices.find( + (candidate) => candidate.index === index, + ); + if (!choice) return; + const result = await callMutation( + WalletApiOperation.ConfirmPay, + paymentConfirmationRequest(transactionId, index, choice, collect), + ["balances", "transactions"], + ); + if (!isActive(current)) return; + if (Result.isError(result)) + setError( + walletCoreError( + result.detail, + i18n.str`Wallet-core could not confirm this payment.`, + ), + ); + else success = true; + } catch (cause) { + if (isActive(current)) + setError( + errorFromException(cause, i18n.str`Payment confirmation failed`), + ); + } finally { + finish(current, success); + } + }; + useEffect(() => { + if ( + !options.automatic || + !canConfirm || + review?.automaticChoiceIndex === undefined || + automaticStarted.current || + active.current + ) + return; + automaticStarted.current = true; + void confirm(false, review.automaticChoiceIndex); + }, [options.automatic, canConfirm, review]); + + const reclaim = async () => { + if (!transactionId) return; + if (active.current?.kind === "unclaim" && !active.current.acknowledged) { + keepHere(); + return; + } + if (active.current && active.current.kind !== "unclaim") return; + const current = begin("reclaim"); + let success = false; + try { + const result = await callMutation( + WalletApiOperation.ReclaimPayment, + { transactionId }, + ["transactions"], + ); + if (!isActive(current)) return; + if (Result.isError(result)) + setError( + walletCoreError( + result.detail, + i18n.str`The payment could not continue with this wallet.`, + ), + ); + else success = true; + } catch (cause) { + if (isActive(current)) + setError( + errorFromException( + cause, + i18n.str`Continuing the payment with this wallet failed.`, + ), + ); + } finally { + finish(current, success); + } + }; + const keepHere = () => { + const current = active.current; + if (current?.kind !== "unclaim" || current.keepHere) return; + if (current.acknowledged) { + void reclaim(); + return; + } + current.keepHere = true; + setRequest({ ...current }); + void unclaimRequest.cancel().catch((cause) => { + if (isActive(current)) + setError( + errorFromException( + cause, + i18n.str`Cancelling the payment handoff failed.`, + ), + ); + }); + }; + const unclaim = async () => { + if ( + active.current || + !transactionId || + !view.ready || + snapshot?.transaction.txState.major !== TransactionMajorState.Dialog + ) + return; + const current = begin("unclaim"); + let success = false; + try { + const result = await unclaimRequest.callAndInvalidate( + WalletApiOperation.UnclaimPayment, + { transactionId }, + ["transactions"], + ); + if (!isActive(current)) return; + if (Result.isError(result)) { + if (!current.keepHere) + setError( + walletCoreError( + result.detail, + i18n.str`The payment could not be handed off to another wallet.`, + ), + ); + } else success = true; + } catch (cause) { + if ( + isActive(current) && + !current.keepHere && + !isProgressRequestCancelled(cause) + ) + setError(errorFromException(cause, i18n.str`Payment handoff failed`)); + } finally { + if (isActive(current) && current.keepHere) { + finish(current, false); + await reclaim(); + } else finish(current, success); + } + }; + return { + review, + selectedChoice: choiceIndex, + selectChoice: setSelectedChoice, + useDonau, + setUseDonau, + canConfirm: canConfirm && !request, + confirming: request?.kind === "confirm", + unclaiming: request?.kind === "unclaim", + reclaiming: request?.kind === "reclaim" || !!request?.keepHere, + recovery, + confirm, + unclaim, + reclaim, + keepHere, + }; +} diff --git a/packages/wallet-webui/src/routes/payment-model.ts b/packages/wallet-webui/src/routes/payment-model.ts @@ -10,9 +10,10 @@ import { isSafeExternalUrl, type ConfirmPayRequest, type PaymentInsufficientBalanceDetails, - type GetChoicesForPaymentResult, + type ObservedPaymentChoices, type TransactionIdStr, - type TransactionPayment, + type ObservedPaymentTransaction, + type MerchantContractTerms, } from "@gnu-taler/taler-util"; import type { PaymentChoiceOutputView, @@ -38,19 +39,14 @@ export interface PaymentReviewView { automaticChoiceIndex?: number; } -export function asynchronousConfirmPayRequest( - request: Omit<ConfirmPayRequest, "noWait">, -): ConfirmPayRequest { - return { ...request, noWait: true }; -} - export function paymentConfirmationRequest( transactionId: TransactionIdStr, choiceIndex: number, choice: PaymentChoiceView | undefined, collectDonationReceipt: boolean, ): ConfirmPayRequest { - return asynchronousConfirmPayRequest({ + return { + noWait: true, transactionId, choiceIndex, ...(choice?.forceTokenSelection ? { forcedTokenSel: true } : {}), @@ -58,7 +54,7 @@ export function paymentConfirmationRequest( choice?.donationReceipt?.status === "available" ? { useDonau: true } : {}), - }); + }; } /** Choose what the payment review should display and submit. */ @@ -76,7 +72,7 @@ export function activePaymentChoiceIndex( /** Return the original payment that wallet-core is replaying for a repurchase. */ export function paymentRepurchaseTarget( - transaction: TransactionPayment | undefined, + transaction: ObservedPaymentTransaction | undefined, ): TransactionIdStr | undefined { if ( transaction?.txState.major !== TransactionMajorState.Failed || @@ -89,8 +85,8 @@ export function paymentRepurchaseTarget( /** Map a payment and its optional repurchase replay to the payment screen. */ export function paymentResultState( - transaction: TransactionPayment, - replay: TransactionPayment | undefined, + transaction: ObservedPaymentTransaction, + replay: ObservedPaymentTransaction | undefined, ): "pending" | "paused" | "done" | "handed-off" | "error" { if (paymentRepurchaseTarget(transaction)) { if (!replay) return "pending"; @@ -114,13 +110,11 @@ export function paymentResultState( } export function paymentReviewView( - transaction: TransactionPayment, - result: GetChoicesForPaymentResult, + terms: MerchantContractTerms, + result: ObservedPaymentChoices, currentDonauInfo?: { donauBaseUrl: string }, language = "en", -): PaymentReviewView | undefined { - const terms = transaction.contractTerms; - if (!terms) return undefined; +): PaymentReviewView { const contractChoices = terms.version === MerchantContractVersion.V1 ? terms.choices : undefined; const choices = result.choices.map((details, index): PaymentChoiceView => { diff --git a/packages/wallet-webui/src/routes/peer-credit-review-model.ts b/packages/wallet-webui/src/routes/peer-credit-review-model.ts @@ -5,7 +5,7 @@ */ import { TalerErrorCode } from "@gnu-taler/taler-util"; -import type { PeerCreditObservationState } from "../api/observations.js"; +import type { TransactionObservationState } from "../api/observations.js"; import { i18n } from "../i18n/runtime.js"; import type { ErrorPresentation } from "../ui/error.js"; import { exchangeKeyRecoveryFromError } from "./exchange-key-recovery-model.js"; @@ -21,7 +21,7 @@ export type PeerCreditConfirmationView = /** Translate core decisions into presentation; do not recompute eligibility. */ export function peerCreditConfirmationView( - state: PeerCreditObservationState, + state: TransactionObservationState, returnTo: string, actionError?: ErrorPresentation, ): PeerCreditConfirmationView { @@ -78,15 +78,24 @@ export function peerCreditConfirmationView( }; // Ordinary request errors remain visible; retrying confirmation is allowed. } - const url = state.snapshot.transaction.exchangeBaseUrl; - const reason = state.snapshot.confirmation.unavailableReasons[0]; + const snapshot = state.snapshot; + if ( + snapshot.type !== "peer-push-credit" && + snapshot.type !== "peer-pull-debit" + ) + return { enabled: false, reason: i18n.str`This is not a peer payment.` }; + const paying = snapshot.type === "peer-pull-debit"; + const url = snapshot.transaction.exchangeBaseUrl; + const reason = snapshot.confirmation.unavailableReasons[0]; switch (reason) { case undefined: return { enabled: true }; case "exchange-keys-not-accepted": return { enabled: false, - reason: /* 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.`, + reason: paying + ? i18n.str`This exchange changed its signing keys. Verify that change before paying this invoice.` + : /* 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.`, recovery: { label: i18n.str`Verify key change`, href: exchangeRoute(url), @@ -95,12 +104,19 @@ export function peerCreditConfirmationView( case "exchange-tos-not-accepted": return { enabled: false, - reason: /* 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.`, + reason: paying + ? i18n.str`Review and accept this exchange's terms of service before paying this invoice.` + : /* 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.`, recovery: { label: i18n.str`Review terms`, href: exchangeRoute(url, true), }, }; + case "contract-unavailable": + return { + enabled: false, + reason: i18n.str`Waiting for current payment information…`, + }; case "expired": return { enabled: false, diff --git a/packages/wallet-webui/src/routes/transaction-model.ts b/packages/wallet-webui/src/routes/transaction-model.ts @@ -6,8 +6,8 @@ import { TransactionType, WithdrawalType, assertUnreachable, - type Transaction, - type ObservedPeerPushCreditTransaction, + type ObservedTransaction, + type MerchantContractTerms, } from "@gnu-taler/taler-util"; import { parseTransactionIdentifier } from "@gnu-taler/taler-wallet-core"; import { safeWebUrl } from "./payment-model.js"; @@ -17,8 +17,6 @@ import { depositDestinationView } from "./deposit-model.js"; import { i18n } from "../i18n/runtime.js"; import { walletCoreError, type ErrorPresentation } from "../ui/error.js"; -type PresentedTransaction = Transaction | ObservedPeerPushCreditTransaction; - export type TransactionDirection = "credit" | "debit" | "neutral"; export type TransactionTone = "success" | "warning" | "error" | "neutral"; export type TransactionUiAction = @@ -168,7 +166,7 @@ function host(value: string | undefined): string | undefined { } } -function titleAndSubtitle(transaction: PresentedTransaction): { +function titleAndSubtitle(transaction: ObservedTransaction): { title: string; subtitle?: string; } { @@ -256,7 +254,7 @@ function minorLabels(): Partial<Record<TransactionMinorState, string>> { }; } -export function transactionStateView(transaction: PresentedTransaction): { +export function transactionStateView(transaction: ObservedTransaction): { label: string; detail: string; tone: TransactionTone; @@ -361,7 +359,7 @@ export function transactionStateView(transaction: PresentedTransaction): { } function timestampView( - transaction: PresentedTransaction, + transaction: ObservedTransaction, language?: string, ): { timestamp: string; @@ -381,7 +379,7 @@ function timestampView( /** Preserve the structured reason for any wallet-core transaction failure. */ export function transactionErrorPresentation( - transaction: PresentedTransaction, + transaction: ObservedTransaction, fallback?: string, ): ErrorPresentation | undefined { const detail = @@ -393,9 +391,7 @@ export function transactionErrorPresentation( ); } -function fieldsFor( - transaction: PresentedTransaction, -): TransactionDetailField[] { +function fieldsFor(transaction: ObservedTransaction): TransactionDetailField[] { const fields: TransactionDetailField[] = []; switch (transaction.type) { case TransactionType.Payment: @@ -660,7 +656,7 @@ function actionPresentations(): Record< } export function transactionHistoryView( - transaction: PresentedTransaction, + transaction: ObservedTransaction, language?: string, ): TransactionHistoryView { const presentation = typePresentations()[transaction.type]; @@ -701,8 +697,9 @@ export function transactionHistoryView( } export function transactionDetailView( - transaction: PresentedTransaction, + transaction: ObservedTransaction, language?: string, + contractTerms?: MerchantContractTerms, ): TransactionDetailView { const base = transactionHistoryView(transaction, language); const state = transactionStateView(transaction); @@ -759,6 +756,8 @@ export function transactionDetailView( transaction.withdrawalDetails.type === WithdrawalType.TalerBankIntegrationApi && base.pending && + !externalAction && + !transaction.withdrawalDetails.confirmed && safeWebUrl(transaction.withdrawalDetails.bankConfirmationUrl) ) { externalAction = { @@ -772,7 +771,9 @@ export function transactionDetailView( if ( transaction.type === TransactionType.Withdrawal && transaction.withdrawalDetails.type === WithdrawalType.ManualTransfer && - base.pending && + transaction.txState.major === TransactionMajorState.Pending && + transaction.txState.minor === TransactionMinorState.ExchangeWaitReserve && + !transaction.error && (transaction.withdrawalDetails.exchangeCreditAccountDetails?.some( (account) => account.status === "ok" && account.transferOptions.length > 0, @@ -802,26 +803,17 @@ export function transactionDetailView( } const fulfillmentUrl = transaction.type === TransactionType.Payment && - safeWebUrl(transaction.contractTerms?.fulfillment_url) - ? transaction.contractTerms.fulfillment_url + safeWebUrl(transaction.info?.fulfillmentUrl) + ? transaction.info.fulfillmentUrl : undefined; const order = - transaction.type === TransactionType.Payment && transaction.contractTerms + transaction.type === TransactionType.Payment && contractTerms ? orderSummaryView( - transaction.contractTerms, + contractTerms, Amounts.parse(transaction.amountRaw)?.currency, ) : undefined; const technicalFields: TransactionDetailField[] = []; - if ("kycPaytoHash" in transaction && transaction.kycPaytoHash) { - technicalFields.push({ - // Translators: KYC is "Know Your Customer"; payto is the name of a URI scheme. - label: i18n.str`KYC payto hash`, - value: transaction.kycPaytoHash, - breakAll: true, - copyable: true, - }); - } if (transaction.type === TransactionType.Refresh) { technicalFields.push( { label: i18n.str`Raw amount`, value: transaction.amountRaw }, diff --git a/packages/wallet-webui/src/routes/withdrawal-model.ts b/packages/wallet-webui/src/routes/withdrawal-model.ts @@ -8,8 +8,8 @@ import { isSafeExternalUrl, type AccountRestriction, type InternationalizedString, - type TransactionDeposit, - type TransactionWithdrawal, + type ObservedDepositTransaction, + type ObservedWithdrawalTransaction, type WithdrawalExchangeAccountDetails, type WithdrawUriInfoResponse, } from "@gnu-taler/taler-util"; @@ -312,7 +312,7 @@ function accountRestrictionView( /** Rebuild user-facing wire instructions without replaying the withdrawal. */ export function transactionWireOptions( - transaction: TransactionWithdrawal, + transaction: ObservedWithdrawalTransaction, languages: readonly string[] = [], ): WireOptionView[] { const details = transaction.withdrawalDetails; @@ -337,7 +337,7 @@ export function transactionWireOptions( /** Present the small source-account authentication transfer required by a deposit. */ export function depositKycAuthWireOptions( - transaction: TransactionDeposit, + transaction: ObservedDepositTransaction, languages: readonly string[] = [], ): WireOptionView[] { const info = transaction.kycAuthTransferInfo; diff --git a/packages/wallet-webui/src/screens/PaymentScreen.tsx b/packages/wallet-webui/src/screens/PaymentScreen.tsx @@ -169,6 +169,7 @@ export function PaymentOptions(props: { selectedChoice?: number; useDonau?: boolean; cancelling?: boolean; + confirmDisabled?: boolean; unclaiming?: boolean; reclaiming?: boolean; onSelectChoice: (index: number) => void; @@ -367,6 +368,7 @@ export function PaymentOptions(props: { <Button onClick={() => props.onConfirm(props.useDonau === true)} disabled={ + props.confirmDisabled || !selected?.payable || props.state === "paying" || props.cancelling || @@ -445,12 +447,17 @@ export function PaymentScreen(props: { choices?: PaymentChoiceView[]; selectedChoice?: number; error?: ErrorPresentation; + onRetryObservation?: () => void; + contractLoading?: boolean; + contractError?: ErrorPresentation; + onRetryContract?: () => void; fulfillmentMessage?: string; fulfillmentUrl?: string; posConfirmation?: string; useDonau?: boolean; cancelling?: boolean; resuming?: boolean; + confirmDisabled?: boolean; unclaiming?: boolean; reclaiming?: boolean; talerPayUri?: string; @@ -517,6 +524,11 @@ export function PaymentScreen(props: { } > <div class="mt-4 flex flex-wrap gap-3"> + {props.onRetryObservation && ( + <Button + onClick={props.onRetryObservation} + >{i18n.str`Retry updates`}</Button> + )} {props.onRecoveryAction && ( <Button onClick={props.onRecoveryAction}> {props.recoveryActionLabel ?? i18n.str`Review exchange`} @@ -591,6 +603,7 @@ export function PaymentScreen(props: { /> <PaymentOptions state={props.state} + confirmDisabled={props.confirmDisabled} choices={props.choices} selectedChoice={props.selectedChoice} useDonau={props.useDonau} @@ -622,11 +635,30 @@ export function PaymentScreen(props: { /> )} + {props.contractLoading && ( + <Card> + <p role="status">{i18n.str`Loading order details…`}</p> + </Card> + )} + {props.contractError && ( + <ErrorCard error={props.contractError}> + {props.onRetryContract && ( + <Button onClick={props.onRetryContract}> + {i18n.str`Retry order details`} + </Button> + )} + </ErrorCard> + )} {props.error && props.state !== "error" && props.state !== "paused" && ( <ErrorCard title={i18n.str`Payment could not continue`} error={props.error} > + {props.onRetryObservation && ( + <Button + onClick={props.onRetryObservation} + >{i18n.str`Retry updates`}</Button> + )} {props.onRecoveryAction && ( <div class="mt-4"> <Button onClick={props.onRecoveryAction}> @@ -679,6 +711,11 @@ export function PaymentScreen(props: { } > <div class="mt-4 flex flex-wrap gap-3"> + {props.onRetryObservation && ( + <Button + onClick={props.onRetryObservation} + >{i18n.str`Retry updates`}</Button> + )} {props.onRecoveryAction && ( <Button onClick={props.onRecoveryAction}> {props.recoveryActionLabel ?? i18n.str`Review exchange`} diff --git a/packages/wallet-webui/src/screens/PeerShareScreen.tsx b/packages/wallet-webui/src/screens/PeerShareScreen.tsx @@ -10,7 +10,9 @@ export function PeerShareScreen(props: { uri?: string; loading: boolean; delayed?: boolean; + status?: { label: string; detail: string }; error?: ErrorPresentation; + onRetryObservation?: () => void; retryable?: boolean; retrying?: boolean; onCopy: () => void; @@ -61,6 +63,11 @@ export function PeerShareScreen(props: { tone="secondary" onClick={props.onDone} >{i18n.str`View transaction`}</Button> + {props.onRetryObservation && ( + <Button + onClick={props.onRetryObservation} + >{i18n.str`Retry updates`}</Button> + )} {props.retryable && props.onRetry && ( <Button disabled={props.retrying} onClick={props.onRetry}> {props.retrying ? i18n.str`Trying…` : i18n.str`Try now`} @@ -69,6 +76,17 @@ export function PeerShareScreen(props: { </div> </ErrorCard> )} + {props.status && ( + <Card> + <p role="status" class="font-medium"> + {props.status.label} + </p> + <p class="mt-2 text-sm text-secondary">{props.status.detail}</p> + <div class="mt-4 flex justify-end"> + <Button onClick={props.onDone}>{i18n.str`View transaction`}</Button> + </div> + </Card> + )} {props.uri && ( <> <QrFrame diff --git a/packages/wallet-webui/src/screens/TransactionDetailScreen.tsx b/packages/wallet-webui/src/screens/TransactionDetailScreen.tsx @@ -31,6 +31,7 @@ export type TransactionPaymentReview = choices: PaymentChoiceView[]; selectedChoice?: number; useDonau?: boolean; + confirmDisabled?: boolean; unclaiming?: boolean; reclaiming?: boolean; }; @@ -47,6 +48,9 @@ export function TransactionDetailScreen(props: { loading: boolean; error?: ErrorPresentation; onRetryObservation?: () => void; + contractLoading?: boolean; + contractError?: ErrorPresentation; + onRetryContract?: () => void; message?: string; workingAction?: TransactionUiAction; onBack: () => void; @@ -291,12 +295,26 @@ export function TransactionDetailScreen(props: { heading={i18n.str`Order details`} /> )} - {props.paymentReview?.state === "loading" && ( + {props.contractLoading && ( + <Card> + <p role="status">{i18n.str`Loading order details…`}</p> + </Card> + )} + {props.contractError && ( + <ErrorCard error={props.contractError}> + {props.onRetryContract && ( + <Button onClick={props.onRetryContract}> + {i18n.str`Retry order details`} + </Button> + )} + </ErrorCard> + )} + {props.paymentReview?.state === "loading" && !props.contractLoading && ( <Card> <p role="status">{i18n.str`Loading payment details…`}</p> </Card> )} - {props.paymentReview?.state === "error" && ( + {props.paymentReview?.state === "error" && !props.contractError && ( <ErrorCard title={i18n.str`Payment options could not be loaded.`} error={props.paymentReview.error} @@ -317,6 +335,7 @@ export function TransactionDetailScreen(props: { choices={props.paymentReview.choices} selectedChoice={props.paymentReview.selectedChoice} useDonau={props.paymentReview.useDonau} + confirmDisabled={props.paymentReview.confirmDisabled} unclaiming={props.paymentReview.unclaiming} reclaiming={props.paymentReview.reclaiming} onSelectChoice={(index) => props.onSelectPaymentChoice?.(index)} diff --git a/packages/wallet-webui/src/testing/demo-wallet.ts b/packages/wallet-webui/src/testing/demo-wallet.ts @@ -1,11 +1,12 @@ import { ConfirmPayResultType, + observedTransaction, ExchangeEntryStatus, ExchangeTosStatus, ExchangeUpdateStatus, NotificationType, ObservationType, - type PeerPushCreditSnapshot, + type TransactionSnapshot, Paytos, PaytoType, Result, @@ -219,6 +220,7 @@ function makePayment( info: { merchant: terms.merchant, orderId: terms.order_id, + contractTermsHash: "demo-contract", summary: terms.summary, products: terms.products, }, @@ -502,54 +504,94 @@ export class DemoWalletConnection implements WalletConnection { const t = this.state.transactions.find( (t) => t.transactionId === entry.transactionId, ); - const snapshot: PeerPushCreditSnapshot | null = - t?.type === TransactionType.PeerPushCredit - ? { - transaction: { - type: t.type, - transactionId: t.transactionId, - timestamp: t.timestamp, - scopes: t.scopes, - txState: t.txState, - txActions: t.txActions, - amountRaw: t.amountRaw, - amountEffective: t.amountEffective, - amountEffectiveFinal: t.amountEffectiveFinal, - info: t.info, - exchangeBaseUrl: t.exchangeBaseUrl, - kycUrl: t.kycUrl, - kycAmlReview: t.kycAmlReview, - error: t.error, - }, - exchange: { - exchangeBaseUrl: t.exchangeBaseUrl, - tosStatus: - this.state.exchanges.find( - (e) => e.exchangeBaseUrl === t.exchangeBaseUrl, - )?.tosStatus ?? ExchangeTosStatus.Accepted, - exchangeUpdateStatus: ExchangeUpdateStatus.Ready, - currencySpec: { - name: "CHF", - alt_unit_names: {}, - num_fractional_input_digits: 2, - num_fractional_normal_digits: 2, - num_fractional_trailing_zero_digits: 2, - }, - }, - confirmation: { - unavailableReasons: - t.txState.major === TransactionMajorState.Dialog - ? [] - : ["not-proposed"], - }, - } + const observed = t && observedTransaction(t); + const exchanges = this.state.exchanges.map((e) => ({ + exchangeBaseUrl: e.exchangeBaseUrl, + tosStatus: e.tosStatus, + unconfirmedKeyChange: e.unconfirmedKeyChange, + exchangeUpdateStatus: ExchangeUpdateStatus.Ready, + currencySpec: { + name: "CHF", + alt_unit_names: {}, + num_fractional_input_digits: 2, + num_fractional_normal_digits: 2, + num_fractional_trailing_zero_digits: 2, + }, + })); + const snapshot = + t && observed + ? ({ + type: t.type, + transaction: observed, + exchanges, + ...([ + TransactionType.Payment, + TransactionType.PeerPushCredit, + TransactionType.PeerPullDebit, + ].includes(t.type) + ? { + confirmation: { + unavailableReasons: + t.txState.major === TransactionMajorState.Dialog && + t.txState.minor === TransactionMinorState.Proposed + ? [] + : ["not-proposed"], + }, + } + : {}), + ...(t.type === TransactionType.Withdrawal && + t.withdrawalDetails.type === + WithdrawalType.TalerBankIntegrationApi + ? { + bank: { + operationId: "demo-operation", + status: t.withdrawalDetails.confirmed + ? "confirmed" + : t.txState.major === TransactionMajorState.Dialog + ? "pending" + : "selected", + currency: "CHF", + amount: t.amountEffective, + editableAmount: true, + editableExchange: true, + maxAmount: "CHF:100", + wireFee: "CHF:0.50", + defaultExchangeBaseUrl: exchangeBaseUrl, + confirmTransferUrl: + t.withdrawalDetails.bankConfirmationUrl, + }, + } + : {}), + ...(t.type === TransactionType.Payment + ? { + payment: + t.txState.major === TransactionMajorState.Dialog + ? { + choices: [ + { + status: "payment-possible", + amountRaw: t.amountRaw, + amountEffective: t.amountEffective, + scopeInfo: chfScope, + }, + ], + defaultChoiceIndex: 0, + automaticExecution: false, + } + : null, + currentDonauInfo: this.state.donau + ? { donauBaseUrl: this.state.donau.donauBaseUrl } + : undefined, + } + : {}), + } as TransactionSnapshot) : null; const value = JSON.stringify(snapshot); if (value === entry.value) continue; entry.value = value; this.emit({ type: NotificationType.ObservationSnapshot, - observationType: ObservationType.PeerPushCredit, + observationType: ObservationType.Transaction, observationId, transactionId: entry.transactionId as TransactionIdStr, revision: ++entry.revision, @@ -1173,13 +1215,12 @@ export class DemoWalletConnection implements WalletConnection { transactionId: id, } as never); } - case WalletApiOperation.ObservePeerPushCredit: { + case WalletApiOperation.ObserveTransaction: { const id = String(request.observationId); if (this.observations.has(id)) throw Error("Observation ID already active"); const t = this.findTransaction(String(request.transactionId)); - if (t.type !== TransactionType.PeerPushCredit) - throw Error("Expected peer push credit"); + this.observations.set(id, { transactionId: t.transactionId, revision: 0, @@ -1204,7 +1245,7 @@ export class DemoWalletConnection implements WalletConnection { "CHF:7.00", "CHF:7.00", TransactionMajorState.Dialog, - TransactionMinorState.Ready, + TransactionMinorState.Proposed, ), exchangeBaseUrl, info: { diff --git a/packages/wallet-webui/test/observations-hook.test.tsx b/packages/wallet-webui/test/observations-hook.test.tsx @@ -7,10 +7,21 @@ import assert from "node:assert/strict"; import test from "node:test"; import { Window } from "happy-dom"; -import { NotificationType, type TransactionIdStr } from "@gnu-taler/taler-util"; +import { + TransactionType, + NotificationType, + type TransactionIdStr, +} from "@gnu-taler/taler-util"; import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; -import { usePeerCreditObservation } from "../src/api/observations.js"; -import type { WalletConnection } from "../src/api/contracts.js"; +import { + useTransactionObservation, + usePaymentContract, + type PaymentContractView, +} from "../src/api/observations.js"; +import type { + WalletConnection, + ConnectionStatus, +} from "../src/api/contracts.js"; import { DemoWalletConnection, demoActionUris, @@ -20,13 +31,14 @@ function Probe(props: { connection: WalletConnection; transactionId: TransactionIdStr; }) { - const { state } = usePeerCreditObservation( + const { state } = useTransactionObservation( props.connection, props.transactionId, ); return ( <div> - {state.status === "ready" + {state.status === "ready" && + state.snapshot.type === TransactionType.PeerPushCredit ? state.snapshot.transaction.info.summary : state.status} </div> @@ -45,23 +57,29 @@ async function fixture(summary: string) { const subscribe = connection.subscribeNotifications.bind(connection); connection.subscribeNotifications = (listener) => subscribe((n) => { - if (n.type === NotificationType.ObservationSnapshot && n.snapshot) + if ( + n.type === NotificationType.ObservationSnapshot && + n.snapshot?.type === TransactionType.PeerPushCredit + ) { + const snapshot = n.snapshot; pending.push(() => listener({ ...n, snapshot: { - ...n.snapshot!, + ...snapshot, + type: TransactionType.PeerPushCredit, + exchanges: [], transaction: { - ...n.snapshot!.transaction, + ...snapshot.transaction, info: { - ...n.snapshot!.transaction.info, + ...snapshot.transaction.info, summary: `${summary}:${n.transactionId}`, }, }, }, }), ); - else listener(n); + } else listener(n); }); return { connection, @@ -142,3 +160,198 @@ test("the hook resets on connection and target changes and rejects late notifica await dom.happyDOM.abort(); } }); + +for (const recovery of ["retry", "reconnect"] as const) { + test(`payment contract reads recover after ${recovery}`, async () => { + const dom = new Window({ url: "https://wallet.example/" }); + for (const [key, value] of Object.entries({ + window: dom, + document: dom.document, + navigator: dom.navigator, + HTMLElement: dom.HTMLElement, + MutationObserver: dom.MutationObserver, + })) + Object.defineProperty(globalThis, key, { + value, + writable: true, + configurable: true, + }); + const { render, cleanup, act } = await import("@testing-library/preact"); + const connection = new DemoWalletConnection(); + const { transactionId } = await connection.client.call( + WalletApiOperation.PreparePayForUriV2, + { talerPayUri: demoActionUris.payment }, + ); + const statuses = new Set<(status: ConnectionStatus) => void>(); + connection.subscribeStatus = (listener) => { + statuses.add(listener); + listener({ state: "connected" }); + return () => { + statuses.delete(listener); + }; + }; + let reads = 0; + let registrations = 0; + const call = connection.client.call.bind(connection.client); + connection.client.call = async (op, args) => { + if (op === WalletApiOperation.ObserveTransaction) registrations++; + if (op === WalletApiOperation.GetTransactionById && ++reads === 1) + throw Error("connection lost while reading contract"); + return call(op, args); + }; + let current: PaymentContractView | undefined; + function PaymentProbe() { + const observation = useTransactionObservation(connection, transactionId); + current = usePaymentContract( + connection, + observation.snapshot?.type === TransactionType.Payment + ? observation.snapshot.transaction + : undefined, + observation.ready, + ); + return ( + <div> + {current.terms + ? "loaded" + : (current.error?.message ?? observation.state.status)} + {current.error && ( + <button onClick={current.retry}>Retry details</button> + )} + </div> + ); + } + const view = render(<PaymentProbe />); + const wait = async (check: () => void) => { + for (let i = 0; ; i++) { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + }); + try { + check(); + return; + } catch (e) { + if (i > 100) throw e; + } + } + }; + try { + await wait(() => + assert(view.getByRole("button", { name: "Retry details" })), + ); + assert.equal(reads, 1); + if (recovery === "retry") + await act(async () => + view.getByRole("button", { name: "Retry details" }).click(), + ); + else { + await act(async () => { + for (const listener of statuses) + listener({ + state: "disconnected", + reason: "lost", + unknownMutationIds: [], + }); + }); + await act(async () => { + for (const listener of statuses) listener({ state: "connected" }); + }); + } + await wait(() => assert(current?.terms)); + assert.equal(reads, 2); + assert.equal(current?.error, undefined); + assert.equal(registrations, recovery === "retry" ? 1 : 2); + } finally { + cleanup(); + connection.close(); + await dom.happyDOM.abort(); + } + }); +} + +test("contract reads discard late failures and never reuse another payment's document", async () => { + const dom = new Window({ url: "https://wallet.example/" }); + for (const [key, value] of Object.entries({ + window: dom, + document: dom.document, + navigator: dom.navigator, + HTMLElement: dom.HTMLElement, + MutationObserver: dom.MutationObserver, + })) + Object.defineProperty(globalThis, key, { + configurable: true, + writable: true, + value, + }); + const { render, cleanup, act } = await import("@testing-library/preact"); + const connection = new DemoWalletConnection(); + const prepare = async () => { + const { transactionId } = await connection.client.call( + WalletApiOperation.PreparePayForUriV2, + { talerPayUri: demoActionUris.payment }, + ); + const transaction = await connection.client.call( + WalletApiOperation.GetTransactionById, + { transactionId, includeContractTerms: true }, + ); + assert.ok( + transaction.type === TransactionType.Payment && transaction.contractTerms, + ); + return transaction; + }; + const first = await prepare(); + const second = await prepare(); + const pending: { + resolve: (transaction: typeof first) => void; + reject: (error: Error) => void; + }[] = []; + const call = connection.client.call.bind(connection.client); + connection.client.call = async (op, args) => { + if (op === WalletApiOperation.GetTransactionById) + return new Promise((resolve, reject) => + pending.push({ resolve, reject }), + ) as never; + return call(op, args); + }; + let current: PaymentContractView | undefined; + function DocumentProbe({ payment }: { payment: typeof first }) { + current = usePaymentContract(connection, payment, true); + return ( + <div>{current.terms?.summary ?? current.error?.message ?? "loading"}</div> + ); + } + const view = render(<DocumentProbe payment={first} />); + const wait = async (check: () => void) => { + for (let i = 0; ; i++) { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + }); + try { + check(); + return; + } catch (error) { + if (i >= 100) throw error; + } + } + }; + try { + await wait(() => assert.equal(pending.length, 1)); + await act(async () => view.rerender(<DocumentProbe payment={second} />)); + await wait(() => assert.equal(pending.length, 2)); + await act(async () => + pending[0].reject(new Error("stale document failure")), + ); + assert.equal(current?.error, undefined); + assert.equal(current?.terms, undefined); + await act(async () => pending[1].resolve(second)); + await wait(() => assert.equal(current?.terms, second.contractTerms)); + await act(async () => view.rerender(<DocumentProbe payment={first} />)); + assert.equal(current?.terms, undefined); + await wait(() => assert.equal(pending.length, 3)); + await act(async () => pending[2].resolve(first)); + await wait(() => assert.equal(current?.terms, first.contractTerms)); + } finally { + cleanup(); + connection.close(); + await dom.happyDOM.abort(); + } +}); diff --git a/packages/wallet-webui/test/observations.test.ts b/packages/wallet-webui/test/observations.test.ts @@ -8,6 +8,9 @@ import assert from "node:assert/strict"; import test from "node:test"; import { NotificationType, + observedTransaction, + TalerErrorCode, + type TransactionPeerPushCredit, ObservationType, TransactionType, TransactionMajorState, @@ -19,7 +22,7 @@ import { type CoreApiResponse, } from "@gnu-taler/taler-util"; import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; -import { PeerCreditObservation } from "../src/api/observations.js"; +import { TransactionObservation } from "../src/api/observations.js"; import type { ConnectionStatus, WalletConnection, @@ -29,10 +32,13 @@ import { DemoWalletConnection, demoActionUris, } from "../src/testing/demo-wallet.js"; +import { exchangeKeyRecoveryFromError } from "../src/routes/exchange-key-recovery-model.js"; import { transactionDetailView } from "../src/routes/transaction-model.js"; const transactionId = "txn:peer-push-credit:test" as TransactionIdStr; const snapshot: PeerPushCreditSnapshot = { + type: TransactionType.PeerPushCredit, + exchanges: [], transaction: { type: TransactionType.PeerPushCredit, transactionId, @@ -50,7 +56,6 @@ const snapshot: PeerPushCreditSnapshot = { kycUrl: "https://exchange.example/kyc-spa/token", kycAmlReview: true, }, - exchange: null, confirmation: { unavailableReasons: ["not-proposed"] }, }; const tick = () => new Promise<void>((resolve) => setImmediate(resolve)); @@ -64,8 +69,7 @@ function fixture() { client: { async call(op: string, args: { observationId: string }) { calls.push({ op, id: args.observationId }); - if (op === WalletApiOperation.ObservePeerPushCredit) - await acknowledgement; + if (op === WalletApiOperation.ObserveTransaction) await acknowledgement; return {}; }, } as unknown as WalletConnection["client"], @@ -94,14 +98,14 @@ function fixture() { ) => emit({ type: NotificationType.ObservationSnapshot, - observationType: ObservationType.PeerPushCredit, + observationType: ObservationType.Transaction, transactionId, observationId: id, revision, snapshot: value, }); let serial = 0; - const observer = new PeerCreditObservation( + const observer = new TransactionObservation( connection, transactionId, () => {}, @@ -118,15 +122,15 @@ function fixture() { }; } -function readState(observer: PeerCreditObservation) { +function readState(observer: TransactionObservation) { return observer.state; } -function failureMessage(observer: PeerCreditObservation) { +function failureMessage(observer: TransactionObservation) { const state = observer.state; return state.status === "failed" ? state.error.message : undefined; } -function currentSnapshot(observer: PeerCreditObservation) { +function currentSnapshot(observer: TransactionObservation) { const state = observer.state; return state.status === "deleted" ? undefined : state.snapshot; } @@ -139,8 +143,10 @@ test("initial notification before acknowledgement, revision filtering and comple assert.equal(currentSnapshot(f.observer), snapshot); f.send("view-1", 1, null); assert.equal(readState(f.observer).status === "deleted", false); - const replacement = { + const replacement: PeerPushCreditSnapshot = { ...snapshot, + type: TransactionType.PeerPushCredit, + exchanges: [], transaction: { ...snapshot.transaction, kycUrl: undefined, @@ -183,14 +189,14 @@ test("reconnect replaces registration; errors permit retry and deletion ends it" assert.equal(readState(f.observer).status, "ready"); f.emit({ type: NotificationType.ObservationError, - observationType: ObservationType.PeerPushCredit, + observationType: ObservationType.Transaction, observationId: "view-2", error: { code: 1, hint: "read failed" }, }); assert.equal(failureMessage(f.observer), "read failed"); f.status({ state: "connected" }); assert.equal( - f.calls.filter((c) => c.op === WalletApiOperation.ObservePeerPushCredit) + f.calls.filter((c) => c.op === WalletApiOperation.ObserveTransaction) .length, 2, ); @@ -203,7 +209,7 @@ test("reconnect replaces registration; errors permit retry and deletion ends it" f.observer.retry(); assert.deepEqual(readState(f.observer), { status: "deleted" }); assert.equal( - f.calls.filter((c) => c.op === WalletApiOperation.ObservePeerPushCredit) + f.calls.filter((c) => c.op === WalletApiOperation.ObserveTransaction) .length, 3, ); @@ -217,7 +223,7 @@ test("extension disconnect cleans up registration that completes after disconnec const calls: CoreApiRequestEnvelope[] = []; const owner = new ObservationOwner(async (request) => { calls.push(request); - if (request.operation === WalletApiOperation.ObservePeerPushCredit) + if (request.operation === WalletApiOperation.ObserveTransaction) return new Promise((resolve) => (complete = resolve)); return { type: "response", @@ -227,7 +233,7 @@ test("extension disconnect cleans up registration that completes after disconnec }; }); const request = { - operation: WalletApiOperation.ObservePeerPushCredit, + operation: WalletApiOperation.ObserveTransaction, id: "register", args: { observationId: "view", transactionId }, }; @@ -259,14 +265,18 @@ test("receive preparation, observed detail and completion need no follow-up quer WalletApiOperation.PreparePeerPushCredit, { talerUri: demoActionUris["peer-receive"] }, ); - const observer = new PeerCreditObservation( + const observer = new TransactionObservation( connection, prepared.transactionId, () => {}, () => "receive", ); + const initial = currentSnapshot(observer); + assert.equal(initial?.type, TransactionType.PeerPushCredit); assert.deepEqual( - currentSnapshot(observer)?.confirmation.unavailableReasons, + initial?.type === TransactionType.PeerPushCredit + ? initial.confirmation.unavailableReasons + : undefined, [], ); await connection.client.call(WalletApiOperation.ConfirmPeerPushCredit, { @@ -285,3 +295,77 @@ test("AML review uses waiting copy and a details link, not an instruction to com assert.equal(view.statusDetail, "Waiting for review"); assert.equal(view.externalAction?.label, "View verification details"); }); + +test("bank withdrawal tracking follows generic snapshots without preparing again", async () => { + const connection = new DemoWalletConnection(); + const calls: string[] = []; + const call = connection.client.call.bind(connection.client); + connection.client.call = ((op, request) => { + calls.push(op); + return call(op, request); + }) as typeof call; + const prepared = await connection.client.call( + WalletApiOperation.PrepareBankIntegratedWithdrawal, + { + talerWithdrawUri: "taler://withdraw/bank.demo.invalid/operation", + }, + ); + const observer = new TransactionObservation( + connection, + prepared.transactionId, + () => {}, + () => "bank", + ); + try { + const initial = currentSnapshot(observer); + assert.ok(initial?.type === TransactionType.Withdrawal); + assert.equal(initial.bank?.status, "pending"); + await connection.client.call(WalletApiOperation.ConfirmWithdrawal, { + transactionId: prepared.transactionId, + exchangeBaseUrl: prepared.info.defaultExchangeBaseUrl!, + amount: "CHF:10", + }); + const updated = currentSnapshot(observer); + assert.ok(updated?.type === TransactionType.Withdrawal); + assert.equal(updated.bank?.status, "selected"); + assert.equal( + calls.filter( + (op) => op === WalletApiOperation.PrepareBankIntegratedWithdrawal, + ).length, + 1, + ); + assert.equal(calls.includes(WalletApiOperation.GetTransactionById), false); + } finally { + observer.dispose(); + connection.close(); + } +}); + +test("the snapshot projection excludes new diagnostics but preserves key-change recovery", () => { + const raw: TransactionPeerPushCredit = { + ...snapshot.transaction, + stId: 7, + abortReason: undefined, + failReason: undefined, + kycAccessToken: "secret", + kycPaytoHash: "internal", + error: { + code: TalerErrorCode.WALLET_EXCHANGE_KEYS_NOT_ACCEPTED, + exchangeBaseUrl: "https://exchange.example/", + hint: "Verify key change", + internalDiagnostic: "secret", + }, + }; + const withFutureDiagnostic = { + ...raw, + futurePrivateField: "secret", + }; + const observed = observedTransaction(withFutureDiagnostic); + assert.equal(JSON.stringify(observed).includes("secret"), false); + assert.equal("stId" in observed, false); + assert.equal("futurePrivateField" in observed, false); + assert.deepEqual( + exchangeKeyRecoveryFromError(observed.error)?.exchangeBaseUrls, + ["https://exchange.example/"], + ); +}); diff --git a/packages/wallet-webui/test/payment-model.test.ts b/packages/wallet-webui/test/payment-model.test.ts @@ -16,7 +16,6 @@ import { } from "@gnu-taler/taler-util"; import { activePaymentChoiceIndex, - asynchronousConfirmPayRequest, paymentConfirmationRequest, paymentRepurchaseTarget, paymentResultState, @@ -62,10 +61,12 @@ test("payment review keeps an unavailable choice visible", () => { test("payment confirmation always returns immediately", () => { assert.deepEqual( - asynchronousConfirmPayRequest({ - transactionId: "txn:payment:test" as TransactionIdStr, - choiceIndex: 1, - }), + paymentConfirmationRequest( + "txn:payment:test" as TransactionIdStr, + 1, + undefined, + false, + ), { transactionId: "txn:payment:test", choiceIndex: 1, @@ -169,7 +170,7 @@ test("a suspended payment is shown as paused", () => { assert.equal(paymentResultState(transaction, undefined), "paused"); }); -test("payment review preserves core choice availability and rejects unsafe fulfillment URLs", () => { +test("payment review preserves core choice availability", () => { const transaction = { contractTerms: { version: MerchantContractVersion.V1, @@ -178,7 +179,6 @@ test("payment review preserves core choice availability and rejects unsafe fulfi name: "Example Museum", website: "https://merchant.example/", }, - fulfillment_url: "javascript:alert(1)", choices: [ { amount: "CHF:5", @@ -275,9 +275,8 @@ test("payment review preserves core choice availability and rejects unsafe fulfi }, ], } as unknown as GetChoicesForPaymentResult; - const view = paymentReviewView(transaction, choices); + const view = paymentReviewView(transaction.contractTerms!, choices); assert(view); - assert.equal(view.fulfillmentUrl, undefined); assert.equal(view.choices[0].description, "Member"); assert.equal(view.choices[0].forceTokenSelection, true); assert.equal(view.choices[1].payable, false); @@ -356,13 +355,13 @@ test("payment review selects merchant token descriptions for the active language ], } as unknown as GetChoicesForPaymentResult; assert.equal( - paymentReviewView(transaction, choices, undefined, "de-DE")?.choices[0] - .outputs[0]?.description, + paymentReviewView(transaction.contractTerms!, choices, undefined, "de-DE") + ?.choices[0].outputs[0]?.description, "Deutsche Beschreibung", ); assert.equal( - paymentReviewView(transaction, choices, undefined, "fr")?.choices[0] - .outputs[0]?.description, + paymentReviewView(transaction.contractTerms!, choices, undefined, "fr") + ?.choices[0].outputs[0]?.description, "English description", ); }); @@ -402,23 +401,24 @@ test("payment review classifies donation receipt authority compatibility", () => ], } as unknown as GetChoicesForPaymentResult; assert.equal( - paymentReviewView(transaction, choices)?.choices[0].donationReceipt?.status, + paymentReviewView(transaction.contractTerms!, choices)?.choices[0] + .donationReceipt?.status, "setup", ); assert.equal( - paymentReviewView(transaction, choices, { + paymentReviewView(transaction.contractTerms!, choices, { donauBaseUrl: "https://donau.example/", })?.choices[0].donationReceipt?.status, "available", ); assert.equal( - paymentReviewView(transaction, choices, { + paymentReviewView(transaction.contractTerms!, choices, { donauBaseUrl: "https://other.example/", })?.choices[0].donationReceipt?.status, "mismatch", ); assert.equal( - paymentReviewView(transaction, choices, { + paymentReviewView(transaction.contractTerms!, choices, { donauBaseUrl: "https://donau.example/", })?.automaticChoiceIndex, undefined, diff --git a/packages/wallet-webui/test/peer-credit-observation.test.tsx b/packages/wallet-webui/test/peer-credit-observation.test.tsx @@ -20,8 +20,9 @@ import { register } from "node:module"; import { Window } from "happy-dom"; import { NotificationType, + TransactionMinorState, ExchangeTosStatus, - type PeerPushCreditSnapshotNotification, + type TransactionSnapshotNotification, type WalletNotification, ObservationType, TransactionType, @@ -30,6 +31,7 @@ import { TalerError, TalerErrorCode, type TransactionIdStr, + type TransactionConfirmationUnavailableReason, } from "@gnu-taler/taler-util"; import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; import { @@ -56,7 +58,9 @@ async function harness( | "failure" | "delayed" | "snapshot-delayed" - | "pull" = "normal", + | "pull" + | "bank" = "normal", + pullBlocker?: TransactionConfirmationUnavailableReason, ) { const dom = new Window({ url: "https://wallet.example/" }); for (const key of [ @@ -100,19 +104,21 @@ async function harness( // The route must use core's blockers instead of reconstructing eligibility. let holdSnapshots = mode === "snapshot-delayed"; const pendingSnapshots: (() => void)[] = []; - let latest: PeerPushCreditSnapshotNotification | undefined; + let latest: TransactionSnapshotNotification | 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 + n.snapshot?.type === TransactionType.PeerPushCredit && + n.snapshot.exchanges[0] ) { - const value: PeerPushCreditSnapshotNotification = { + const value: TransactionSnapshotNotification = { ...n, snapshot: { ...n.snapshot, + type: TransactionType.PeerPushCredit, transaction: { ...n.snapshot.transaction, ...(mode === "snapshot-delayed" @@ -125,15 +131,34 @@ async function harness( } : {}), }, - exchange: { - ...n.snapshot.exchange, - tosStatus: ExchangeTosStatus.Proposed, - }, + exchanges: [ + { + ...n.snapshot.exchanges[0], + tosStatus: ExchangeTosStatus.Proposed, + }, + ], }, }; latest = value; if (holdSnapshots) pendingSnapshots.push(() => listener(value)); else listener(value); + } else if ( + mode === "bank" && + n.type === NotificationType.ObservationSnapshot && + n.snapshot?.type === TransactionType.Withdrawal + ) { + // The exchange can complete a funded reserve while cached bank status is stale. + latest = { + ...n, + snapshot: { + ...n.snapshot, + transaction: { + ...n.snapshot.transaction, + txState: { major: TransactionMajorState.Done }, + }, + }, + }; + listener(latest); } else listener(n); }); return () => { @@ -142,7 +167,9 @@ async function harness( }; }; const entry = await services.platform.actionInbox.put( - demoActionUris["peer-receive"], + mode === "bank" + ? demoActionUris.withdrawal + : demoActionUris["peer-receive"], source, ); if (mode === "pull") { @@ -156,11 +183,58 @@ async function harness( : undefined; }; } - dom.location.hash = `#/peer-receive/${entry.id}`; + dom.location.hash = + mode === "bank" + ? `#/withdraw-action/${entry.id}` + : `#/peer-receive/${entry.id}`; const calls: string[] = []; const originalCall = services.connection.client.call; services.connection.client.call = async (operation, request) => { calls.push(operation); + if ( + mode === "pull" && + operation === WalletApiOperation.ObserveTransaction + ) { + const args = request as { + observationId: string; + transactionId: TransactionIdStr; + }; + latest = { + type: NotificationType.ObservationSnapshot, + observationType: ObservationType.Transaction, + observationId: args.observationId, + transactionId: args.transactionId, + revision: 1, + snapshot: { + type: TransactionType.PeerPullDebit, + exchanges: [], + confirmation: { + unavailableReasons: pullBlocker ? [pullBlocker] : [], + }, + transaction: { + type: TransactionType.PeerPullDebit, + transactionId: args.transactionId, + timestamp: { t_s: 1 }, + scopes: [], + txState: { + major: TransactionMajorState.Dialog, + minor: TransactionMinorState.Proposed, + }, + txActions: [], + amountRaw: "CHF:3", + amountEffective: "CHF:3.1", + exchangeBaseUrl: "https://exchange.example/", + info: { + summary: "Observed invoice", + expiration: { t_s: 2000000000 }, + iconId: undefined, + }, + }, + }, + }; + for (const listener of listeners) listener(latest); + return {} as never; + } return originalCall(operation, request); }; const mutations: string[] = []; @@ -241,7 +315,7 @@ async function harness( for (const listener of listeners) listener({ type: NotificationType.ObservationError, - observationType: ObservationType.PeerPushCredit, + observationType: ObservationType.Transaction, observationId: latest.observationId, error: { code: 1, hint: "read failed" }, }); @@ -251,6 +325,40 @@ async function harness( for (const listener of listeners) listener({ ...latest, revision: latest.revision + 1, snapshot: null }); }, + flipPeerType: () => { + assert.ok(latest?.snapshot); + const snapshot = latest.snapshot; + assert.ok( + snapshot.type === TransactionType.PeerPushCredit || + snapshot.type === TransactionType.PeerPullDebit, + ); + const changed = + snapshot.type === TransactionType.PeerPushCredit + ? { + type: TransactionType.PeerPullDebit as const, + transaction: { + ...snapshot.transaction, + type: TransactionType.PeerPullDebit as const, + }, + confirmation: snapshot.confirmation, + exchanges: snapshot.exchanges, + } + : { + type: TransactionType.PeerPushCredit as const, + transaction: { + ...snapshot.transaction, + type: TransactionType.PeerPushCredit as const, + }, + confirmation: { unavailableReasons: [] }, + exchanges: snapshot.exchanges, + }; + for (const listener of listeners) + listener({ + ...latest, + revision: latest.revision + 1, + snapshot: changed, + }); + }, counts: () => ({ prepares, confirms }), dom, close: async () => { @@ -282,7 +390,7 @@ test("incoming push receive and detail use snapshots without transaction/exchang ); assert.equal(h.calls.includes(WalletApiOperation.ListExchanges), false); assert.equal( - h.calls.filter((op) => op === WalletApiOperation.ObservePeerPushCredit) + h.calls.filter((op) => op === WalletApiOperation.ObserveTransaction) .length, 2, ); @@ -300,7 +408,7 @@ test("preparation values stay hidden until the first snapshot, and deletion neve const h = await harness("paste", "snapshot-delayed"); try { await h.waitFor(() => - assert(h.calls.includes(WalletApiOperation.ObservePeerPushCredit)), + assert(h.calls.includes(WalletApiOperation.ObserveTransaction)), ); assert.equal(h.view.queryByText("CHF:7.00"), null); assert.equal(h.view.queryByText("Shared lunch"), null); @@ -326,7 +434,7 @@ test("preparation failure stays in preparation without registering an observer", await h.waitFor(() => assert.equal(h.counts().prepares, 1)); await h.waitFor(() => assert(h.view.getByRole("alert"))); assert.equal( - h.calls.includes(WalletApiOperation.ObservePeerPushCredit), + h.calls.includes(WalletApiOperation.ObserveTransaction), false, ); } finally { @@ -352,7 +460,7 @@ test("cancelling preparation ignores its late result", async () => { ), ); assert.equal( - h.calls.includes(WalletApiOperation.ObservePeerPushCredit), + h.calls.includes(WalletApiOperation.ObserveTransaction), false, ); assert.equal( @@ -408,7 +516,7 @@ test("peer-credit detail retains its value after failure and offers observation ), ); assert.equal( - h.calls.filter((op) => op === WalletApiOperation.ObservePeerPushCredit) + h.calls.filter((op) => op === WalletApiOperation.ObserveTransaction) .length, 3, ); @@ -465,16 +573,13 @@ for (const kind of ["peer", "queried"] as const) } }); -test("peer-pull review keeps using its preparation response without an observation", async () => { +test("peer-pull review uses the observed invoice instead of preparation data", 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("Observed invoice")); assert(h.view.getByText("CHF:3.1")); - assert.equal( - h.calls.includes(WalletApiOperation.ObservePeerPushCredit), - false, - ); + assert.equal(h.calls.includes(WalletApiOperation.ObserveTransaction), true); await h.act(async () => h.view.getByRole("button", { name: "Pay" }).click(), ); @@ -578,3 +683,95 @@ test("cancelled push confirmation can be retried without completing the inbox ac await h.close(); } }); + +for (const [reason, label] of [ + ["exchange-tos-not-accepted", "Review terms"], + ["exchange-keys-not-accepted", "Verify key change"], +] as const) { + test(`invoice review offers recovery for ${reason}`, async () => { + const h = await harness("paste", "pull", reason); + try { + await h.waitFor(() => + assert(h.view.getByRole("button", { name: label })), + ); + assert.equal( + (h.view.getByRole("button", { name: "Pay" }) as HTMLButtonElement) + .disabled, + true, + ); + await h.act(async () => + h.view.getByRole("button", { name: label }).click(), + ); + await h.waitFor(() => assert.match(h.dom.location.hash, /#\/exchange\//)); + assert.equal( + new URLSearchParams(h.dom.location.hash.split("?")[1]).get("returnTo"), + `/peer-receive/${h.entry.id}`, + ); + } finally { + await h.close(); + } + }); +} + +test("invoice review retries failed observations without preparing again", async () => { + const h = await harness("paste", "pull"); + try { + await h.waitFor(() => assert(h.view.getByRole("button", { name: "Pay" }))); + await h.act(async () => h.failObserved()); + await h.waitFor(() => + assert(h.view.getByRole("button", { name: "Retry updates" })), + ); + assert.equal( + (h.view.getByRole("button", { name: "Pay" }) as HTMLButtonElement) + .disabled, + true, + ); + await h.act(async () => + h.view.getByRole("button", { name: "Retry updates" }).click(), + ); + await h.waitFor(() => + assert.equal( + (h.view.getByRole("button", { name: "Pay" }) as HTMLButtonElement) + .disabled, + false, + ), + ); + assert.equal(h.counts().prepares, 1); + assert.equal( + h.calls.filter((op) => op === WalletApiOperation.ObserveTransaction) + .length, + 2, + ); + } finally { + await h.close(); + } +}); + +for (const mode of ["normal", "pull"] as const) { + test(`${mode} peer review rejects an unexpected snapshot type`, async () => { + const h = await harness("paste", mode); + try { + const name = mode === "normal" ? "Receive money" : "Pay"; + await h.waitFor(() => + assert.equal( + (h.view.getByRole("button", { name }) as HTMLButtonElement).disabled, + false, + ), + ); + await h.act(async () => h.flipPeerType()); + await h.waitFor(() => + assert.ok( + h.view.getByText("This is not a supported peer payment link."), + ), + ); + assert.equal(h.view.queryByRole("button", { name }), null); + assert.equal(h.counts().confirms, 0); + assert.equal( + h.mutations.includes(WalletApiOperation.ConfirmPeerPullDebit), + false, + ); + } finally { + await h.close(); + } + }); +} diff --git a/packages/wallet-webui/test/peer-credit-review-model.test.ts b/packages/wallet-webui/test/peer-credit-review-model.test.ts @@ -14,9 +14,11 @@ import { type TransactionIdStr, } from "@gnu-taler/taler-util"; import { peerCreditConfirmationView } from "../src/routes/peer-credit-review-model.js"; -import type { PeerCreditObservationState } from "../src/api/observations.js"; +import type { TransactionObservationState } from "../src/api/observations.js"; const snapshot: PeerPushCreditSnapshot = { + type: TransactionType.PeerPushCredit, + exchanges: [], transaction: { type: TransactionType.PeerPushCredit, transactionId: "txn:peer-push-credit:test" as TransactionIdStr, @@ -29,7 +31,6 @@ const snapshot: PeerPushCreditSnapshot = { info: { summary: "Lunch", expiration: undefined, iconId: undefined }, exchangeBaseUrl: "https://exchange.example/", }, - exchange: null, confirmation: { unavailableReasons: [] }, }; const returnTo = "/peer-receive/inbox"; @@ -41,7 +42,7 @@ test("only a ready snapshot can enable confirmation", () => { { status: "disconnected", snapshot }, { status: "failed", error: Error("failed"), snapshot }, { status: "deleted" }, - ] satisfies PeerCreditObservationState[]) + ] satisfies TransactionObservationState[]) assert.equal(peerCreditConfirmationView(state, returnTo).enabled, false); assert.deepEqual( peerCreditConfirmationView({ status: "ready", snapshot }, returnTo), @@ -121,3 +122,37 @@ test("confirmation RPC failures preserve their recovery information", () => { ); } }); + +test("peer invoice prerequisites offer recovery and never request another confirmation after processing", () => { + for (const reason of [ + "exchange-keys-not-accepted", + "exchange-tos-not-accepted", + "not-proposed", + ] as const) { + const view = peerCreditConfirmationView( + { + status: "ready", + snapshot: { + type: TransactionType.PeerPullDebit, + transaction: { + ...snapshot.transaction, + type: TransactionType.PeerPullDebit, + }, + exchanges: [], + confirmation: { unavailableReasons: [reason] }, + }, + }, + "/peer-receive/invoice", + ); + assert.equal(view.enabled, false); + if (view.enabled) throw Error("unexpected confirmation"); + if (reason === "not-proposed") assert.equal(view.recovery, undefined); + else { + assert.ok(view.recovery); + assert.equal( + view.recovery.href.includes("/terms?"), + reason === "exchange-tos-not-accepted", + ); + } + } +}); diff --git a/packages/wallet-webui/test/transaction-model.test.ts b/packages/wallet-webui/test/transaction-model.test.ts @@ -322,24 +322,20 @@ test("contract-less payment failures omit unknown price fields", () => { }); test("payment details include the Penpot order summary when contract terms are requested", () => { - const view = transactionDetailView( - payment({ - contractTerms: { - summary: "Museum entry", - merchant: { name: "Museum" }, - products: [ - { - product_id: "ticket", - product_name: "Museum ticket", - description: "One admission", - quantity: 1, - unit: "ticket", - price: "CHF:5", - }, - ], - } as NonNullable<TransactionPayment["contractTerms"]>, - }), - ); + const view = transactionDetailView(payment(), undefined, { + summary: "Museum entry", + merchant: { name: "Museum" }, + products: [ + { + product_id: "ticket", + product_name: "Museum ticket", + description: "One admission", + quantity: 1, + unit: "ticket", + price: "CHF:5", + }, + ], + } as NonNullable<TransactionPayment["contractTerms"]>); assert.deepEqual(view.order, { summary: "Museum entry", products: [ @@ -388,7 +384,7 @@ test("external transaction actions require a safe URL and non-final state", () = } }); -test("integrated withdrawal confirmation is available only while non-final", () => { +test("integrated withdrawals show bank confirmation only when needed and preserve KYC", () => { const integrated = withdrawal({ txState: { major: TransactionMajorState.Dialog, @@ -409,6 +405,29 @@ test("integrated withdrawal confirmation is available only while non-final", () label: "Continue at bank", url: "https://bank.example/confirm", }); + assert.ok( + integrated.withdrawalDetails.type === + WithdrawalType.TalerBankIntegrationApi, + ); + assert.equal( + transactionDetailView({ + ...integrated, + withdrawalDetails: { ...integrated.withdrawalDetails, confirmed: true }, + }).externalAction, + undefined, + ); + assert.equal( + transactionDetailView({ + ...integrated, + txState: { + major: TransactionMajorState.Pending, + minor: TransactionMinorState.KycRequired, + }, + kycUrl: "https://exchange.example/kyc", + }).externalAction?.url, + "https://exchange.example/kyc", + ); + assert.equal( transactionDetailView({ ...integrated, @@ -454,39 +473,6 @@ test("withdrawal details expose the reserve public key as a technical identifier ); }); -test("transaction details expose an available KYC payto hash as a technical identifier", () => { - for (const txState of [ - { - major: TransactionMajorState.Pending, - minor: TransactionMinorState.KycRequired, - working: false, - }, - { - major: TransactionMajorState.Done, - minor: undefined, - working: false, - }, - ]) { - const view = transactionDetailView( - payment({ kycPaytoHash: "KYC-PAYTO-HASH", txState }), - ); - assert( - view.technicalFields?.some( - (field) => - field.label === "KYC payto hash" && - field.value === "KYC-PAYTO-HASH" && - field.breakAll && - field.copyable, - ), - ); - } - assert( - !transactionDetailView(payment()).technicalFields?.some( - (field) => field.label === "KYC payto hash", - ), - ); -}); - test("pending manual withdrawals expose transfer continuation without replay", () => { assert.deepEqual(transactionDetailView(withdrawal()).continuationAction, { kind: "withdrawal-transfer", diff --git a/packages/wallet-webui/test/transaction-observation-routes.test.tsx b/packages/wallet-webui/test/transaction-observation-routes.test.tsx @@ -0,0 +1,586 @@ +/* + * This file is part of GNU Taler + * (C) 2026 Taler Systems S.A. + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import assert from "node:assert/strict"; +import { register } from "node:module"; +import test from "node:test"; +import { Window } from "happy-dom"; +import { + ConfirmPayResultType, + NotificationType, + ObservationType, + TransactionMajorState, + TransactionMinorState, + TransactionType, + observedTransaction, + type ObserveTransactionRequest, + type StopObservationRequest, + type TransactionSnapshot, + type WalletNotification, +} from "@gnu-taler/taler-util"; +import { WalletApiOperation } from "@gnu-taler/taler-wallet-core"; +import { + createDemoServices, + demoActionUris, +} from "../src/testing/demo-wallet.js"; + +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( + kind: + | "payment-done" + | "payment-details" + | "payment-claim" + | "payment-review" + | "payment-review-details" + | "invoice" + | "withdrawal" + | "withdrawal-new" + | "bank-withdrawal", + fulfillmentUrl?: string, +) { + 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(); + Object.assign(services.platform, { target: "chrome" }); + const entry = await services.platform.actionInbox.put( + kind === "bank-withdrawal" + ? demoActionUris.withdrawal + : demoActionUris.payment, + "link", + { + fulfillmentTarget: "current-tab", + }, + ); + const navigations: { url: string; target?: string }[] = []; + services.platform.openExternal = async (url, target) => { + navigations.push({ url, target }); + }; + const completions: string[] = []; + const complete = services.platform.actionInbox.complete.bind( + services.platform.actionInbox, + ); + services.platform.actionInbox.complete = async (id) => { + completions.push(id); + await complete(id); + }; + const bankPreparation = + kind === "bank-withdrawal" + ? await services.connection.client.call( + WalletApiOperation.PrepareBankIntegratedWithdrawal, + { talerWithdrawUri: demoActionUris.withdrawal }, + ) + : undefined; + const created = + bankPreparation ?? + (kind === "withdrawal" || kind === "withdrawal-new" + ? await services.connection.client.call( + WalletApiOperation.AcceptManualWithdrawal, + { + exchangeBaseUrl: "https://exchange.demo.invalid/", + amount: "CHF:3", + }, + ) + : kind === "invoice" + ? await services.connection.client.call( + WalletApiOperation.InitiatePeerPullCredit, + { + partialContractTerms: { + amount: "CHF:3", + summary: "Lunch invoice", + purse_expiration: { t_s: 2000000000 }, + }, + }, + ) + : await services.connection.client.call( + WalletApiOperation.PreparePayForUriV2, + { + talerPayUri: demoActionUris.payment, + }, + )); + const transactionId = created.transactionId; + const transaction = await services.connection.client.call( + WalletApiOperation.GetTransactionById, + { + transactionId, + includeContractTerms: true, + }, + ); + let readySnapshot: TransactionSnapshot; + if (transaction.type === TransactionType.Payment) { + assert.ok(transaction.contractTerms); + transaction.contractTerms.fulfillment_url = fulfillmentUrl; + assert.ok(transaction.info); + transaction.info.fulfillmentUrl = fulfillmentUrl; + if (kind === "payment-done" || kind === "payment-details") + transaction.txState = { major: TransactionMajorState.Done }; + const choices = await services.connection.client.call( + WalletApiOperation.GetChoicesForPayment, + { transactionId }, + ); + const observed = observedTransaction(transaction); + assert.ok(observed.type === TransactionType.Payment); + readySnapshot = { + type: TransactionType.Payment, + transaction: observed, + exchanges: [], + payment: + kind === "payment-done" || kind === "payment-details" + ? null + : { + choices: choices.choices, + defaultChoiceIndex: choices.defaultChoiceIndex, + automaticExecution: false, + }, + confirmation: { + unavailableReasons: + kind === "payment-done" || kind === "payment-details" + ? ["not-proposed"] + : [], + }, + }; + } else if (transaction.type === TransactionType.Withdrawal) { + const observed = observedTransaction(transaction); + assert.ok(observed.type === TransactionType.Withdrawal); + readySnapshot = { + type: observed.type, + transaction: observed, + exchanges: [], + bank: bankPreparation + ? { + operationId: bankPreparation.info.operationId, + maxAmount: bankPreparation.info.maxAmount, + wireFee: bankPreparation.info.wireFee, + status: bankPreparation.info.status, + currency: bankPreparation.info.currency, + amount: bankPreparation.info.amount, + editableAmount: bankPreparation.info.editableAmount, + editableExchange: bankPreparation.info.editableExchange, + defaultExchangeBaseUrl: bankPreparation.info.defaultExchangeBaseUrl, + confirmTransferUrl: bankPreparation.info.confirmTransferUrl, + } + : undefined, + }; + } else { + assert.equal(transaction.type, TransactionType.PeerPullCredit); + const observed = observedTransaction(transaction); + assert.ok(observed.type === TransactionType.PeerPullCredit); + readySnapshot = { + type: TransactionType.PeerPullCredit, + transaction: observed, + exchanges: [], + }; + } + let snapshot = readySnapshot; + if (kind === "payment-claim") { + assert.ok(snapshot.type === TransactionType.Payment); + snapshot = { + ...snapshot, + transaction: { + ...snapshot.transaction, + info: undefined, + txState: { + major: TransactionMajorState.Pending, + minor: TransactionMinorState.ClaimProposal, + working: true, + }, + }, + payment: null, + confirmation: { unavailableReasons: ["not-proposed"] }, + }; + } + let releaseDocument!: () => void; + const documentGate = new Promise<void>((resolve) => { + releaseDocument = resolve; + }); + let documentReads = 0; + let documentError: Error | undefined; + const listeners = new Set<(n: WalletNotification) => void>(); + const subscriptions = new Map<string, number>(); + const registrations: string[] = []; + services.connection.subscribeNotifications = (listener) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }; + const emit = (notification: WalletNotification) => { + for (const listener of listeners) listener(notification); + }; + const publish = (value = snapshot) => { + snapshot = value; + for (const [observationId, revision] of subscriptions) { + subscriptions.set(observationId, revision + 1); + emit({ + type: NotificationType.ObservationSnapshot, + observationType: ObservationType.Transaction, + observationId, + transactionId, + revision: revision + 1, + snapshot, + }); + } + }; + let cancelledRequests = 0; + const paymentRequests: { + operation: WalletApiOperation; + args: unknown; + resolve: (value: unknown) => void; + reject: (error: Error) => void; + }[] = []; + const call = services.connection.client.call.bind(services.connection.client); + services.connection.client.call = async (op, args) => { + if (op === WalletApiOperation.CancelProgressToken) { + cancelledRequests++; + return {} as never; + } + if (op === WalletApiOperation.ObserveTransaction) { + const { observationId } = args as ObserveTransactionRequest; + registrations.push(observationId); + subscriptions.set(observationId, 0); + publish(); + return {} as never; + } + if (op === WalletApiOperation.StopObservation) { + subscriptions.delete((args as StopObservationRequest).observationId); + return {} as never; + } + if (op === WalletApiOperation.GetTransactionById) { + documentReads++; + await documentGate; + if (documentError) throw documentError; + return transaction as never; + } + return call(op, args); + }; + let bankConfirmations = 0; + const callForResult = services.connection.client.callForResult.bind( + services.connection.client, + ); + services.connection.client.callForResult = async (op, args) => { + if ( + op === WalletApiOperation.ConfirmPay || + op === WalletApiOperation.UnclaimPayment || + op === WalletApiOperation.ReclaimPayment || + op === WalletApiOperation.ResumeTransaction + ) { + return new Promise((resolve, reject) => + paymentRequests.push({ operation: op, args, resolve, reject }), + ) as never; + } + if ( + kind === "withdrawal-new" && + op === WalletApiOperation.AcceptManualWithdrawal + ) + return { tag: "ok", value: created } as never; + if ( + bankPreparation && + op === WalletApiOperation.PrepareBankIntegratedWithdrawal + ) + return { tag: "ok", value: bankPreparation } as never; + if (bankPreparation && op === WalletApiOperation.ConfirmWithdrawal) { + bankConfirmations++; + return { tag: "ok", value: {} } as never; + } + return callForResult(op, args); + }; + dom.location.hash = + kind === "bank-withdrawal" + ? `#/withdraw-action/${entry.id}` + : kind === "withdrawal-new" + ? "#/withdraw" + : kind === "withdrawal" || + kind === "payment-details" || + kind === "payment-review-details" + ? `#/transaction/${transactionId}` + : kind === "invoice" + ? `#/peer/share/${transactionId}/request` + : `#/pay/${transactionId}/${entry.id}`; + const view = render( + <SWRConfig value={{ provider: () => new Map(), shouldRetryOnError: false }}> + <App {...services} /> + </SWRConfig>, + ); + const waitFor = async (check: () => void) => { + for (let attempt = 0; ; attempt++) { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + }); + try { + check(); + return; + } catch (error) { + if (attempt >= 200) throw error; + } + } + }; + return { + view, + act, + waitFor, + services, + entry, + dom, + transactionId, + readySnapshot, + navigations, + completions, + registrations, + paymentRequests, + cancelledRequests: () => cancelledRequests, + bankConfirmations: () => bankConfirmations, + publish, + publishDeleted: () => { + for (const [observationId, revision] of subscriptions) { + subscriptions.delete(observationId); + emit({ + type: NotificationType.ObservationSnapshot, + observationType: ObservationType.Transaction, + observationId, + transactionId, + revision: revision + 1, + snapshot: null, + }); + } + }, + releaseDocument, + failDocument: () => { + documentError = new Error("Order document read failed"); + releaseDocument(); + }, + allowDocument: () => { + documentError = undefined; + }, + documentReads: () => documentReads, + failObservation: () => { + for (const observationId of subscriptions.keys()) { + subscriptions.delete(observationId); + emit({ + type: NotificationType.ObservationError, + observationType: ObservationType.Transaction, + observationId, + error: { code: 1, hint: "Claim updates stopped" }, + }); + } + }, + close: async () => { + cleanup(); + releaseDocument(); + services.connection.close(); + await dom.happyDOM.abort(); + }, + }; +} + +for (const [minor, label] of [ + [TransactionMinorState.KycRequired, "Identity verification required"], + [ + TransactionMinorState.BalanceKycRequired, + "Balance limit verification required", + ], +] as const) { + test(`a paid invoice share view exposes ${minor} and its transaction`, async () => { + const h = await harness("invoice"); + try { + await h.waitFor(() => + assert.ok(h.view.getByRole("button", { name: "Copy link" })), + ); + const snapshot = h.readySnapshot; + assert.ok(snapshot.type === TransactionType.PeerPullCredit); + const kycUrl = "https://exchange.example/kyc-spa/token"; + await h.act(async () => + h.publish({ + ...snapshot, + transaction: { + ...snapshot.transaction, + talerUri: undefined, + kycUrl, + txState: { major: TransactionMajorState.Pending, minor }, + }, + }), + ); + await h.waitFor(() => assert.ok(h.view.getByText(label))); + assert.equal(h.view.queryByText("Preparing a secure share link…"), null); + assert.equal(h.view.queryByRole("button", { name: "Copy link" }), null); + await h.act(async () => + h.view.getByRole("button", { name: "View transaction" }).click(), + ); + await h.waitFor(() => + assert.ok( + h.view.getByRole("button", { name: "Complete verification" }), + ), + ); + assert.equal(h.dom.location.hash, `#/transaction/${h.transactionId}`); + await h.act(async () => + h.view.getByRole("button", { name: "Complete verification" }).click(), + ); + assert.equal(h.navigations.at(-1)?.url, kycUrl); + } finally { + await h.close(); + } + }); +} + +test("payment details keep live status visible while the order document loads or fails", async () => { + const h = await harness( + "payment-details", + "https://merchant.example/fulfilled", + ); + try { + await h.waitFor(() => assert.equal(h.documentReads(), 1)); + assert.equal(h.view.queryByText("Loading transaction…"), null); + assert.ok(h.view.getByText("Completed")); + assert.ok(h.view.getByText("Loading order details…")); + await h.act(async () => h.failDocument()); + await h.waitFor(() => + assert.ok(h.view.getByRole("button", { name: "Retry order details" })), + ); + assert.ok(h.view.getByText("Completed")); + assert.equal(h.registrations.length, 1); + await h.act(async () => { + h.allowDocument(); + h.view.getByRole("button", { name: "Retry order details" }).click(); + }); + await h.waitFor(() => + assert.equal( + h.view.queryByRole("button", { name: "Retry order details" }), + null, + ), + ); + assert.equal(h.documentReads(), 2); + assert.equal(h.registrations.length, 1); + assert.ok(h.view.getByText("Completed")); + } finally { + await h.close(); + } +}); + +for (const next of ["kyc", "done", "failed", "deleted"] as const) { + test(`withdrawal instructions expose ${next} observation updates`, async () => { + const h = await harness("withdrawal"); + try { + await h.waitFor(() => + assert.ok( + h.view.getByRole("button", { + name: "View bank transfer instructions", + }), + ), + ); + await h.act(async () => + h.view + .getByRole("button", { name: "View bank transfer instructions" }) + .click(), + ); + await h.waitFor(() => + assert.ok(h.view.getByRole("heading", { name: "Pending withdrawal" })), + ); + assert.equal(h.documentReads(), 0); + const snapshot = h.readySnapshot; + assert.ok(snapshot.type === TransactionType.Withdrawal); + if (next === "failed") { + await h.act(async () => h.failObservation()); + await h.waitFor(() => + assert.ok(h.view.getByRole("button", { name: "Retry updates" })), + ); + assert.equal( + h.view.queryByRole("heading", { name: "Pending withdrawal" }), + null, + ); + await h.act(async () => + h.view.getByRole("button", { name: "Retry updates" }).click(), + ); + await h.waitFor(() => + assert.ok( + h.view.getByRole("heading", { name: "Pending withdrawal" }), + ), + ); + assert.equal(h.registrations.length, 2); + } else if (next === "deleted") { + // Deletion must dismiss instructions and discard the retained snapshot. + await h.act(async () => h.publishDeleted()); + await h.waitFor(() => + assert.ok(h.view.getByText("This transaction no longer exists.")), + ); + assert.equal( + h.view.queryByRole("heading", { name: "Pending withdrawal" }), + null, + ); + } else { + await h.act(async () => + h.publish({ + ...snapshot, + transaction: { + ...snapshot.transaction, + txState: + next === "done" + ? { major: TransactionMajorState.Done } + : { + major: TransactionMajorState.Pending, + minor: TransactionMinorState.KycRequired, + }, + kycUrl: + next === "kyc" ? "https://exchange.example/kyc" : undefined, + amountEffectiveFinal: next === "done" ? "CHF:3" : undefined, + }, + }), + ); + await h.waitFor(() => + assert.equal( + h.view.queryByRole("heading", { name: "Pending withdrawal" }), + null, + ), + ); + if (next === "kyc") + assert.ok( + h.view.getByRole("button", { name: "Complete verification" }), + ); + else assert.ok(h.view.getByText("Completed")); + assert.equal(h.registrations.length, 1); + } + } finally { + await h.close(); + } + }); +}