taler-typescript-core

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

commit 89f5316f7b6d2e91006f21f1e0b70747a5c110d1
parent 4d542c5204e5f48508f3c9b855ee09eadb3d3797
Author: Florian Dold <dold@taler.net>
Date:   Tue, 17 Nov 2026 23:20:03 +0100

wallet-core: notify when a commit changes the visible balance

Several writes can cancel each other out. Compare the balance overview
before the first relevant write and after the last.

Diffstat:
Mpackages/taler-util/src/notifications.ts | 5++---
Mpackages/taler-wallet-core/src/balance.ts | 42++++++++++++++++++++++++++++++++++++++++--
Mpackages/taler-wallet-core/src/db/shared.ts | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Mpackages/taler-wallet-core/src/donau.ts | 6+++---
Mpackages/taler-wallet-core/src/exchanges.ts | 29+++++++++++------------------
Mpackages/taler-wallet-core/src/pay-merchant.ts | 17+++++------------
Mpackages/taler-wallet-core/src/refresh.test.ts | 47-----------------------------------------------
Mpackages/taler-wallet-core/src/refreshBalance.ts | 6++----
Mpackages/taler-wallet-core/src/requests.test.ts | 5-----
Mpackages/taler-wallet-core/src/requests.ts | 40++++++++--------------------------------
Mpackages/taler-wallet-core/src/testing-recover-coins.ts | 3++-
Mpackages/taler-wallet-core/src/transaction-amounts.ts | 1+
Mpackages/taler-wallet-core/src/transactions.ts | 3++-
Mpackages/taler-wallet-core/src/wallet-notifications.test.ts | 214++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mpackages/taler-wallet-core/src/wallet.ts | 8+++++---
Mpackages/taler-wallet-core/src/withdraw.ts | 5-----
16 files changed, 382 insertions(+), 167 deletions(-)

diff --git a/packages/taler-util/src/notifications.ts b/packages/taler-util/src/notifications.ts @@ -231,8 +231,7 @@ export interface BankAccountChangeNotification { } /** - * Invalidates balance data, including flags and refreshInfo. The monetary - * amounts need not have changed, for example when a refresh cost becomes ready. + * Invalidates the balance overview, including scope membership and expiration risk. */ export interface BalanceChangeNotification { type: NotificationType.BalanceChange; @@ -251,7 +250,7 @@ export interface BalanceChangeNotification { * * Only used as a hint for debugging, should not be relied upon by clients. */ - hintTransactionId: string; + hintTransactionId?: string; } export interface TaskProgressNotification { diff --git a/packages/taler-wallet-core/src/balance.ts b/packages/taler-wallet-core/src/balance.ts @@ -60,6 +60,10 @@ * Imports. */ +import { + watchForCacheInvalidation, + WalletCacheInvalidation, +} from "./db/shared.js"; import { readRefreshBalanceInfo } from "./refreshBalance.js"; import { AmountJson, @@ -67,6 +71,8 @@ import { Amounts, assertUnreachable, BalanceFlag, + canonicalJson, + NotificationType, BalancesResponse, checkDbInvariant, DonauSummaryItem, @@ -338,7 +344,7 @@ class BalancesStore { private donauSummaryItems: DonauSummaryItem[] | undefined = undefined; constructor( - private wex: WalletExecutionContext, + private wex: Pick<WalletExecutionContext, "ws">, private scopeResolver: BalanceScopeResolver, ) {} @@ -603,7 +609,7 @@ class BalancesStore { * Get balance information. */ export async function getBalancesInsideTransaction( - wex: WalletExecutionContext, + wex: Pick<WalletExecutionContext, "ws">, tx: WalletDbTransaction, includeRefreshInfo = true, ): Promise<BalancesResponse> { @@ -1475,3 +1481,35 @@ export async function getBalanceDetail( depositPaytoUri: undefined, }); } + +/** + * Read the overview before the first relevant write and again after all writes. + * Queue one notification in the transaction if the visible balance changed. + */ +export async function withBalanceNotifications<T>( + wex: Pick<WalletExecutionContext, "ws">, + tx: WalletDbTransaction, + dirty: WalletCacheInvalidation, + run: (tx: WalletDbTransaction) => Promise<T>, +): Promise<T> { + const overview = async () => + canonicalJson(await getBalancesInsideTransaction(wex, tx)); + let before: Promise<string> | undefined; + const hints = new Set<string>(); + const result = await run( + watchForCacheInvalidation(tx, dirty, { + async beforeWrite() { + before ??= overview(); + await before; + }, + hint: (id) => hints.add(id), + }), + ); + if (before && (await before) !== (await overview())) { + tx.notify({ + type: NotificationType.BalanceChange, + hintTransactionId: hints.size === 1 ? [...hints][0] : undefined, + }); + } + return result; +} diff --git a/packages/taler-wallet-core/src/db/shared.ts b/packages/taler-wallet-core/src/db/shared.ts @@ -37,6 +37,7 @@ import { import { WalletDbTransaction } from "./transaction.js"; import { ConfigRecordKey, + ConfigRecord, PurchaseStatus, WalletExchangeEntry, WalletOperationRetry, @@ -49,7 +50,7 @@ export function coalesceWalletNotifications( notifications: readonly WalletNotification[], ): WalletNotification[] { const result: WalletNotification[] = []; - const balances = new Map<string, BalanceChangeNotification>(); + const balances = new Map<string | undefined, BalanceChangeNotification>(); for (const notification of notifications) { if (notification.type !== NotificationType.BalanceChange) { result.push(notification); @@ -213,32 +214,48 @@ export const CACHE_INVALIDATING_METHODS: ReadonlySet<string> = new Set([ "deleteGlobalCurrencyAuditor", ]); -/** - * Wrap a transaction so that calls to cache-invalidating methods are noticed. - * - * `flag.dirty` is set as a side effect; the caller drops the caches after the - * transaction commits, never before, so a rolled-back transaction does not - * invalidate anything. - */ -/** Changes that affect the persisted renewal report, including its balance. */ +/** Writes that can change GetBalances. Config records are checked by key. */ +const BALANCE_OVERVIEW_WRITES: ReadonlySet<string> = new Set([ + "upsertExchange", + "deleteExchange", + "upsertExchangeDetails", + "deleteExchangeDetails", + "upsertCoin", + "deleteCoin", + "upsertCoinAvailability", + "deleteCoinAvailability", + "upsertRefreshGroup", + "deleteRefreshGroup", + "upsertWithdrawalGroup", + "deleteWithdrawalGroup", + "upsertPurchase", + "deletePurchase", + "upsertDepositGroup", + "deleteDepositGroup", + "upsertPeerPushDebit", + "deletePeerPushDebit", + "upsertPeerPushCredit", + "deletePeerPushCredit", + "upsertPeerPullDebit", + "deletePeerPullDebit", + "upsertPeerPullCredit", + "deletePeerPullCredit", + "upsertDonationSummary", + "upsertGlobalCurrencyExchange", + "deleteGlobalCurrencyExchange", + "upsertGlobalCurrencyAuditor", + "deleteGlobalCurrencyAuditor", +] satisfies (keyof WalletDbTransaction)[]); + +/** The renewal report also depends on denomination and recovery data. */ export const REFRESH_BALANCE_INVALIDATING_METHODS: ReadonlySet<string> = new Set([ ...CACHE_INVALIDATING_METHODS, - ...[ - "Coin", - "CoinAvailability", - "RefreshGroup", - "RefreshSession", - "WithdrawalGroup", - "Purchase", - "DepositGroup", - "PeerPushDebit", - "PeerPushCredit", - "PeerPullDebit", - "PeerPullCredit", - "RecoupGroup", - "DonationSummary", - ].flatMap((name) => [`upsert${name}`, `delete${name}`]), + ...BALANCE_OVERVIEW_WRITES, + "upsertRefreshSession", + "deleteRefreshSession", + "upsertRecoupGroup", + "deleteRecoupGroup", ]); export interface WalletCacheInvalidation { @@ -266,11 +283,24 @@ function exchangeCacheInputs(exchange: WalletExchangeEntry | undefined) { return inputs; } +function exchangeBalanceInputs(exchange: WalletExchangeEntry | undefined) { + if (!exchange) return null; + return [ + exchange.entryStatus, + exchange.tosAcceptedTimestamp != null, + exchange.presetType ?? null, + !!exchange.peerPaymentsDisabled, + !!exchange.directDepositDisabled, + exchange.detailsPointer?.currency ?? null, + exchange.detailsPointer?.masterPublicKey ?? null, + ]; +} + async function trackExchangeUpdate( tx: WalletDbTransaction, exchange: WalletExchangeEntry, flag: WalletCacheInvalidation, -): Promise<void> { +): Promise<boolean> { const previous = await tx.getExchange(exchange.baseUrl); if ( canonicalJson(exchangeCacheInputs(previous)) !== @@ -279,6 +309,10 @@ async function trackExchangeUpdate( flag.dirty = true; flag.refreshBalanceDirty = true; } + return ( + JSON.stringify(exchangeBalanceInputs(previous)) !== + JSON.stringify(exchangeBalanceInputs(exchange)) + ); } /** Match the purchase contribution read by getBalancesInsideTransaction. */ @@ -302,13 +336,16 @@ async function trackPurchaseUpdate( proposalId: string, purchase: WalletPurchase | undefined, flag: WalletCacheInvalidation, -): Promise<void> { +): Promise<boolean> { const previous = await tx.getPurchase(proposalId); if ( canonicalJson(purchaseBalanceInputs(previous)) !== canonicalJson(purchaseBalanceInputs(purchase)) - ) + ) { flag.refreshBalanceDirty = true; + return true; + } + return false; } async function trackRetryUpdate( @@ -325,15 +362,34 @@ async function trackRetryUpdate( flag.refreshBalanceDirty = true; } +export interface BalanceWriteObserver { + beforeWrite(): Promise<void>; + hint(transactionId: string): void; +} + export function watchForCacheInvalidation<T extends WalletDbTransaction>( tx: T, flag: WalletCacheInvalidation, + balance?: BalanceWriteObserver, ): T { return new Proxy(tx, { get(target, prop, receiver) { const value = Reflect.get(target, prop, receiver); if (typeof value !== "function") return value; return (...args: unknown[]) => { + const write = (balanceMayChange: boolean) => + balanceMayChange && balance + ? balance.beforeWrite().then(() => value.apply(target, args)) + : value.apply(target, args); + if (prop === "notify" && balance) { + const n = args[0] as WalletNotification; + if (n.type === NotificationType.BalanceChange && n.hintTransactionId) + balance.hint(n.hintTransactionId); + } + if (prop === "upsertConfig" && balance) { + const record = args[0] as ConfigRecord; + return write(record.key === ConfigRecordKey.RefreshBalance || record.key === ConfigRecordKey.RefreshBalanceGeneration); + } if (prop === "upsertPurchase") { const purchase = args[0] as WalletPurchase; if (purchase.purchaseStatus >= PurchaseStatus.Done) @@ -347,7 +403,7 @@ export function watchForCacheInvalidation<T extends WalletDbTransaction>( target, args[0] as WalletExchangeEntry, flag, - ).then(() => value.apply(target, args)); + ).then(write); } if (prop === "upsertPurchase" || prop === "deletePurchase") { const purchase = @@ -357,7 +413,7 @@ export function watchForCacheInvalidation<T extends WalletDbTransaction>( purchase?.proposalId ?? (args[0] as string), purchase, flag, - ).then(() => value.apply(target, args)); + ).then(write); } if (typeof prop === "string" && CACHE_INVALIDATING_METHODS.has(prop)) flag.dirty = true; @@ -385,7 +441,9 @@ export function watchForCacheInvalidation<T extends WalletDbTransaction>( ).then(() => value.apply(target, args)); } } - return value.apply(target, args); + return write( + typeof prop === "string" && BALANCE_OVERVIEW_WRITES.has(prop), + ); }; }, }); diff --git a/packages/taler-wallet-core/src/donau.ts b/packages/taler-wallet-core/src/donau.ts @@ -171,7 +171,7 @@ async function submitDonationReceipts( await tx.upsertDonationSummary(donauSummary); tx.notify({ type: NotificationType.BalanceChange, - hintTransactionId: "donau", + isInternal: true, }); }); } @@ -245,7 +245,7 @@ async function persistDonauStatementTotal( await tx.upsertDonationSummary(summary); tx.notify({ type: NotificationType.BalanceChange, - hintTransactionId: "donau", + isInternal: true, }); }); } @@ -745,7 +745,7 @@ export async function acceptDonauBlindSigs( await tx.upsertDonationSummary(donauSummary); tx.notify({ type: NotificationType.BalanceChange, - hintTransactionId: "donau", + isInternal: true, }); } }); diff --git a/packages/taler-wallet-core/src/exchanges.ts b/packages/taler-wallet-core/src/exchanges.ts @@ -2904,6 +2904,8 @@ export async function updateExchangeFromUrlHandler( if (reusableDetails?.rowId !== undefined) { newDetails.rowId = reusableDetails.rowId; } + const exchangeDetailsChanged = + canonicalJson(existingDetails ?? null) !== canonicalJson(newDetails); r.lastUpdate = timestampPreciseToDb(TalerPreciseTimestamp.now()); r.nextUpdateStamp = timestampPreciseToDb( AbsoluteTime.toPreciseTimestamp( @@ -3209,7 +3211,7 @@ export async function updateExchangeFromUrlHandler( currencySpecChanged || denominationsChanged || oldMetadata !== entryMetadata() || - canonicalJson(existingDetails ?? null) !== canonicalJson(newDetails), + exchangeDetailsChanged, ); return TaskRunResult.progress(); @@ -3480,20 +3482,12 @@ async function handleDenomLoss( ? undefined : timestampAbsoluteFromDb(denom.stampExpireDeposit); if (!denom) { - // Remove availability - coinAv.freshCoinCount = 0; - coinAv.visibleCoinCount = 0; - await tx.upsertCoinAvailability(coinAv); denomsVanished.push(coinAv.denomPubHash); const total = Amount.from(coinAv.value).mult(n); amountVanished = amountVanished.add(total); } else if (denom.isRevoked) { // Checked before isOffered, because the exchange drops a revoked // denomination from /keys and it is therefore unoffered as well. - // Remove availability - coinAv.freshCoinCount = 0; - coinAv.visibleCoinCount = 0; - await tx.upsertCoinAvailability(coinAv); denomsRevoked.push(coinAv.denomPubHash); const total = Amount.from(coinAv.value).mult(n); amountRevoked = amountRevoked.add(total); @@ -3503,18 +3497,10 @@ async function handleDenomLoss( ) { // Checked before isOffered, because the exchange drops an expired // denomination from /keys in the same update that shows the expiry. - // Remove availability - coinAv.freshCoinCount = 0; - coinAv.visibleCoinCount = 0; - await tx.upsertCoinAvailability(coinAv); denomsExpired.push(coinAv.denomPubHash); const total = Amount.from(coinAv.value).mult(n); amountExpired = amountExpired.add(total); } else if (!denom.isOffered) { - // Remove availability - coinAv.freshCoinCount = 0; - coinAv.visibleCoinCount = 0; - await tx.upsertCoinAvailability(coinAv); denomsUnoffered.push(coinAv.denomPubHash); const total = Amount.from(coinAv.value).mult(n); amountUnoffered = amountUnoffered.add(total); @@ -3523,6 +3509,9 @@ async function handleDenomLoss( continue; } + coinAv.freshCoinCount = 0; + coinAv.visibleCoinCount = 0; + await tx.upsertCoinAvailability(coinAv); logger.warn(`denomination ${coinAv.denomPubHash} is a loss`); const coins = coinsByDenomHash.get(coinAv.denomPubHash) ?? []; @@ -3569,6 +3558,7 @@ async function handleDenomLoss( tx.notify({ type: NotificationType.BalanceChange, hintTransactionId: ctx.transactionId, + isInternal: true, }); } @@ -3603,6 +3593,7 @@ async function handleDenomLoss( tx.notify({ type: NotificationType.BalanceChange, hintTransactionId: ctx.transactionId, + isInternal: true, }); } @@ -3637,6 +3628,7 @@ async function handleDenomLoss( tx.notify({ type: NotificationType.BalanceChange, hintTransactionId: ctx.transactionId, + isInternal: true, }); } @@ -3673,6 +3665,7 @@ async function handleDenomLoss( tx.notify({ type: NotificationType.BalanceChange, hintTransactionId: transactionId, + isInternal: true, }); } } @@ -4942,7 +4935,7 @@ export async function purgeExchangeLegacyKeysInTx( tx.notify({ type: NotificationType.BalanceChange, - hintTransactionId: "purge-exchange-legacy-keys", + isInternal: true, }); return true; } diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts @@ -2733,6 +2733,11 @@ async function reselectCoinsTx( tokenPubs: p.payInfo.payTokenSelection.tokenPubs, }); } + tx.notify({ + type: NotificationType.BalanceChange, + hintTransactionId: ctx.transactionId, + isInternal: true, + }); return "success"; } @@ -2839,14 +2844,6 @@ async function handleInsufficientFunds( return TaskRunResult.finished(); } - wex.ws.notify({ - type: NotificationType.BalanceChange, - hintTransactionId: constructTransactionIdentifier({ - tag: TransactionType.Payment, - proposalId, - }), - }); - return TaskRunResult.progress(); } @@ -2889,10 +2886,6 @@ async function repairPayAfterExchangeFailure( if (repair === "insufficient") { return recoverPayAfterStableFailure(ctx, reason); } - wex.ws.notify({ - type: NotificationType.BalanceChange, - hintTransactionId: ctx.transactionId, - }); return TaskRunResult.progress(); } diff --git a/packages/taler-wallet-core/src/refresh.test.ts b/packages/taler-wallet-core/src/refresh.test.ts @@ -23,9 +23,6 @@ import { TalerError, TalerErrorCode, TransactionAction, - NotificationType, - RefreshReason, - WalletNotification, } from "@gnu-taler/taler-util"; import assert from "node:assert"; import { test } from "node:test"; @@ -117,50 +114,6 @@ test("refresh costs exclude outputs with a different age mask", () => { }); for (const makeRunner of runnerFactories) { - test(`${makeRunner.name}: refresh completion emits one balance invalidation`, async () => { - const runner = await makeRunner(); - const notifications: WalletNotification[] = []; - runner.setNotificationSink((n) => notifications.push(n)); - try { - const group: WalletRefreshGroup = { - refreshGroupId: "notification-test", - currency: "TESTKUDOS", - reason: RefreshReason.Manual, - operationStatus: RefreshOperationStatus.Pending, - oldCoinPubs: [], - inputPerCoin: [], - expectedOutputPerCoin: [], - statusPerCoin: [], - refundRequests: {}, - timestampCreated: 1 as WalletRefreshGroup["timestampCreated"], - timestampFinished: undefined, - }; - await runner.runReadWriteTx((tx) => tx.upsertRefreshGroup(group)); - const ctx = new RefreshTransactionContext( - {} as WalletExecutionContext, - group.refreshGroupId, - ); - await runner.runReadWriteTx(async (tx) => { - const [record, handle] = await ctx.getRecordHandle(tx); - record!.operationStatus = RefreshOperationStatus.Finished; - await handle.update(record, "refresh-done"); - }); - const balances = notifications.filter( - (n) => n.type === NotificationType.BalanceChange, - ); - assert.strictEqual(balances.length, 1); - assert.strictEqual(balances[0].isInternal, false); - assert.strictEqual( - notifications.filter( - (n) => n.type === NotificationType.TransactionStateTransition, - ).length, - 1, - ); - } finally { - await runner.close(); - } - }); - test(`${makeRunner.name}: refresh finds a matching age mask within a denomination family`, async () => { const runner = await makeRunner(); try { diff --git a/packages/taler-wallet-core/src/refreshBalance.ts b/packages/taler-wallet-core/src/refreshBalance.ts @@ -45,8 +45,6 @@ import { } from "./autoRefresh.js"; import { TaskIdentifiers, TaskRunResult } from "./common.js"; -export const REFRESH_BALANCE_NOTIFICATION = "refresh-balance"; - /** Project the cache exactly as a balance reader would see it. */ function visibleRefreshInfo( saved: WalletRefreshBalance | undefined, @@ -262,7 +260,6 @@ export async function publishRefreshBalance( (await tx.getConfig(ConfigRecordKey.RefreshBalanceGeneration))?.value ?? ""; if (generation !== value.generation) return false; const previous = (await tx.getConfig(ConfigRecordKey.RefreshBalance))?.value; - await tx.upsertConfig({ key: ConfigRecordKey.RefreshBalance, value }); const now = AbsoluteTime.toStampMs(AbsoluteTime.now()); // Generation and scheduling changes alone are not balance changes. Still // notify when publication replaces a reader's "checking" status, even if @@ -281,9 +278,10 @@ export async function publishRefreshBalance( ) { tx.notify({ type: NotificationType.BalanceChange, - hintTransactionId: REFRESH_BALANCE_NOTIFICATION, + isInternal: true, }); } + await tx.upsertConfig({ key: ConfigRecordKey.RefreshBalance, value }); return true; } diff --git a/packages/taler-wallet-core/src/requests.test.ts b/packages/taler-wallet-core/src/requests.test.ts @@ -453,7 +453,6 @@ test("removing one global exchange retains shared currency metadata", async () = }, ]; let currencyInfoDeletes = 0; - let balanceNotifications = 0; const tx = { async getGlobalCurrencyExchange( currency: string, @@ -486,9 +485,6 @@ test("removing one global exchange retains shared currency metadata", async () = }, ws: { exchangeCache: { clear() {} }, - notify(notification) { - if (notification.type === "balance-change") balanceNotifications++; - }, }, } as WalletExecutionContext; @@ -505,7 +501,6 @@ test("removing one global exchange retains shared currency metadata", async () = exchangeMasterPub: "master-two", }); assert.strictEqual(currencyInfoDeletes, 1); - assert.strictEqual(balanceNotifications, 2); }); function makeCoinSuspensionContext( diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts @@ -1805,14 +1805,14 @@ export async function handleAddGlobalCurrencyExchange( wex: WalletExecutionContext, req: AddGlobalCurrencyExchangeRequest, ): Promise<EmptyObject> { - const changed = await wex.runWalletDbTx(async (tx) => { + await wex.runWalletDbTx(async (tx) => { const existingRec = await tx.getGlobalCurrencyExchange( req.currency, req.exchangeBaseUrl, req.exchangeMasterPub, ); if (existingRec) { - return false; + return; } wex.ws.exchangeCache.clear(); // Re-scope currency info from exchange scope to global scope. The scope @@ -1835,13 +1835,7 @@ export async function handleAddGlobalCurrencyExchange( exchangeBaseUrl: req.exchangeBaseUrl, exchangeMasterPub: req.exchangeMasterPub, }); - return true; }); - if (changed) - wex.ws.notify({ - type: NotificationType.BalanceChange, - hintTransactionId: "global-currency-config", - }); return {}; } @@ -1849,14 +1843,14 @@ async function handleRemoveGlobalCurrencyAuditor( wex: WalletExecutionContext, req: RemoveGlobalCurrencyAuditorRequest, ): Promise<EmptyObject> { - const changed = await wex.runWalletDbTx(async (tx) => { + await wex.runWalletDbTx(async (tx) => { const existingRec = await tx.getGlobalCurrencyAuditor( req.currency, req.auditorBaseUrl, req.auditorPub, ); if (!existingRec) { - return false; + return; } checkDbInvariant( !!existingRec.id, @@ -1864,13 +1858,7 @@ async function handleRemoveGlobalCurrencyAuditor( ); await tx.deleteGlobalCurrencyAuditor(existingRec.id); wex.ws.exchangeCache.clear(); - return true; }); - if (changed) - wex.ws.notify({ - type: NotificationType.BalanceChange, - hintTransactionId: "global-currency-config", - }); return {}; } @@ -1878,14 +1866,14 @@ export async function handleRemoveGlobalCurrencyExchange( wex: WalletExecutionContext, req: RemoveGlobalCurrencyExchangeRequest, ): Promise<EmptyObject> { - const changed = await wex.runWalletDbTx(async (tx) => { + await wex.runWalletDbTx(async (tx) => { const existingRec = await tx.getGlobalCurrencyExchange( req.currency, req.exchangeBaseUrl, req.exchangeMasterPub, ); if (!existingRec) { - return false; + return; } wex.ws.exchangeCache.clear(); checkDbInvariant( @@ -1900,13 +1888,7 @@ export async function handleRemoveGlobalCurrencyExchange( currency: req.currency, }); } - return true; }); - if (changed) - wex.ws.notify({ - type: NotificationType.BalanceChange, - hintTransactionId: "global-currency-config", - }); return {}; } @@ -1914,14 +1896,14 @@ async function handleAddGlobalCurrencyAuditor( wex: WalletExecutionContext, req: AddGlobalCurrencyAuditorRequest, ): Promise<EmptyObject> { - const changed = await wex.runWalletDbTx(async (tx) => { + await wex.runWalletDbTx(async (tx) => { const existingRec = await tx.getGlobalCurrencyAuditor( req.currency, req.auditorBaseUrl, req.auditorPub, ); if (existingRec) { - return false; + return; } await tx.upsertGlobalCurrencyAuditor({ currency: req.currency, @@ -1929,13 +1911,7 @@ async function handleAddGlobalCurrencyAuditor( auditorPub: req.auditorPub, }); wex.ws.exchangeCache.clear(); - return true; }); - if (changed) - wex.ws.notify({ - type: NotificationType.BalanceChange, - hintTransactionId: "global-currency-config", - }); return {}; } diff --git a/packages/taler-wallet-core/src/testing-recover-coins.ts b/packages/taler-wallet-core/src/testing-recover-coins.ts @@ -155,7 +155,8 @@ async function changeAvailability( await tx.upsertCoinAvailability(car); tx.notify({ type: NotificationType.BalanceChange, - hintTransactionId: coin.sourceTransactionId ?? "", + hintTransactionId: coin.sourceTransactionId, + isInternal: true, }); } diff --git a/packages/taler-wallet-core/src/transaction-amounts.ts b/packages/taler-wallet-core/src/transaction-amounts.ts @@ -424,6 +424,7 @@ export async function updateTransactionAmounts( tx.notify({ type: NotificationType.BalanceChange, hintTransactionId: transactionId, + isInternal: true, }); } if ( diff --git a/packages/taler-wallet-core/src/transactions.ts b/packages/taler-wallet-core/src/transactions.ts @@ -1230,7 +1230,8 @@ export function applyNotifyBalanceEffect( notify({ type: NotificationType.BalanceChange, hintTransactionId: transactionId, - isInternal: balanceEffect <= BalanceEffect.PreserveUserVisible, + // Wake wallet tasks even when this transition leaves the overview unchanged. + isInternal: true, }); } } diff --git a/packages/taler-wallet-core/src/wallet-notifications.test.ts b/packages/taler-wallet-core/src/wallet-notifications.test.ts @@ -24,6 +24,7 @@ import { encodeCrock, NotificationType, openPromise, + RefreshReason, SetTimeoutTimerAPI, TalerErrorCode, TransactionMajorState, @@ -42,17 +43,30 @@ import { ExchangeEntryDbRecordStatus, ExchangeEntryDbUpdateStatus, PurchaseStatus, + RefreshOperationStatus, timestampPreciseToDb, timestampProtocolToDb, WalletDenomination, WalletExchangeDetails, WalletExchangeEntry, WalletPurchase, + WalletRefreshGroup, + WalletWithdrawalGroup, + WithdrawalRecordType, + WithdrawalGroupStatus, } from "./db/records.js"; import { runnerFactories } from "./db/testing/runners.js"; -import { doExchangeAutoRefresh, waitReadyExchange } from "./exchanges.js"; +import { getBalances } from "./balance.js"; +import { + acceptExchangeTermsOfService, + doExchangeAutoRefresh, + markExchangeUsed, + waitReadyExchange, +} from "./exchanges.js"; import { preparePayForUriV2, processPurchase } from "./pay-merchant.js"; +import { RefreshTransactionContext } from "./refresh.js"; import { processRefreshBalance } from "./refreshBalance.js"; +import { WithdrawTransactionContext } from "./withdraw.js"; import { clearTaskRetry, storePendingTaskError, @@ -314,6 +328,204 @@ for (const makeRunner of runnerFactories) { } }); + test(`${makeRunner.name}: direct balance writes notify only after a visible commit`, async () => { + const f = await fixture(makeRunner); + try { + const availability = { + ...withdrawableDenom(), + maxAge: 0, + freshCoinCount: 2, + visibleCoinCount: 2, + hasFreshCoins: 1 as const, + }; + const events = () => + f.notifications.filter( + (n) => n.type === NotificationType.BalanceChange, + ); + await assert.rejects( + f.wex.runWalletDbTx(async (tx) => { + await tx.upsertCoinAvailability(availability); + throw Error("rollback"); + }), + /rollback/, + ); + await tick(); + assert.equal(events().length, 0); + await f.ws.runStandaloneWalletDbTx((tx) => + tx.upsertCoinAvailability(availability), + ); + await tick(); + assert.deepEqual( + events().map((n) => n.hintTransactionId), + [undefined], + ); + f.notifications.length = 0; + await f.wex.runWalletDbTx(async (tx) => { + await tx.deleteCoinAvailability(availability); + await tx.upsertCoinAvailability(availability); + }); + await tick(); + assert.equal(events().length, 0); + await f.wex.runWalletDbTx((tx) => + tx.deleteCoinAvailability(availability), + ); + await tick(); + assert.equal(events().length, 1); + } finally { + await f.close(); + } + }); + + test(`${makeRunner.name}: refresh completion notifies only when its output was visible`, async () => { + const f = await fixture(makeRunner); + try { + for (const hasOutput of [false, true]) { + const group: WalletRefreshGroup = { + refreshGroupId: hasOutput ? "with-output" : "empty", + currency: "TESTKUDOS", + reason: RefreshReason.Manual, + operationStatus: RefreshOperationStatus.Pending, + oldCoinPubs: [], + inputPerCoin: [], + expectedOutputPerCoin: [], + statusPerCoin: [], + refundRequests: {}, + timestampCreated: f.exchange.lastUpdate!, + timestampFinished: undefined, + infoPerExchange: hasOutput + ? { [exchangeUrl]: { outputEffective: "TESTKUDOS:1" } } + : undefined, + }; + await f.db.runReadWriteTx((tx) => tx.upsertRefreshGroup(group)); + assert.equal( + (await getBalances(f.wex)).balances[0].available, + hasOutput ? "TESTKUDOS:1" : "TESTKUDOS:0", + ); + const ctx = new RefreshTransactionContext(f.wex, group.refreshGroupId); + await f.wex.runWalletDbTx(async (tx) => { + const [record, handle] = await ctx.getRecordHandle(tx); + assert.ok(record); + record.operationStatus = RefreshOperationStatus.Finished; + await handle.update(record, "refresh-done"); + }); + await tick(); + assert.equal( + (await getBalances(f.wex)).balances[0].available, + "TESTKUDOS:0", + ); + assert.deepEqual( + f.notifications + .filter((n) => n.type === NotificationType.BalanceChange) + .map((n) => n.hintTransactionId), + hasOutput ? [ctx.transactionId] : [], + ); + assert.equal( + f.notifications.filter( + (n) => n.type === NotificationType.TransactionStateTransition, + ).length, + 1, + ); + f.notifications.length = 0; + } + } finally { + await f.close(); + } + }); + + test(`${makeRunner.name}: withdrawal transitions publish the final pending balance once per commit`, async () => { + const f = await fixture(makeRunner); + try { + const ctx = new WithdrawTransactionContext(f.wex, "withdrawal"); + const record: WalletWithdrawalGroup = { + withdrawalGroupId: ctx.withdrawalGroupId, + wgInfo: { withdrawalType: WithdrawalRecordType.BankManual }, + status: WithdrawalGroupStatus.DialogProposed, + exchangeBaseUrl: exchangeUrl, + secretSeed: master, + reservePub: master, + reservePriv: master, + instructedAmount: "TESTKUDOS:1", + timestampStart: f.exchange.lastUpdate!, + denomsSel: { + selectedDenoms: [], + hasDenomWithAgeRestriction: false, + totalCoinValue: "TESTKUDOS:1", + totalWithdrawCost: "TESTKUDOS:1", + }, + }; + await f.db.runReadWriteTx((tx) => tx.upsertWithdrawalGroup(record)); + const events = () => + f.notifications.filter( + (n) => n.type === NotificationType.BalanceChange, + ); + await f.wex.runWalletDbTx(async (tx) => { + const [, handle] = await ctx.getRecordHandle(tx); + await handle.update( + { ...record, status: WithdrawalGroupStatus.PendingReady }, + "start", + ); + await handle.update(record, "undo"); + }); + await tick(); + assert.deepEqual(events(), []); + await f.wex.runWalletDbTx(async (tx) => { + const [, handle] = await ctx.getRecordHandle(tx); + await handle.update( + { ...record, status: WithdrawalGroupStatus.PendingReady }, + "start", + ); + await handle.update( + { ...record, status: WithdrawalGroupStatus.SuspendedReady }, + "suspend", + ); + }); + await tick(); + assert.equal( + (await getBalances(f.wex)).balances[0].pendingIncoming, + "TESTKUDOS:1", + ); + assert.deepEqual( + events().map((n) => n.hintTransactionId), + [ctx.transactionId], + ); + } finally { + await f.close(); + } + }); + + test(`${makeRunner.name}: marking an exchange used after accepting its terms preserves the visible balance`, async () => { + const f = await fixture(makeRunner); + try { + await f.db.runReadWriteTx((tx) => + tx.upsertExchange({ + ...f.exchange, + entryStatus: ExchangeEntryDbRecordStatus.Ephemeral, + tosCurrentEtag: "terms", + }), + ); + assert.deepEqual((await getBalances(f.wex)).balances, []); + await acceptExchangeTermsOfService(f.wex, exchangeUrl); + await tick(); + const accepted = await getBalances(f.wex); + assert.equal(accepted.balances[0].available, "TESTKUDOS:0"); + assert.equal( + f.notifications.filter((n) => n.type === NotificationType.BalanceChange) + .length, + 1, + ); + f.notifications.length = 0; + await f.wex.runWalletDbTx((tx) => markExchangeUsed(tx, exchangeUrl)); + await tick(); + assert.deepEqual(await getBalances(f.wex), accepted); + assert.deepEqual( + f.notifications.map((n) => n.type), + [NotificationType.ExchangeStateTransition], + ); + } finally { + await f.close(); + } + }); + test( `${makeRunner.name}: auto-refresh wakes internal waiters without frontend reloads`, { timeout: 5000 }, diff --git a/packages/taler-wallet-core/src/wallet.ts b/packages/taler-wallet-core/src/wallet.ts @@ -23,6 +23,7 @@ /** * Imports. */ +import { withBalanceNotifications } from "./balance.js"; import { AbsoluteTime, LongpollObserver, @@ -100,7 +101,6 @@ import { import { WalletDbHandle } from "./db/handle.js"; import { persistRefreshBalanceInvalidation, - watchForCacheInvalidation, } from "./db/shared.js"; import { WalletCoinAvailabilityRef, @@ -991,7 +991,7 @@ async function runWalletDbTx<T>( const start = performanceNow(); try { const ret = await wex.ws.db.runReadWriteTx(async (tx) => { - const ret = await f(watchForCacheInvalidation(tx, dirty)); + const ret = await withBalanceNotifications(wex, tx, dirty, f); await persistRefreshBalanceInvalidation(tx, dirty); return ret; }); @@ -1524,7 +1524,7 @@ export class InternalWalletState { ): Promise<T> { const dirty = { dirty: false, refreshBalanceDirty: false }; const ret = await this.db.runReadWriteTx(async (tx) => { - const ret = await f(watchForCacheInvalidation(tx, dirty)); + const ret = await withBalanceNotifications({ ws: this }, tx, dirty, f); await persistRefreshBalanceInvalidation(tx, dirty); return ret; }); @@ -1898,6 +1898,8 @@ export class InternalWalletState { TaskIdentifiers.forExchangeAutoRefreshFromUrl(n.exchangeBaseUrl), ); } + if (n.type === NotificationType.BalanceChange && n.isInternal) + return this.notifyInternal(n); if (n.type === NotificationType.DatabaseMaintenanceProgress) { this.maintenanceNotifications.offer(n); return; diff --git a/packages/taler-wallet-core/src/withdraw.ts b/packages/taler-wallet-core/src/withdraw.ts @@ -5821,11 +5821,6 @@ export async function createManualWithdrawal( withdrawalGroup.withdrawalGroupId, ); - wex.ws.notify({ - type: NotificationType.BalanceChange, - hintTransactionId: ctx.transactionId, - }); - wex.taskScheduler.startShepherdTask(ctx.taskId); return {