taler-typescript-core

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

commit 9a75edcd783a79dfcc932812092f6c35a083ac1e
parent b31d095e7c8be6f08427aa547ba762a374cb4b81
Author: Florian Dold <dold@taler.net>
Date:   Wed, 25 Nov 2026 16:07:12 +0100

wallet web UI: explain insufficient funds for deposits and peer payments

Issue: https://bugs.taler.net/n/12074

Diffstat:
Mpackages/wallet-webui/src/routes/App.tsx | 5+++--
Mpackages/wallet-webui/src/routes/exchange-key-recovery-model.ts | 11-----------
Mpackages/wallet-webui/src/ui/error.ts | 167++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mpackages/wallet-webui/test/error.test.ts | 226++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/wallet-webui/test/transaction-observation-routes.test.tsx | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 414 insertions(+), 49 deletions(-)

diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -113,6 +113,8 @@ import { ErrorCard } from "../ui/ErrorCard.js"; import { RequestProgressPanel } from "../ui/RequestProgress.js"; import { errorFromException, + insufficientBalanceDetailsFromError, + insufficientBalanceMessage, localError, walletCoreError, type ErrorPresentation, @@ -161,7 +163,6 @@ import { import { exchangeKeyRecoveryFromError, exchangeKeyRecoveryFromInsufficientBalance, - insufficientBalanceDetailsFromError, type ExchangeKeyRecovery, } from "./exchange-key-recovery-model.js"; import { @@ -1828,7 +1829,7 @@ function PeerCreateRoute(props: { mode: "send" | "request" }) { scope, insufficient: recovery?.message ?? - i18n.str`The wallet does not have enough compatible funds for this transfer.`, + insufficientBalanceMessage(result.value.insufficientBalanceDetails), ...(recovery ? { recovery } : {}), }); } else { diff --git a/packages/wallet-webui/src/routes/exchange-key-recovery-model.ts b/packages/wallet-webui/src/routes/exchange-key-recovery-model.ts @@ -77,17 +77,6 @@ export function exchangeKeyRecoveryFromInsufficientBalance( }; } -export function insufficientBalanceDetailsFromError( - detail: unknown, -): PaymentInsufficientBalanceDetails | undefined { - if (!detail || typeof detail !== "object") return undefined; - const value = (detail as { insufficientBalanceDetails?: unknown }) - .insufficientBalanceDetails; - return value && typeof value === "object" - ? (value as PaymentInsufficientBalanceDetails) - : undefined; -} - export function exchangeKeyRecoveryFromError( detail: unknown, ): ExchangeKeyRecovery | undefined { diff --git a/packages/wallet-webui/src/ui/error.ts b/packages/wallet-webui/src/ui/error.ts @@ -1,4 +1,5 @@ import { + Amounts, CoinSelectionFailureReasonType, InsufficientBalanceHint, TalerError, @@ -27,14 +28,6 @@ function errorMessage(detail: TalerErrorDetail, fallback: string): string { return i18n.str`This order was already paid.`; case TalerErrorCode.WALLET_MERCHANT_ORDER_NOT_FOUND: return i18n.str`The merchant order no longer exists or has expired.`; - case TalerErrorCode.WALLET_PAY_MERCHANT_INSUFFICIENT_BALANCE: - return insufficientBalanceMessage( - ( - detail as { - insufficientBalanceDetails?: PaymentInsufficientBalanceDetails; - } - ).insufficientBalanceDetails, - ); case TalerErrorCode.WALLET_NETWORK_ERROR: return i18n.str`The wallet could not reach the service.`; case TalerErrorCode.WALLET_HTTP_REQUEST_GENERIC_TIMEOUT: @@ -86,8 +79,6 @@ function errorGuidance(detail: TalerErrorDetail): string | undefined { return i18n.str`Return to the merchant to view the completed purchase.`; case TalerErrorCode.WALLET_MERCHANT_ORDER_NOT_FOUND: return i18n.str`Return to the merchant and create a new order.`; - case TalerErrorCode.WALLET_PAY_MERCHANT_INSUFFICIENT_BALANCE: - return /* 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`Withdraw funds or choose another payment option, then try again.`; case TalerErrorCode.WALLET_NETWORK_ERROR: case TalerErrorCode.WALLET_HTTP_REQUEST_GENERIC_TIMEOUT: case TalerErrorCode.GENERIC_TIMEOUT: @@ -100,6 +91,32 @@ function errorGuidance(detail: TalerErrorDetail): string | undefined { } } +function depositWireMethodUnsupported( + detail: PaymentInsufficientBalanceDetails | undefined, +): boolean { + // Core also reports same-currency exchanges outside the deposit's scope + // and exchanges the receiver does not accept. + const candidates = Object.values(detail?.exchanges ?? {}).filter( + (exchange) => + !exchange.reasons.some( + ({ type }) => + type === CoinSelectionFailureReasonType.ScopeRestricted || + type === CoinSelectionFailureReasonType.ReceiverNotAccepted || + type === + CoinSelectionFailureReasonType.ReceiverExchangeMasterPubMismatch, + ), + ); + return ( + candidates.length > 0 && + candidates.every((exchange) => + exchange.reasons.some( + ({ type }) => + type === CoinSelectionFailureReasonType.WireMethodUnsupported, + ), + ) + ); +} + export function walletCoreError( detail: unknown, fallback: string, @@ -112,6 +129,37 @@ export function walletCoreError( return localError(fallback); } const errorDetail = detail as TalerErrorDetail; + switch (errorDetail.code) { + case TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE: + case TalerErrorCode.WALLET_PAY_MERCHANT_INSUFFICIENT_BALANCE: + case TalerErrorCode.WALLET_PEER_PULL_PAYMENT_INSUFFICIENT_BALANCE: + case TalerErrorCode.WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE: { + const balance = insufficientBalanceDetailsFromError(errorDetail); + const cause = insufficientBalanceCause(balance); + if ( + errorDetail.code === + TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE + ) { + if (depositWireMethodUnsupported(balance)) { + return { + message: /* Translators: A deposit transfers digital cash from the wallet to a bank account. */ i18n.str`No exchange available for this deposit supports this type of bank account.`, + detail: errorDetail, + }; + } + if (cause === InsufficientBalanceHint.MerchantDepositInsufficient) { + return { + message: /* Translators: A deposit transfers digital cash from the wallet to a bank account. */ i18n.str`The exchanges holding your funds cannot transfer the requested amount to this bank account.`, + detail: errorDetail, + }; + } + } + return { + message: insufficientBalanceMessage(balance, cause, errorDetail.code), + guidance: /* 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`Withdraw funds or choose another payment option, then try again.`, + detail: errorDetail, + }; + } + } const guidance = errorGuidance(errorDetail); return { message: errorMessage(errorDetail, fallback), @@ -133,33 +181,61 @@ export function errorFromException( return localError(fallback); } -export function insufficientBalanceMessage( +export function insufficientBalanceDetailsFromError( + detail: unknown, +): PaymentInsufficientBalanceDetails | undefined { + if ( + !detail || + typeof detail !== "object" || + !("insufficientBalanceDetails" in detail) + ) + return undefined; + const value = detail.insufficientBalanceDetails; + return value && typeof value === "object" + ? (value as PaymentInsufficientBalanceDetails) + : undefined; +} + +function insufficientBalanceCause( detail: PaymentInsufficientBalanceDetails | undefined, -): string { - if (!detail) - return i18n.str`The wallet does not have enough compatible funds.`; +) { + if (!detail) return undefined; + const reasons = detail.reasons?.map((reason) => reason.type); if ( - detail.reasons?.some( - (reason) => - reason.type === - CoinSelectionFailureReasonType.SupersededExchangeMasterPub, + reasons?.includes( + CoinSelectionFailureReasonType.SupersededExchangeMasterPub, ) ) - return /* Translators: Legacy funds belong to a previous cryptographic identity of an exchange, not merely an old wallet software version. */ i18n.str`Some funds were issued under legacy exchange keys and cannot be used for this operation.`; - const exchangeHints = Array.from( - new Set( - Object.values(detail.perExchange ?? {}).flatMap((exchange) => - exchange.causeHint ? [exchange.causeHint] : [], - ), + return CoinSelectionFailureReasonType.SupersededExchangeMasterPub; + if (reasons?.includes(CoinSelectionFailureReasonType.BalanceFragmented)) + return CoinSelectionFailureReasonType.BalanceFragmented; + if (detail.causeHint) return detail.causeHint; + if (reasons?.includes(CoinSelectionFailureReasonType.FeesNotCovered)) + return InsufficientBalanceHint.FeesNotCovered; + const exchangeHints = new Set( + Object.values(detail.perExchange ?? {}).flatMap((exchange) => + exchange.causeHint ? [exchange.causeHint] : [], ), ); - const causeHint = - detail.causeHint ?? - (exchangeHints.length === 1 ? exchangeHints[0] : undefined); - if (!causeHint && exchangeHints.length > 1) { - return /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`The wallet's funds have multiple exchange, merchant, or fee restrictions that prevent this payment.`; - } - switch (causeHint) { + return exchangeHints.size > 1 + ? "multiple" + : exchangeHints.values().next().value; +} + +export function insufficientBalanceMessage( + detail: PaymentInsufficientBalanceDetails | undefined, + cause = insufficientBalanceCause(detail), + code?: TalerErrorCode, +): string { + if (!detail) + return i18n.str`The wallet does not have enough compatible funds.`; + switch (cause) { + case CoinSelectionFailureReasonType.SupersededExchangeMasterPub: + return /* Translators: Legacy funds belong to a previous cryptographic identity of an exchange, not merely an old wallet software version. */ i18n.str`Some funds were issued under legacy exchange keys and cannot be used for this operation.`; + case CoinSelectionFailureReasonType.BalanceFragmented: + return /* Translators: A peer payment must be funded by a single Taler exchange. */ i18n.str`Your funds are spread across exchanges. No single exchange holds enough for this payment.`; + case "multiple": + return /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`The wallet's funds have multiple exchange, merchant, or fee restrictions that prevent this payment.`; case InsufficientBalanceHint.MerchantAcceptInsufficient: return i18n.str`The merchant does not accept the funds available in this wallet.`; case InsufficientBalanceHint.MerchantDepositInsufficient: @@ -173,10 +249,31 @@ export function insufficientBalanceMessage( case InsufficientBalanceHint.ExchangeMissingGlobalFees: return /* Translators: An exchange is a GNU Taler service issuing and redeeming digital cash, not an action that converts one currency into another. */ i18n.str`The exchange is missing fee information required for this payment.`; case InsufficientBalanceHint.WalletBalanceAvailableInsufficient: - case undefined: - return detail.balanceAvailable - ? i18n.str`The wallet has ${detail.balanceAvailable} available, which is not enough for ${detail.amountRequested}.` - : i18n.str`The wallet does not have enough funds for this payment.`; + case undefined: { + const available = detail.balance?.available ?? detail.balanceAvailable; + if ( + typeof available !== "string" || + typeof detail.amountRequested !== "string" + ) + return i18n.str`The wallet does not have enough funds for this payment.`; + const balance = Amounts.parse(available); + const requested = Amounts.parse(detail.amountRequested); + if ( + balance && + requested && + balance.currency === requested.currency && + Amounts.cmp(balance, requested) < 0 + ) { + if ( + code === TalerErrorCode.WALLET_PEER_PULL_PAYMENT_INSUFFICIENT_BALANCE + ) + return /* Translators: A peer invoice can only be paid with funds from the exchange that hosts it. */ i18n.str`You have ${available} available at this invoice’s exchange. The requested amount is ${detail.amountRequested}.`; + return i18n.str`The wallet has ${available} available, which is not enough for ${detail.amountRequested}.`; + } + return i18n.str`The wallet does not have enough compatible funds.`; + } + default: + return i18n.str`The wallet does not have enough compatible funds.`; } } diff --git a/packages/wallet-webui/test/error.test.ts b/packages/wallet-webui/test/error.test.ts @@ -1,6 +1,13 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { errorFromException } from "../src/ui/error.js"; +import { + CoinSelectionFailureReasonType, + InsufficientBalanceHint, + ScopeType, + TalerErrorCode, + type CoinSelectionFailureReason, +} from "@gnu-taler/taler-util"; +import { errorFromException, walletCoreError } from "../src/ui/error.js"; test("generic exceptions do not replace a translated user-facing fallback", () => { const error = errorFromException( @@ -9,3 +16,220 @@ test("generic exceptions do not replace a translated user-facing fallback", () = ); assert.equal(error.message, "Operation failed"); }); + +test("deposit and peer payment errors show the available and requested amounts", () => { + for (const code of [ + TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE, + TalerErrorCode.WALLET_PEER_PULL_PAYMENT_INSUFFICIENT_BALANCE, + TalerErrorCode.WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE, + TalerErrorCode.WALLET_PAY_MERCHANT_INSUFFICIENT_BALANCE, + ]) { + const detail = { + code, + insufficientBalanceDetails: { + amountRequested: "KUDOS:50", + balanceAvailable: "KUDOS:20", + causeHint: InsufficientBalanceHint.WalletBalanceAvailableInsufficient, + }, + }; + const error = walletCoreError(detail, "Operation failed"); + assert.equal( + error.message, + code === TalerErrorCode.WALLET_PEER_PULL_PAYMENT_INSUFFICIENT_BALANCE + ? "You have KUDOS:20 available at this invoice’s exchange. The requested amount is KUDOS:50." + : "The wallet has KUDOS:20 available, which is not enough for KUDOS:50.", + ); + assert.equal( + error.guidance, + "Withdraw funds or choose another payment option, then try again.", + ); + assert.strictEqual(error.detail, detail); + assert.equal( + walletCoreError({ code }, "Operation failed").message, + "The wallet does not have enough compatible funds.", + ); + } +}); + +test("a peer invoice reports the balance at its exchange when funds are held elsewhere", () => { + const invoiceExchange = "https://invoice-exchange.example/"; + const outOfScope: CoinSelectionFailureReason = { + type: CoinSelectionFailureReasonType.ScopeRestricted, + scopeInfo: { + type: ScopeType.Exchange, + currency: "KUDOS", + url: invoiceExchange, + }, + }; + const detail = { + code: TalerErrorCode.WALLET_PEER_PULL_PAYMENT_INSUFFICIENT_BALANCE, + insufficientBalanceDetails: { + amountRequested: "KUDOS:10", + causeHint: InsufficientBalanceHint.WalletBalanceAvailableInsufficient, + balance: { available: "KUDOS:0" }, + exchanges: { + [invoiceExchange]: { balance: { available: "KUDOS:0" }, reasons: [] }, + "https://other.example/": { + balance: { available: "KUDOS:50" }, + reasons: [outOfScope], + }, + }, + }, + }; + assert.equal( + walletCoreError(detail, "Operation failed").message, + "You have KUDOS:0 available at this invoice’s exchange. The requested amount is KUDOS:10.", + ); +}); + +test("only exchanges eligible for the deposit determine wire method support", () => { + const selected = "https://selected.example/"; + const other = "https://other.example/"; + const outOfScope: CoinSelectionFailureReason = { + type: CoinSelectionFailureReasonType.ScopeRestricted, + scopeInfo: { type: ScopeType.Exchange, currency: "KUDOS", url: selected }, + }; + const unsupported: CoinSelectionFailureReason = { + type: CoinSelectionFailureReasonType.WireMethodUnsupported, + wireMethod: "iban", + }; + const explain = ( + exchanges: Record<string, { reasons: CoinSelectionFailureReason[] }>, + ) => + walletCoreError( + { + code: TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE, + insufficientBalanceDetails: { + amountRequested: "KUDOS:50", + balanceAvailable: "KUDOS:20", + causeHint: InsufficientBalanceHint.WalletBalanceAvailableInsufficient, + exchanges, + }, + }, + "Operation failed", + ); + for (const excluded of [ + outOfScope, + { type: CoinSelectionFailureReasonType.ReceiverNotAccepted }, + { + type: CoinSelectionFailureReasonType.ReceiverExchangeMasterPubMismatch, + walletMasterPub: "previous-key", + receiverMasterPubs: ["current-key"], + }, + ] satisfies CoinSelectionFailureReason[]) { + const error = explain({ + [selected]: { reasons: [unsupported] }, + [other]: { reasons: [excluded] }, + }); + assert.equal( + error.message, + "No exchange available for this deposit supports this type of bank account.", + ); + assert.equal(error.guidance, undefined); + } + const availableShortfall = + "The wallet has KUDOS:20 available, which is not enough for KUDOS:50."; + assert.equal( + explain({ + [selected]: { reasons: [] }, + [other]: { reasons: [outOfScope, unsupported] }, + }).message, + availableShortfall, + ); + assert.equal( + explain({ [other]: { reasons: [outOfScope, unsupported] } }).message, + availableShortfall, + ); +}); + +test("deposit restrictions identify the bank account and omit withdrawal guidance", () => { + const causeHint = InsufficientBalanceHint.MerchantDepositInsufficient; + const unsupportedWire = { + reasons: [ + { + type: CoinSelectionFailureReasonType.WireMethodUnsupported, + wireMethod: "iban", + }, + ], + }; + const depositCode = TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE; + const unsupported = walletCoreError( + { + code: depositCode, + insufficientBalanceDetails: { + causeHint, + exchanges: { "https://exchange.example/": unsupportedWire }, + }, + }, + "Operation failed", + ); + assert.equal( + unsupported.message, + "No exchange available for this deposit supports this type of bank account.", + ); + assert.equal(unsupported.guidance, undefined); + for (const insufficientBalanceDetails of [ + { causeHint }, + { perExchange: { "https://exchange.example/": { causeHint } } }, + { + causeHint, + exchanges: { + "https://exchange.example/": unsupportedWire, + "https://other.example/": { reasons: [] }, + }, + }, + ]) { + const error = walletCoreError( + { + code: depositCode, + insufficientBalanceDetails, + }, + "Operation failed", + ); + assert.equal( + error.message, + "The exchanges holding your funds cannot transfer the requested amount to this bank account.", + ); + assert.equal(error.guidance, undefined); + } + const merchant = walletCoreError( + { + code: TalerErrorCode.WALLET_PAY_MERCHANT_INSUFFICIENT_BALANCE, + insufficientBalanceDetails: { causeHint }, + }, + "Operation failed", + ); + assert.equal( + merchant.message, + "The available funds cannot be deposited by this merchant.", + ); +}); + +test("peer payments explain why a sufficient total balance cannot fund the request", () => { + const base = { + amountRequested: "KUDOS:10", + balanceAvailable: "KUDOS:12", + perExchange: { + "https://exchange.example/": { + causeHint: InsufficientBalanceHint.WalletBalanceAvailableInsufficient, + }, + }, + }; + const explain = (reasons?: { type: CoinSelectionFailureReasonType }[]) => + walletCoreError( + { + code: TalerErrorCode.WALLET_PEER_PUSH_PAYMENT_INSUFFICIENT_BALANCE, + insufficientBalanceDetails: { ...base, reasons }, + }, + "Operation failed", + ).message; + assert.match( + explain([{ type: CoinSelectionFailureReasonType.BalanceFragmented }]), + /no single exchange/i, + ); + assert.match( + explain([{ type: CoinSelectionFailureReasonType.FeesNotCovered }]), + /fees/, + ); + assert.equal(explain(), "The wallet does not have enough compatible funds."); +}); diff --git a/packages/wallet-webui/test/transaction-observation-routes.test.tsx b/packages/wallet-webui/test/transaction-observation-routes.test.tsx @@ -10,8 +10,10 @@ import test from "node:test"; import { Window } from "happy-dom"; import { ConfirmPayResultType, + InsufficientBalanceHint, NotificationType, ObservationType, + Result, TransactionMajorState, TransactionMinorState, TransactionType, @@ -422,6 +424,58 @@ async function harness( }; } +test("sending a peer payment explains a shortfall during review and disables link creation", async () => { + const dom = installRouteDom("#/peer/send?currency=CHF"); + const { cleanup, render, act } = await import("@testing-library/preact"); + const { SWRConfig } = await import("swr"); + const { App } = await import("../src/routes/App.js"); + const services = createDemoServices(); + const call = services.connection.client.callForResult; + services.connection.client.callForResult = async (operation, request) => { + if (operation === WalletApiOperation.CheckPeerPushDebitV2) { + return Result.of({ + type: "insufficient-balance", + insufficientBalanceDetails: { + amountRequested: "CHF:50", + balanceAvailable: "CHF:20", + causeHint: InsufficientBalanceHint.WalletBalanceAvailableInsufficient, + }, + }) as never; + } + return call(operation, request); + }; + try { + const view = render( + <SWRConfig value={{ provider: () => new Map() }}> + <App {...services} /> + </SWRConfig>, + ); + const amount = await view.findByLabelText("Amount (CHF)"); + const description = view.getByLabelText("Payment description"); + await act(() => { + amount.value = "50"; + amount.dispatchEvent(new Event("input", { bubbles: true })); + description.value = "Lunch"; + description.dispatchEvent(new Event("input", { bubbles: true })); + }); + await act(() => view.getByRole("button", { name: "Review" }).click()); + assert.ok( + await view.findByText( + "The wallet has CHF:20 available, which is not enough for CHF:50.", + ), + ); + assert.ok( + view + .getByRole("button", { name: "Create link" }) + .hasAttribute("disabled"), + ); + } finally { + cleanup(); + services.connection.close(); + await dom.happyDOM.abort(); + } +}); + for (const [route, list] of [ ["#/", "recent activity"], ["#/transactions", "transaction history"],