taler-typescript-core

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

commit c434ff2d7bc045c14ab7de47b401525758401aee
parent f09ad203cc8b653fb2d4aaf58ac1eb5a71c02ff6
Author: Florian Dold <dold@taler.net>
Date:   Wed, 11 Nov 2026 11:40:01 +0100

wallet-webui: observe withdrawals

Diffstat:
Mpackages/wallet-webui/src/api/notifications.ts | 2--
Mpackages/wallet-webui/src/routes/App.tsx | 256+++++++++++++++++++++++--------------------------------------------------------
Mpackages/wallet-webui/src/routes/withdrawal-model.ts | 22++++++++++++----------
Mpackages/wallet-webui/src/screens/WireTransferScreen.tsx | 55-------------------------------------------------------
Mpackages/wallet-webui/test/notifications.test.ts | 8++++----
Mpackages/wallet-webui/test/peer-credit-observation.test.tsx | 35+++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/test/screens.test.tsx | 41+++--------------------------------------
Mpackages/wallet-webui/test/transaction-observation-routes.test.tsx | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/wallet-webui/test/withdrawal-model.test.ts | 12++++--------
9 files changed, 285 insertions(+), 300 deletions(-)

diff --git a/packages/wallet-webui/src/api/notifications.ts b/packages/wallet-webui/src/api/notifications.ts @@ -22,8 +22,6 @@ export const familyOperations: Record<WalletKeyFamily, readonly string[]> = { transactions: [ WalletApiOperation.GetTransactions, WalletApiOperation.GetTransactionsV2, - WalletApiOperation.GetTransactionById, - WalletApiOperation.GetChoicesForPayment, ], exchanges: [ WalletApiOperation.ListExchanges, diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -22,8 +22,6 @@ import { TransactionType, } from "@gnu-taler/taler-util"; import type { - AcceptManualWithdrawalResult, - PrepareBankIntegratedWithdrawalResponse, AmountString, CheckDepositResponse, ScopeInfo, @@ -126,8 +124,6 @@ import { import { usePaymentFulfillment } from "./payment-fulfillment.js"; import { depositKycAuthWireOptions, - shouldPollIntegratedWithdrawal, - wireOptions, integratedWithdrawalView, isIntegratedWithdrawalTerminal, transactionWireOptions, @@ -2737,16 +2733,6 @@ function WithdrawalRoute( const [prepared, setPrepared] = useState<WithdrawalPreparation | undefined>( () => loadWithdrawalGateDraft(returnTo), ); - const [accepted, setAccepted] = useState<AcceptManualWithdrawalResult>(); - const acceptedTransaction = useWalletQuery( - connection, - WalletApiOperation.GetTransactionById, - { - transactionId: (accepted?.transactionId ?? "") as TransactionIdStr, - includeContractTerms: true, - }, - { enabled: accepted !== undefined }, - ); let providers: WithdrawalProviderView[] | undefined; if (props.exchangeAction) { providers = [props.exchangeAction.provider]; @@ -2871,7 +2857,7 @@ function WithdrawalRoute( ); } else { clearWithdrawalGateDraft(); - setAccepted(result.value); + window.location.hash = `/transaction/${result.value.transactionId}?transfer=1`; void completeActionBestEffort(platform.actionInbox, actionId); } } catch (cause) { @@ -2886,54 +2872,6 @@ function WithdrawalRoute( setAccepting(false); } }; - if (prepared && accepted) { - const withdrawal = - acceptedTransaction.data?.type === TransactionType.Withdrawal - ? acceptedTransaction.data - : undefined; - const current = withdrawal - ? transactionDetailView(withdrawal, language) - : undefined; - const outcome = - current && !current.pending - ? { - title: - current.state === "Completed" - ? /* Translators: Withdrawing adds digital cash to this wallet, usually funded by a bank transfer; it does not cash out the wallet to a bank account. */ i18n.str`Withdrawal completed` - : // Translators: Outcome heading; %1$s is an already translated withdrawal status. - i18n.str`Withdrawal: ${current.state}`, - detail: - current.state === "Completed" - ? /* Translators: %1$s is a formatted amount, including its currency. */ i18n.str`${current.amount} is now reflected in your wallet balance.` - : current.statusDetail, - success: current.tone === "success", - } - : undefined; - const options = withdrawal - ? transactionWireOptions(withdrawal, [language]) - : wireOptions(accepted.withdrawalAccountsList, { - languages: [language], - }); - return ( - <WireTransferScreen - amountRaw={withdrawal?.amountRaw ?? prepared.details.amountRaw} - amountEffective={ - withdrawal?.amountEffective ?? prepared.details.amountEffective - } - exchange={ - withdrawal?.exchangeBaseUrl ?? prepared.provider.exchangeBaseUrl - } - options={options} - outcome={outcome} - onCopy={(value) => void navigator.clipboard.writeText(value)} - onOpenExternal={(uri) => void platform.openExternal(uri)} - onDone={() => - navigate(outcome ? `/transaction/${accepted.transactionId}` : "/") - } - onViewWallet={outcome ? () => navigate("/") : undefined} - /> - ); - } if (prepared) { const review = withdrawalReviewModel( prepared, @@ -3527,9 +3465,6 @@ function IntegratedWithdrawalRoute() { const [, navigate] = useLocation(); const callMutation = useWalletMutation(connection); const { controller: progressRequest } = useWalletProgress(connection); - const { controller: pollProgressRequest } = useWalletProgress(connection, { - visible: false, - }); const durability = useDurability(); const returnTo = `/withdraw-action/${params?.actionId ?? ""}`; const allExchanges = useWalletQuery( @@ -3539,12 +3474,16 @@ function IntegratedWithdrawalRoute() { ); const [entry, setEntry] = useState<Awaited<ReturnType<typeof platform.actionInbox.get>>>(); - const [preparation, setPreparation] = - useState<PrepareBankIntegratedWithdrawalResponse>(); + const [transactionId, setTransactionId] = useState<TransactionIdStr>(); const [prepared, setPrepared] = useState<WithdrawalPreparation | undefined>( () => loadWithdrawalGateDraft(returnTo), ); - const [accepted, setAccepted] = useState(false); + const bankView = useTransactionObservation(connection, transactionId); + const bankSnapshot = + bankView.snapshot?.type === TransactionType.Withdrawal + ? bankView.snapshot + : undefined; + const bankTransaction = bankSnapshot?.transaction; const [loading, setLoading] = useState(true); const [preparing, setPreparing] = useState(false); const [accepting, setAccepting] = useState(false); @@ -3559,7 +3498,7 @@ function IntegratedWithdrawalRoute() { if (!action) { if (isActive()) { setEntry(undefined); - setPreparation(undefined); + setTransactionId(undefined); setError( localError( /* Translators: Withdrawing adds digital cash to this wallet, usually funded by a bank transfer; it does not cash out the wallet to a bank account. */ i18n.str`This withdrawal action expired or was already completed.`, @@ -3576,7 +3515,7 @@ function IntegratedWithdrawalRoute() { parsed.value.type !== TalerUriAction.Withdraw ) { if (isActive()) { - setPreparation(undefined); + setTransactionId(undefined); setError( localError( /* Translators: Withdrawing adds digital cash to this wallet, usually funded by a bank transfer; it does not cash out the wallet to a bank account. */ i18n.str`This action is not a valid bank withdrawal.`, @@ -3593,7 +3532,7 @@ function IntegratedWithdrawalRoute() { ); if (!isActive()) return; if (Result.isError(result)) { - setPreparation(undefined); + setTransactionId(undefined); setError( walletErrorHint( result.detail, @@ -3601,7 +3540,7 @@ function IntegratedWithdrawalRoute() { ), ); } else { - setPreparation(result.value); + setTransactionId(result.value.transactionId); } setLoading(false); }, @@ -3613,7 +3552,7 @@ function IntegratedWithdrawalRoute() { if (!isActive()) return; setLoading(false); if (isProgressRequestCancelled(cause)) return; - setPreparation(undefined); + setTransactionId(undefined); setError( errorFromException( cause, @@ -3634,77 +3573,25 @@ function IntegratedWithdrawalRoute() { useEffect(() => { if ( entry && - preparation && - isIntegratedWithdrawalTerminal(preparation.info.status) + transactionId && + bankView.ready && + bankTransaction && + (isIntegratedWithdrawalTerminal( + bankSnapshot?.bank?.status ?? "pending", + ) || + [ + TransactionMajorState.Done, + TransactionMajorState.Aborted, + TransactionMajorState.Failed, + TransactionMajorState.Expired, + ].includes(bankTransaction.txState.major)) ) { void completeActionBestEffort(platform.actionInbox, entry.id); } - }, [entry, platform, preparation]); - useEffect(() => { - if ( - !entry || - !preparation || - !shouldPollIntegratedWithdrawal(preparation.info.status) - ) - return; - let active = true; - let timer: number | undefined; - const schedule = () => { - timer = window.setTimeout(() => void refresh(), 2_000); - }; - const refresh = async () => { - if (!active) return; - if (document.visibilityState === "hidden") { - schedule(); - return; - } - try { - const result = await pollProgressRequest.callAndInvalidate( - WalletApiOperation.PrepareBankIntegratedWithdrawal, - { talerWithdrawUri: entry.uri }, - ["transactions"], - ); - if (!active) return; - if (Result.isError(result)) { - setError( - walletErrorHint( - result.detail, - /* Translators: Withdrawing adds digital cash to this wallet, usually funded by a bank transfer; it does not cash out the wallet to a bank account. */ i18n.str`The bank withdrawal status could not be refreshed.`, - ), - ); - } else { - setPreparation(result.value); - setError(undefined); - } - } catch (cause) { - if (active && !isProgressRequestCancelled(cause)) - setError( - errorFromException( - cause, - i18n.str`The bank withdrawal status could not be refreshed.`, - ), - ); - } finally { - if (active) schedule(); - } - }; - const onVisibility = () => { - if (document.visibilityState === "visible") { - if (timer !== undefined) window.clearTimeout(timer); - void refresh(); - } - }; - document.addEventListener("visibilitychange", onVisibility); - schedule(); - return () => { - active = false; - if (timer !== undefined) window.clearTimeout(timer); - document.removeEventListener("visibilitychange", onVisibility); - }; - }, [entry, pollProgressRequest, preparation]); + }, [entry, platform, transactionId, bankView.snapshot, bankView.ready]); const cancel = async () => { if (cancelling) return; - if (preparation) { + if (transactionId) { setCancelling(true); setError(undefined); try { @@ -3712,7 +3599,7 @@ function IntegratedWithdrawalRoute() { () => callMutation( WalletApiOperation.AbortTransaction, - { transactionId: preparation.transactionId }, + { transactionId }, ["transactions"], ), () => void completeActionBestEffort(platform.actionInbox, entry?.id), @@ -3757,7 +3644,7 @@ function IntegratedWithdrawalRoute() { provider.exchangeBaseUrl, amount, restrictAge, - preparation?.transactionId, + transactionId, ), ["exchanges"], ); @@ -3790,7 +3677,7 @@ function IntegratedWithdrawalRoute() { cashAcceptorProvider?: WithdrawalProviderView, cashAcceptorAge?: number, ) => { - if (!preparation) return; + if (!transactionId || !bankView.ready) return; const provider = prepared?.provider ?? cashAcceptorProvider; if (!provider) return; if (!(await durability.guardValueOperation())) return; @@ -3802,7 +3689,7 @@ function IntegratedWithdrawalRoute() { const result = await progressRequest.callAndInvalidate( WalletApiOperation.ConfirmWithdrawal, { - transactionId: preparation.transactionId, + transactionId, exchangeBaseUrl: provider.exchangeBaseUrl, ...(prepared ? { amount: prepared.amount } : {}), ...(restrictAge === undefined ? {} : { restrictAge }), @@ -3819,17 +3706,6 @@ function IntegratedWithdrawalRoute() { ); } else { clearWithdrawalGateDraft(); - setAccepted(true); - setPreparation({ - ...preparation, - info: { - ...preparation.info, - status: "selected", - confirmTransferUrl: - result.value.confirmTransferUrl ?? - preparation.info.confirmTransferUrl, - }, - }); } } catch (cause) { if (!isProgressRequestCancelled(cause)) @@ -3843,7 +3719,7 @@ function IntegratedWithdrawalRoute() { setAccepting(false); } }; - if (loading || !preparation) + if (loading || !transactionId) return ( <ActionScreen state={loading ? `loading` : `error`} @@ -3854,34 +3730,50 @@ function IntegratedWithdrawalRoute() { onCancel={() => void cancel()} /> ); - const info = preparation.info; - const setup = integratedWithdrawalView(info); - const cashAcceptor = info.amount === undefined && !info.editableAmount; - if (accepted && (info.status === "pending" || info.status === "selected")) { - const confirmationUrl = safeWebUrl(info.confirmTransferUrl) - ? info.confirmTransferUrl - : undefined; + if ( + bankTransaction && + bankView.ready && + bankTransaction.txState.major !== TransactionMajorState.Dialog && + (bankTransaction.error || + bankSnapshot?.bank?.status === "pending" || + bankTransaction.txState.major !== TransactionMajorState.Pending || + ![ + TransactionMinorState.BankConfirmTransfer, + TransactionMinorState.ExchangeWaitReserve, + ].includes(bankTransaction.txState.minor!)) + ) { return ( - <BankConfirmationScreen - amount={ - prepared?.amount ?? - info.amount ?? - i18n.str`Amount selected at cash acceptor` - } - exchange={ - prepared?.provider.exchangeBaseUrl ?? - info.defaultExchangeBaseUrl ?? - /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`Selected exchange` - } - status="selected" - hasConfirmationUrl={Boolean(confirmationUrl)} - onContinueToBank={() => { - if (confirmationUrl) void platform.openExternal(confirmationUrl); - }} - onViewWallet={() => navigate("/")} + <TransactionDetailView + transactionId={bankTransaction.transactionId} + view={bankView} /> ); } + const observedBank = bankSnapshot?.bank; + if (!observedBank || !bankView.ready) + return ( + <ActionScreen + state={bankView.error ? "error" : "loading"} + actionKind="withdraw" + error={ + bankView.error + ? errorFromException( + bankView.error, + i18n.str`Transaction updates stopped.`, + ) + : undefined + } + onRetry={bankView.retry} + onContinue={() => {}} + onCancel={() => void cancel()} + /> + ); + const info = observedBank; + const setup = integratedWithdrawalView( + info, + allExchanges.data?.exchanges ?? [], + ); + const cashAcceptor = info.amount === undefined && !info.editableAmount; if (info.status !== "pending") { const confirmationUrl = safeWebUrl(info.confirmTransferUrl) ? info.confirmTransferUrl @@ -3900,9 +3792,7 @@ function IntegratedWithdrawalRoute() { }} onViewWallet={() => navigate( - info.status === "confirmed" - ? `/transaction/${preparation.transactionId}` - : "/", + info.status === "confirmed" ? `/transaction/${transactionId}` : "/", ) } viewLabel={ diff --git a/packages/wallet-webui/src/routes/withdrawal-model.ts b/packages/wallet-webui/src/routes/withdrawal-model.ts @@ -8,10 +8,11 @@ import { isSafeExternalUrl, type AccountRestriction, type InternationalizedString, + type ObservedBankWithdrawal, + type ExchangeListItem, type ObservedDepositTransaction, type ObservedWithdrawalTransaction, type WithdrawalExchangeAccountDetails, - type WithdrawUriInfoResponse, } from "@gnu-taler/taler-util"; import type { WithdrawalProviderView } from "../screens/WithdrawalScreen.js"; import { i18n } from "../i18n/runtime.js"; @@ -47,14 +48,8 @@ export interface IntegratedWithdrawalView { maximumAmount?: string; } -export function shouldPollIntegratedWithdrawal( - status: WithdrawUriInfoResponse["status"], -): boolean { - return status === "selected"; -} - export function isIntegratedWithdrawalTerminal( - status: WithdrawUriInfoResponse["status"], + status: ObservedBankWithdrawal["status"], ): boolean { return status === "confirmed" || status === "aborted"; } @@ -75,10 +70,17 @@ function amountValue( } export function integratedWithdrawalView( - info: WithdrawUriInfoResponse, + info: ObservedBankWithdrawal, + exchanges: ExchangeListItem[], ): IntegratedWithdrawalView { const providers = new Map<string, WithdrawalProviderView>(); - for (const exchange of info.possibleExchanges) { + for (const exchange of exchanges) { + if ( + exchange.currency !== info.currency || + (!info.editableExchange && + exchange.exchangeBaseUrl !== info.defaultExchangeBaseUrl) + ) + continue; providers.set(exchange.exchangeBaseUrl, { exchangeBaseUrl: exchange.exchangeBaseUrl, currency: exchange.currency, diff --git a/packages/wallet-webui/src/screens/WireTransferScreen.tsx b/packages/wallet-webui/src/screens/WireTransferScreen.tsx @@ -14,11 +14,9 @@ export function WireTransferScreen(props: { purpose?: "withdrawal" | "deposit-kyc-auth"; debitPaytoUri?: string; accountPub?: string; - outcome?: { title: string; detail: string; success: boolean }; onCopy: (value: string) => void; onOpenExternal: (uri: string) => void; onDone: () => void; - onViewWallet?: () => void; }) { const isKycAuth = props.purpose === "deposit-kyc-auth"; const [copied, setCopied] = useState<{ optionId: string; value: string }>(); @@ -53,59 +51,6 @@ export function WireTransferScreen(props: { const wasCopied = (optionId: string, value: string) => copied?.optionId === optionId && copied.value === value; - if (props.outcome) { - return ( - <div class="mx-auto max-w-2xl space-y-6"> - <div class="flex items-center gap-4"> - <button - type="button" - onClick={props.onDone} - aria-label={i18n.str`Back to transaction`} - class="grid h-11 w-11 place-items-center rounded-full text-2xl hover:bg-secondaryContainer" - > - ← - </button> - <div> - <h1 class="text-2xl font-medium">{props.outcome.title}</h1> - <p class="break-all text-sm italic text-secondary"> - {props.exchange} - </p> - </div> - </div> - <Card - class={ - props.outcome.success - ? `border-success bg-successContainer` - : `border-warning bg-warningContainer` - } - > - <div class="flex items-start gap-3"> - <span aria-hidden="true" class="text-2xl"> - {props.outcome.success ? "✓" : "!"} - </span> - <div> - <h2 class="font-semibold">{i18n.str`Transfer instructions are no longer needed`}</h2> - <p role="status" class="mt-2"> - {props.outcome.detail} - </p> - </div> - </div> - </Card> - <div class="flex flex-wrap justify-end gap-3"> - <Button - tone="secondary" - onClick={props.onDone} - >{i18n.str`View transaction`}</Button> - {props.onViewWallet && ( - <Button - onClick={props.onViewWallet} - >{i18n.str`View wallet`}</Button> - )} - </div> - </div> - ); - } - return ( <div class="mx-auto max-w-2xl space-y-6"> <div class="flex items-center gap-4"> diff --git a/packages/wallet-webui/test/notifications.test.ts b/packages/wallet-webui/test/notifications.test.ts @@ -12,8 +12,8 @@ test("balance changes invalidate balances and transactions", () => { assert(operations.has(WalletApiOperation.GetBalances)); assert(operations.has(WalletApiOperation.GetTransactions)); assert(operations.has(WalletApiOperation.GetTransactionsV2)); - assert(operations.has(WalletApiOperation.GetTransactionById)); - assert(operations.has(WalletApiOperation.GetChoicesForPayment)); + assert.equal(operations.has(WalletApiOperation.GetTransactionById), false); + assert.equal(operations.has(WalletApiOperation.GetChoicesForPayment), false); assert(operations.has(WalletApiOperation.ListDiscounts)); assert(operations.has(WalletApiOperation.ListSubscriptions)); }); @@ -25,7 +25,7 @@ test("idle does not cause broad revalidation", () => { ); }); -test("transaction transitions refresh a visible withdrawal detail", () => { +test("transaction transitions refresh lists and balances without reloading observed details", () => { const operations = operationsForNotification({ type: NotificationType.TransactionStateTransition, transactionId: "txn:withdrawal:test", @@ -34,6 +34,6 @@ test("transaction transitions refresh a visible withdrawal detail", () => { newTxState: { major: TransactionMajorState.Done }, newStId: 1, }); - assert(operations.has(WalletApiOperation.GetTransactionById)); + assert.equal(operations.has(WalletApiOperation.GetTransactionById), false); assert(operations.has(WalletApiOperation.GetBalances)); }); diff --git a/packages/wallet-webui/test/peer-credit-observation.test.tsx b/packages/wallet-webui/test/peer-credit-observation.test.tsx @@ -747,6 +747,41 @@ test("invoice review retries failed observations without preparing again", async } }); +test("a completed withdrawal overrides stale bank status and completes the inbox action", async () => { + const h = await harness("paste", "bank"); + try { + await h.waitFor(() => assert(h.view.getAllByText("Completed").length)); + assert.equal( + await h.services.platform.actionInbox.get(h.entry.id), + undefined, + ); + assert.equal( + h.view.queryByRole("button", { name: "Continue to bank" }), + null, + ); + assert.equal( + h.calls.filter((op) => op === WalletApiOperation.ObserveTransaction) + .length, + 1, + ); + await h.act(async () => h.failObserved()); + await h.waitFor(() => + assert.ok(h.view.getByRole("button", { name: "Retry" })), + ); + await h.act(async () => + h.view.getByRole("button", { name: "Retry" }).click(), + ); + await h.waitFor(() => assert.ok(h.view.getAllByText("Completed").length)); + 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); diff --git a/packages/wallet-webui/test/screens.test.tsx b/packages/wallet-webui/test/screens.test.tsx @@ -2544,7 +2544,9 @@ for (const mode of ["send", "request"] as const) { view.rerender(screen([])); assert.match( view.getByRole("alert").textContent ?? "", - new RegExp(`before ${mode === "send" ? "sending" : "requesting"} money`), + new RegExp( + `before ${mode === "send" ? "sending" : "requesting"} money`, + ), ); assert.equal(view.queryByRole("combobox"), null); assert.equal(view.queryByRole("button", { name: "Review" }), null); @@ -4094,43 +4096,6 @@ test("transaction details continue a pending manual withdrawal", async () => { await window.happyDOM.abort(); }); -test("completed withdrawals replace obsolete transfer instructions in place", async () => { - const window = installDom(); - const { render, cleanup } = await import("@testing-library/preact"); - const view = render( - <main> - <WireTransferScreen - amountRaw="CHF:11.23" - amountEffective="CHF:10" - exchange="https://exchange.example/" - options={[ - { - id: "bank", - label: "Bank transfer", - fields: [{ label: "Payment reference", value: "RESERVE" }], - }, - ]} - outcome={{ - title: "Withdrawal completed", - detail: "CHF:10 is now reflected in your wallet balance.", - success: true, - }} - onCopy={() => {}} - onOpenExternal={() => {}} - onDone={() => {}} - onViewWallet={() => {}} - /> - </main>, - ); - assert(view.getByRole("heading", { name: "Withdrawal completed" })); - assert(view.getByRole("status")); - assert.equal(view.queryByText("RESERVE"), null); - assert(view.getByRole("button", { name: "View transaction" })); - assert(view.getByRole("button", { name: "View wallet" })); - cleanup(); - await window.happyDOM.abort(); -}); - test("deposit KYC authentication identifies the source and keeps all transfer options", async () => { const window = installDom(); const { render, cleanup } = await import("@testing-library/preact"); diff --git a/packages/wallet-webui/test/transaction-observation-routes.test.tsx b/packages/wallet-webui/test/transaction-observation-routes.test.tsx @@ -689,6 +689,160 @@ for (const next of ["kyc", "done", "failed", "deleted"] as const) { }); } +test("a new manual withdrawal shares instruction and KYC tracking with transaction details", async () => { + const h = await harness("withdrawal-new"); + try { + await h.waitFor(() => + assert.ok( + h.view.getByRole("textbox", { name: "Amount to withdraw in CHF" }), + ), + ); + const { userEvent } = await import("@testing-library/user-event"); + const user = userEvent.setup({ + document: h.dom.document as unknown as Document, + }); + await user.type( + h.view.getByRole("textbox", { name: "Amount to withdraw in CHF" }), + "3", + ); + await user.click( + h.view.getByRole("button", { name: "Withdraw", exact: true }), + ); + await h.waitFor(() => + assert.ok(h.view.getByRole("heading", { name: "Review withdrawal" })), + ); + await h.waitFor(() => + assert.equal( + ( + h.view.getByRole("button", { + name: "Withdraw", + exact: true, + }) as HTMLButtonElement + ).disabled, + false, + ), + ); + await user.click( + h.view.getByRole("button", { name: "Withdraw", exact: true }), + ); + await h.waitFor(() => + assert.ok(h.view.getByRole("heading", { name: "Pending withdrawal" })), + ); + const snapshot = h.readySnapshot; + assert.ok(snapshot.type === TransactionType.Withdrawal); + assert.equal(h.registrations.length, 1); + await h.act(async () => + h.publish({ + ...snapshot, + transaction: { + ...snapshot.transaction, + txState: { + major: TransactionMajorState.Pending, + minor: TransactionMinorState.KycRequired, + }, + kycUrl: "https://exchange.example/kyc", + }, + }), + ); + await h.waitFor(() => + assert.ok(h.view.getByRole("button", { name: "Complete verification" })), + ); + assert.equal(h.registrations.length, 1); + assert.equal(h.documentReads(), 0); + } finally { + await h.close(); + } +}); + +test("bank withdrawal progress follows snapshots after confirmation", async () => { + const h = await harness("bank-withdrawal"); + try { + await h.waitFor(() => + assert.ok( + h.view.getByRole("heading", { name: "Withdraw from your bank" }), + ), + ); + await h.act(async () => + h.view.getByRole("button", { name: "Withdraw", exact: true }).click(), + ); + await h.waitFor(() => { + assert.ok(h.view.getByRole("heading", { name: "Review withdrawal" })); + assert.equal( + ( + h.view.getByRole("button", { + name: "Withdraw", + exact: true, + }) as HTMLButtonElement + ).disabled, + false, + ); + }); + await h.act(async () => + h.view.getByRole("button", { name: "Withdraw", exact: true }).click(), + ); + await h.waitFor(() => assert.equal(h.bankConfirmations(), 1)); + assert.equal( + h.view.queryByRole("heading", { name: "Confirm with your bank" }), + null, + ); + const initial = h.readySnapshot; + assert.ok(initial.type === TransactionType.Withdrawal && initial.bank); + const bank = initial.bank; + const registering: TransactionSnapshot = { + ...initial, + transaction: { + ...initial.transaction, + txState: { + major: TransactionMajorState.Pending, + minor: TransactionMinorState.BankRegisterReserve, + }, + }, + }; + await h.act(async () => h.publish(registering)); + await h.waitFor(() => + assert.ok(h.view.getByText("Registering withdrawal with bank")), + ); + const selected: TransactionSnapshot = { + ...registering, + bank: { ...bank, status: "selected" }, + transaction: { + ...registering.transaction, + txState: { + major: TransactionMajorState.Pending, + minor: TransactionMinorState.BankConfirmTransfer, + }, + }, + }; + await h.act(async () => h.publish(selected)); + await h.waitFor(() => + assert.ok( + h.view.getByRole("heading", { name: "Confirm with your bank" }), + ), + ); + await h.act(async () => + h.publish({ + ...selected, + bank: { ...bank, status: "confirmed" }, + transaction: { + ...selected.transaction, + txState: { + major: TransactionMajorState.Pending, + minor: TransactionMinorState.KycRequired, + }, + kycUrl: "https://exchange.example/kyc", + }, + }), + ); + await h.waitFor(() => + assert.ok(h.view.getByRole("button", { name: "Complete verification" })), + ); + assert.equal(h.registrations.length, 1); + assert.equal(h.documentReads(), 0); + } finally { + await h.close(); + } +}); + for (const route of ["payment-review", "payment-review-details"] as const) { for (const order of ["response-first", "snapshot-first"] as const) { test(`${route} takes completion from snapshots when ${order}`, async () => { diff --git a/packages/wallet-webui/test/withdrawal-model.test.ts b/packages/wallet-webui/test/withdrawal-model.test.ts @@ -11,16 +11,11 @@ import { depositKycAuthWireOptions, integratedWithdrawalView, isIntegratedWithdrawalTerminal, - shouldPollIntegratedWithdrawal, transactionWireOptions, wireOptions, } from "../src/routes/withdrawal-model.js"; -test("integrated withdrawal status drives polling and terminal handling", () => { - assert.equal(shouldPollIntegratedWithdrawal("pending"), false); - assert.equal(shouldPollIntegratedWithdrawal("selected"), true); - assert.equal(shouldPollIntegratedWithdrawal("confirmed"), false); - assert.equal(shouldPollIntegratedWithdrawal("aborted"), false); +test("integrated withdrawal status drives terminal handling", () => { assert.equal(isIntegratedWithdrawalTerminal("pending"), false); assert.equal(isIntegratedWithdrawalTerminal("selected"), false); assert.equal(isIntegratedWithdrawalTerminal("confirmed"), true); @@ -335,7 +330,7 @@ test("integrated withdrawal setup preserves bank restrictions", () => { editableExchange: false, possibleExchanges: [], } as WithdrawUriInfoResponse; - const view = integratedWithdrawalView(info); + const view = integratedWithdrawalView(info, info.possibleExchanges); assert.equal(view.initialAmount, "12.5"); assert.equal( view.maximumAmount, @@ -370,7 +365,8 @@ test("integrated withdrawal setup preserves exchange age choices", () => { ], } as WithdrawUriInfoResponse; assert.deepEqual( - integratedWithdrawalView(info).providers[0].ageRestrictionOptions, + integratedWithdrawalView(info, info.possibleExchanges).providers[0] + .ageRestrictionOptions, [8, 12, 16, 18], ); });