commit ab13290253adfc66cd2884fab6141062a6863e80
parent d1a46891d4df0d213569542b180c2e28897159a5
Author: Florian Dold <dold@taler.net>
Date: Tue, 17 Nov 2026 23:20:42 +0100
wallet-core: fetch renewal details for a single balance
Clients can request a report once or subscribe to changes. Calculate the
annual cost bound outside the database transaction.
Diffstat:
8 files changed, 582 insertions(+), 22 deletions(-)
diff --git a/packages/taler-wallet-core/src/autoRefresh.ts b/packages/taler-wallet-core/src/autoRefresh.ts
@@ -16,6 +16,7 @@ import {
AbsoluteTime,
Amounts,
AmountString,
+ CancellationToken,
DenomSelectionState,
WalletPowerSource,
AnnualRefreshCostBound,
@@ -371,12 +372,17 @@ export function computeAnnualRefreshBound(
/** Background projection yields to API requests and other wallet tasks. */
export async function computeAnnualRefreshBoundAsync(
- ...args: Parameters<typeof annualRefreshBoundSteps>
+ now: AbsoluteTime,
+ balance: AmountString,
+ inputs: WalletDenomination[],
+ candidates: WalletDenomination[],
+ token = CancellationToken.CONTINUE,
): Promise<AnnualRefreshCostBound> {
- const steps = annualRefreshBoundSteps(...args);
+ const steps = annualRefreshBoundSteps(now, balance, inputs, candidates);
let start = Date.now(),
count = 0;
while (true) {
+ token.throwIfCancelled();
const next = steps.next();
if (next.done) return next.value;
if (++count >= 32 || Date.now() - start >= 8) {
diff --git a/packages/taler-wallet-core/src/autoRefreshBalance.ts b/packages/taler-wallet-core/src/autoRefreshBalance.ts
@@ -17,6 +17,7 @@ import {
Amounts,
AmountString,
BalancesResponse,
+ WalletRefreshInfo,
CashExpirationRisk,
ScopeInfo,
stringifyScopeInfo,
@@ -42,7 +43,7 @@ import {
evaluateAutoRefresh,
unavailableAnnualBound,
DAY_MS,
- refreshLifetime,
+ expirationRisk,
} from "./autoRefresh.js";
export function refreshFailureReason(
@@ -88,16 +89,16 @@ export async function addRefreshBalanceInfo(
hash?: string,
) => Promise<ScopeInfo>,
now = AbsoluteTime.now(),
-): Promise<void> {
+): Promise<Map<string, WalletRefreshInfo>> {
const nowMs = AbsoluteTime.toStampMs(now);
const byScope = new Map(
response.balances.map((b) => {
- b.refreshInfo = {
+ const refreshInfo: WalletRefreshInfo = {
risks: [],
recoveries: [],
annualCostBound: unavailableAnnualBound("missing-holdings"),
};
- return [stringifyScopeInfo(b.scopeInfo), b];
+ return [stringifyScopeInfo(b.scopeInfo), { ...b, refreshInfo }];
}),
);
const denoms = new Map(
@@ -149,14 +150,11 @@ export async function addRefreshBalanceInfo(
d.denomPubHash,
);
if (!b || Amounts.isZero(amount)) return;
- const life = refreshLifetime(d);
- if (
- life &&
- (life.deposit <= nowMs || life.deposit - nowMs >= life.emergency)
- )
- return;
- if (++riskChecks % 32 === 0)
+ if (!expirationRisk(d, nowMs).atRisk) return;
+ if (++riskChecks % 32 === 0) {
await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ wex.cancellationToken.throwIfCancelled();
+ }
const key = denomRefKey(d);
let evaluation = evaluations.get(key);
if (!evaluation) {
@@ -169,7 +167,6 @@ export async function addRefreshBalanceInfo(
});
evaluations.set(key, evaluation);
}
- if (!evaluation.risk && !evaluation.invalidLifetime) return;
const exchange = exchanges.find((e) => e.baseUrl === d.exchangeBaseUrl);
const retry = await tx.getOperationRetry(
TaskIdentifiers.forExchangeAutoRefreshFromUrl(d.exchangeBaseUrl),
@@ -324,6 +321,7 @@ export async function addRefreshBalanceInfo(
group.amount,
group.denoms,
await candidates(group.denoms[0].exchangeMasterPub),
+ wex.cancellationToken,
);
if (bound.status === "available")
total = Amounts.add(total, bound.amount).amount;
@@ -341,4 +339,5 @@ export async function addRefreshBalanceInfo(
amount: Amounts.stringify(total),
};
}
+ return new Map([...byScope].map(([scope, b]) => [scope, b.refreshInfo]));
}
diff --git a/packages/taler-wallet-core/src/autoRefreshLifecycle.test.ts b/packages/taler-wallet-core/src/autoRefreshLifecycle.test.ts
@@ -182,7 +182,7 @@ test("pending and failed renewals retain risks; successful groups yield one dism
},
],
};
- await addRefreshBalanceInfo(
+ const reports = await addRefreshBalanceInfo(
wex,
tx,
response,
@@ -190,7 +190,7 @@ test("pending and failed renewals retain risks; successful groups yield one dism
[],
async () => response.balances[0].scopeInfo,
);
- return response.balances[0].refreshInfo!;
+ return [...reports.values()][0];
};
assert.equal((await getResponse()).risks[0].reason, "pending");
rg.statusPerCoin[0] = RefreshCoinStatus.Finished;
diff --git a/packages/taler-wallet-core/src/refreshBalance.test.ts b/packages/taler-wallet-core/src/refreshBalance.test.ts
@@ -20,6 +20,9 @@ import {
DenomKeyType,
encodeCrock,
NotificationType,
+ ObservationType,
+ ScopeType,
+ RefreshReason,
SetTimeoutTimerAPI,
TalerPreciseTimestamp,
WalletNotification,
@@ -39,9 +42,15 @@ import {
timestampProtocolToDb,
WalletDenomination,
ConfigRecordKey,
+ RefreshOperationStatus,
} from "./db/records.js";
-import { processRefreshBalance } from "./refreshBalance.js";
+import {
+ getBalanceRefreshInfo,
+ observeBalanceRefreshInfo,
+ processRefreshBalance,
+} from "./refreshBalance.js";
import { markExchangeUsed, startUpdateExchangeEntry } from "./exchanges.js";
+import { handleDismissWalletWarning } from "./requests.js";
import { getBalances } from "./balance.js";
import { TaskSchedulerImpl } from "./shepherd.js";
@@ -132,9 +141,14 @@ for (const makeRunner of runnerFactories) {
});
await processRefreshBalance(wex);
const before = await getBalances(wex);
+ const scopeInfo = before.balances[0].scopeInfo;
assert.equal(before.balances[0].available, "TEST:20");
assert.equal(before.balances[0].hasExpirationRisk, false);
assert.ok(!("refreshInfo" in before.balances[0]));
+ await observeBalanceRefreshInfo(wex, {
+ scopeInfo,
+ observationId: "cost",
+ });
await settle();
events.length = 0;
await startUpdateExchangeEntry(wex, stage);
@@ -207,6 +221,9 @@ for (const makeRunner of runnerFactories) {
assert.deepEqual(await getBalances(wex), before);
await settle();
assert.deepEqual(changes(), []);
+ assert.ok(
+ !events.some((n) => n.type === NotificationType.ObservationSnapshot),
+ );
await assert.rejects(
wex.runWalletDbTx(async (tx) => {
await markExchangeUsed(tx, stage);
@@ -225,6 +242,51 @@ for (const makeRunner of runnerFactories) {
after.balances.find((b) => b.scopeInfo.currency === "CHF")?.available,
"CHF:0",
);
+ const report = await getBalanceRefreshInfo(wex, {
+ scopeInfo: { type: ScopeType.Exchange, currency: "CHF", url: stage },
+ });
+ assert.deepEqual(report?.risks, []);
+ events.length = 0;
+ const warningId = "recovered-group";
+ await wex.runWalletDbTx((tx) =>
+ tx.upsertRefreshGroup({
+ refreshGroupId: warningId,
+ currency: "TEST",
+ reason: RefreshReason.Manual,
+ operationStatus: RefreshOperationStatus.Finished,
+ oldCoinPubs: [],
+ inputPerCoin: [],
+ expectedOutputPerCoin: [],
+ statusPerCoin: [],
+ refundRequests: {},
+ timestampCreated: timestamp,
+ timestampFinished: timestamp,
+ autoRefresh: {
+ recovery: {
+ warningId,
+ exchangeBaseUrl: denom.exchangeBaseUrl,
+ exchangeMasterPub: denom.exchangeMasterPub,
+ amount: "TEST:1",
+ oldDepositExpiration: { t_s: 100 },
+ newDepositExpiration: { t_s: 200 },
+ nextRelevantDate: { t_s: 190 },
+ },
+ },
+ }),
+ );
+ assert.deepEqual(
+ (await getBalanceRefreshInfo(wex, { scopeInfo }))?.recoveries.map(
+ (n) => n.warningId,
+ ),
+ [warningId],
+ );
+ await handleDismissWalletWarning(wex, { warningId });
+ assert.deepEqual(
+ (await getBalanceRefreshInfo(wex, { scopeInfo }))?.recoveries,
+ [],
+ );
+ await settle();
+ assert.deepEqual(changes(), []);
events.length = 0;
await wex.runWalletDbTx((tx) =>
tx.upsertDenomination({
@@ -241,11 +303,71 @@ for (const makeRunner of runnerFactories) {
);
await settle();
assert.equal(changes().length, 1);
+ const hasSnapshot = () =>
+ events.some(
+ (n) =>
+ n.type === NotificationType.ObservationSnapshot &&
+ n.observationType === ObservationType.BalanceRefreshInfo &&
+ n.snapshot?.risks.length,
+ );
+ const deadline = Date.now() + 3000;
+ while (!hasSnapshot() && Date.now() < deadline) await settle();
+ assert.ok(hasSnapshot());
events.length = 0;
+ await observeBalanceRefreshInfo(wex, {
+ scopeInfo,
+ observationId: "second",
+ });
+ await settle();
+ events.length = 0;
+ ws.observations.stop("cost");
await wex.runWalletDbTx((tx) => tx.upsertDenomination(denom));
await processRefreshBalance(wex);
await settle();
assert.equal(changes().length, 1);
+ assert.ok(
+ !events.some(
+ (n) => "observationId" in n && n.observationId === "cost",
+ ),
+ );
+ for (const offset of [day, -day]) {
+ const deadline = stamp(now + offset);
+ await wex.runWalletDbTx((tx) =>
+ tx.upsertDenomination({
+ ...denom,
+ stampExpireWithdraw: deadline,
+ stampExpireDeposit: deadline,
+ }),
+ );
+ await processRefreshBalance(wex);
+ const balance = (await getBalances(wex)).balances.find(
+ (b) => b.scopeInfo.currency === "TEST",
+ );
+ assert.equal(balance?.hasExpirationRisk, offset > 0);
+ const info = await getBalanceRefreshInfo(wex, { scopeInfo });
+ assert.ok(info);
+ assert.deepEqual(
+ info.risks.map((r) => r.reason),
+ offset > 0 ? ["invalid-lifetime"] : [],
+ );
+ }
+ const ended = new Promise<void>((resolve) => {
+ const remove = ws.addPublicNotificationListener((n) => {
+ if (
+ n.type === NotificationType.ObservationSnapshot &&
+ n.observationId === "second" &&
+ n.snapshot === null
+ ) {
+ remove();
+ resolve();
+ }
+ });
+ });
+ await wex.runWalletDbTx((tx) =>
+ tx.deleteCoinAvailability({ ...denom, maxAge: 0 }),
+ );
+ await ended;
+ assert.equal(await getBalanceRefreshInfo(wex, { scopeInfo }), null);
} finally {
await ws.shutdown();
}
diff --git a/packages/taler-wallet-core/src/refreshBalance.ts b/packages/taler-wallet-core/src/refreshBalance.ts
@@ -16,7 +16,12 @@ import {
AbsoluteTime,
BalancesResponse,
Amounts,
+ ScopeInfo,
+ BalanceRefreshInfoRequest,
+ ObserveBalanceRefreshInfoRequest,
+ CancellationToken,
stringifyScopeInfo,
+ WalletRefreshInfo,
} from "@gnu-taler/taler-util";
import {
ConfigRecordKey,
@@ -24,12 +29,24 @@ import {
RefreshOperationStatus,
ExpirationRiskCache,
expirationRiskScopes,
+ timestampAbsoluteFromDb,
} from "./db/records.js";
import { WalletDbTransaction } from "./db/transaction.js";
-import { WalletExecutionContext, denomRefKey } from "./wallet.js";
-import { BalanceScopeResolver } from "./balance.js";
-import { DAY_MS, expirationRisk } from "./autoRefresh.js";
-import { TaskRunResult } from "./common.js";
+import {
+ WalletExecutionContext,
+ denomRefKey,
+ getNormalWalletExecutionContext,
+} from "./wallet.js";
+import {
+ BalanceScopeResolver,
+ getBalancesInsideTransaction,
+} from "./balance.js";
+import {
+ addRefreshBalanceInfo,
+ RefreshBalanceSource,
+} from "./autoRefreshBalance.js";
+import { DAY_MS, expirationRisk, stampMs } from "./autoRefresh.js";
+import { TaskIdentifiers, TaskRunResult } from "./common.js";
/** Keep published risk flags stable while a new snapshot is being calculated. */
export async function readExpirationRiskFlags(
@@ -45,6 +62,191 @@ export async function readExpirationRiskFlags(
}
}
+async function reportGeneration(
+ tx: WalletDbTransaction,
+ masters: string[],
+): Promise<string> {
+ const versions = (
+ await tx.getConfig(ConfigRecordKey.RefreshReportGenerations)
+ )?.value;
+ const general =
+ versions?.general ??
+ (await tx.getConfig(ConfigRecordKey.RefreshBalanceGeneration))?.value ??
+ "";
+ return JSON.stringify([
+ general,
+ ...masters.map((m) => versions?.masters[m] ?? ""),
+ ]);
+}
+
+/** Capture database inputs once; all selection and projection runs afterward. */
+async function loadRefreshBalanceSnapshot(
+ wex: WalletExecutionContext,
+ tx: WalletDbTransaction,
+ requestedScope: string,
+) {
+ const now = AbsoluteTime.now(),
+ nowMs = AbsoluteTime.toStampMs(now);
+ const response = await getBalancesInsideTransaction(wex, tx, false);
+ const exchanges = await tx.getExchanges();
+ const allAvailable = await tx.getVisibleCoinAvailabilities();
+ const groups = await tx.listAllRefreshGroups();
+ const pending = groups.filter(
+ (g) => g.operationStatus !== RefreshOperationStatus.Finished,
+ );
+ const pendingCurrencies = new Map<string, string>();
+ for (const group of pending) {
+ group.oldCoinPubs.forEach((pub, i) => {
+ if (group.statusPerCoin[i] !== RefreshCoinStatus.Finished)
+ pendingCurrencies.set(pub, group.currency);
+ });
+ }
+ const allCoins = await tx.getCoinsByPubs([...pendingCurrencies.keys()]);
+ const resolver = await BalanceScopeResolver.load(tx);
+ const scopeKey = (
+ url: string,
+ currency: string,
+ master?: string,
+ hash?: string,
+ ) => JSON.stringify([url, currency, master, hash]);
+ const scopes = new Map<string, ScopeInfo>();
+ async function belongs(row: {
+ exchangeBaseUrl: string;
+ currency: string;
+ exchangeMasterPub: string;
+ denomPubHash: string;
+ }) {
+ const args = [
+ row.exchangeBaseUrl,
+ row.currency,
+ row.exchangeMasterPub,
+ row.denomPubHash,
+ ] as const;
+ const key = scopeKey(...args);
+ const scope = scopes.get(key) ?? (await resolver.resolveScope(...args));
+ scopes.set(key, scope);
+ return stringifyScopeInfo(scope) === requestedScope;
+ }
+ const availability: typeof allAvailable = [];
+ for (const row of allAvailable) {
+ if (await belongs(row)) availability.push(row);
+ }
+ const denoms = new Map(
+ (await tx.getDenominationsByRefs([...availability, ...allCoins])).map(
+ (d) => [denomRefKey(d), d],
+ ),
+ );
+ const coins: typeof allCoins = [];
+ for (const coin of allCoins) {
+ const denom = denoms.get(denomRefKey(coin));
+ if (
+ await belongs(
+ denom ?? { ...coin, currency: pendingCurrencies.get(coin.coinPub)! },
+ )
+ )
+ coins.push(coin);
+ }
+ const coinsByPub = new Map(coins.map((c) => [c.coinPub, c]));
+ const rows = [...availability, ...coins];
+ const heldRefs = new Set(rows.map(denomRefKey));
+ for (const [ref, denom] of denoms) {
+ if (heldRefs.has(ref)) await belongs(denom);
+ else denoms.delete(ref);
+ }
+ const masters = [...new Set(rows.map((row) => row.exchangeMasterPub))].sort();
+ const generation = await reportGeneration(tx, masters);
+ const byMaster = new Map(
+ await Promise.all(
+ [...masters].map(
+ async (master) =>
+ [
+ master,
+ exchanges.some((e) => e.detailsPointer?.masterPublicKey === master)
+ ? await tx.getDenominationsByMasterPub(master)
+ : [],
+ ] as const,
+ ),
+ ),
+ );
+ for (const ds of byMaster.values())
+ for (const d of ds) denoms.set(denomRefKey(d), d);
+ const retryIds = new Set([
+ ...pending.map((g) => `refresh:${g.refreshGroupId}`),
+ ...exchanges.map((e) =>
+ TaskIdentifiers.forExchangeAutoRefreshFromUrl(e.baseUrl),
+ ),
+ ]);
+ const retries = new Map(
+ await Promise.all(
+ [...retryIds].map(
+ async (id) => [id, await tx.getOperationRetry(id)] as const,
+ ),
+ ),
+ );
+ for (const g of groups) {
+ const n = g.autoRefresh?.recovery;
+ if (n)
+ scopes.set(
+ scopeKey(n.exchangeBaseUrl, g.currency, n.exchangeMasterPub),
+ await resolver.resolveScope(
+ n.exchangeBaseUrl,
+ g.currency,
+ n.exchangeMasterPub,
+ ),
+ );
+ }
+ const source: RefreshBalanceSource = {
+ getDenominationsByRefs: async (refs) =>
+ refs.flatMap((r) => {
+ const d = denoms.get(denomRefKey(r));
+ return d ? [d] : [];
+ }),
+ getDenominationsByMasterPub: async (master) => byMaster.get(master) ?? [],
+ getCoinsByPubs: async (pubs) =>
+ pubs.flatMap((p) => {
+ const c = coinsByPub.get(p);
+ return c ? [c] : [];
+ }),
+ getOperationRetry: async (id) => retries.get(id),
+ listAllRefreshGroups: async () => groups,
+ };
+ let nextCheck = nowMs + DAY_MS;
+ const boundary = (at: number) => {
+ if (at > nowMs) nextCheck = Math.min(nextCheck, at);
+ };
+ const participating = new Set(rows.map((r) => r.exchangeBaseUrl));
+ for (const e of exchanges)
+ if (participating.has(e.baseUrl) && e.lastUpdate != null)
+ boundary(
+ AbsoluteTime.toStampMs(timestampAbsoluteFromDb(e.lastUpdate)) + DAY_MS,
+ );
+ for (const d of denoms.values()) {
+ boundary(stampMs(d, "stampStart"));
+ boundary(stampMs(d, "stampExpireWithdraw"));
+ boundary(expirationRisk(d, nowMs).nextCheck);
+ }
+ return {
+ generation,
+ masters,
+ response,
+ exchanges,
+ availability,
+ source,
+ now,
+ nextCheck,
+ resolve: async (
+ url: string,
+ currency: string,
+ master?: string,
+ hash?: string,
+ ) => {
+ const scope = scopes.get(scopeKey(url, currency, master, hash));
+ if (!scope) throw Error("missing scope in refresh balance snapshot");
+ return scope;
+ },
+ };
+}
+
/** The expiry flag depends only on held coins and their deposit lifetimes. */
export async function processRefreshBalance(
wex: WalletExecutionContext,
@@ -120,3 +322,201 @@ export async function processRefreshBalance(
return TaskRunResult.runAgainAt(AbsoluteTime.fromMilliseconds(nextCheck));
});
}
+
+function experimentReport(
+ wex: WalletExecutionContext,
+ response: BalancesResponse,
+ key: string,
+): WalletRefreshInfo | undefined {
+ const scenario = wex.ws.devExperimentState.refreshScenario;
+ if (wex.ws.config?.testing?.devModeActive && scenario) {
+ const b = response.balances[0];
+ if (b && stringifyScopeInfo(b.scopeInfo) === key) {
+ const date = Math.floor(Date.now() / 1000);
+ const amount = b.available;
+ return {
+ risks:
+ scenario === "risk"
+ ? [
+ {
+ exchangeBaseUrl: "https://exchange.example/",
+ exchangeMasterPub: "demo",
+ amount,
+ earliestDepositExpiration: { t_s: date + 7 * 86400 },
+ reason: "no-replacement",
+ },
+ ]
+ : [],
+ recoveries:
+ scenario === "recovered"
+ ? [
+ {
+ warningId: "dd71-experiment",
+ exchangeBaseUrl: "https://exchange.example/",
+ exchangeMasterPub: "demo",
+ amount,
+ oldDepositExpiration: { t_s: date + 7 * 86400 },
+ newDepositExpiration: { t_s: date + 740 * 86400 },
+ nextRelevantDate: { t_s: date + 650 * 86400 },
+ },
+ ]
+ : [],
+ annualCostBound:
+ scenario === "cost-unavailable"
+ ? {
+ status: "unavailable",
+ horizonDays: 365,
+ projection: "stable-current-offerings",
+ reasons: ["unrefreshable-denomination"],
+ }
+ : {
+ status: "available",
+ horizonDays: 365,
+ projection: "stable-current-offerings",
+ amount: Amounts.stringify(
+ Amounts.zeroOfCurrency(b.scopeInfo.currency),
+ ),
+ },
+ };
+ }
+ }
+ return undefined;
+}
+
+interface ScopedReport {
+ info: WalletRefreshInfo | null;
+ nextCheck: number;
+ generation: string;
+ computedAt: number;
+ scenario?: string;
+ masters: string[];
+}
+interface ReportCalculation {
+ source: CancellationToken.Source;
+ result: Promise<ScopedReport>;
+ readers: number;
+}
+const pendingReports = new WeakMap<
+ WalletExecutionContext["ws"],
+ Map<string, ReportCalculation>
+>();
+async function currentReport(
+ wex: WalletExecutionContext,
+ scopeInfo: ScopeInfo,
+): Promise<ScopedReport> {
+ wex.cancellationToken.throwIfCancelled();
+ const key = stringifyScopeInfo(scopeInfo);
+ let pending = pendingReports.get(wex.ws);
+ if (!pending) pendingReports.set(wex.ws, (pending = new Map()));
+ let flight = pending.get(key);
+ if (!flight) {
+ const source = CancellationToken.create();
+ const reader = getNormalWalletExecutionContext(
+ wex.ws,
+ source.token,
+ undefined,
+ { observe() {} },
+ );
+ flight = { source, readers: 0, result: calculateFreshReport(reader, key) };
+ pending.set(key, flight);
+ }
+ flight.readers++;
+ try {
+ return await wex.cancellationToken.racePromise(flight.result);
+ } finally {
+ if (--flight.readers === 0) {
+ pending.delete(key);
+ flight.source.cancel();
+ }
+ }
+}
+
+async function calculateFreshReport(
+ wex: WalletExecutionContext,
+ key: string,
+): Promise<ScopedReport> {
+ while (!wex.ws.stopped) {
+ wex.cancellationToken.throwIfCancelled();
+ const snapshot = await wex.runWalletDbTx((tx) =>
+ loadRefreshBalanceSnapshot(wex, tx, key),
+ );
+ const scenario = wex.ws.devExperimentState.refreshScenario;
+ let info = experimentReport(wex, snapshot.response, key);
+ snapshot.response.balances = snapshot.response.balances.filter(
+ (b) => stringifyScopeInfo(b.scopeInfo) === key,
+ );
+ if (!info && snapshot.response.balances.length) {
+ const reports = await addRefreshBalanceInfo(
+ wex,
+ snapshot.source,
+ snapshot.response,
+ snapshot.exchanges,
+ snapshot.availability,
+ snapshot.resolve,
+ snapshot.now,
+ );
+ info = reports.get(key);
+ }
+ const generation = await wex.runWalletDbTx((tx) =>
+ reportGeneration(tx, snapshot.masters),
+ );
+ const computedAt = AbsoluteTime.toStampMs(snapshot.now);
+ const now = AbsoluteTime.toStampMs(AbsoluteTime.now());
+ if (
+ generation === snapshot.generation &&
+ computedAt <= now &&
+ now < snapshot.nextCheck &&
+ scenario === wex.ws.devExperimentState.refreshScenario
+ )
+ return {
+ info: info ?? null,
+ nextCheck: snapshot.nextCheck,
+ computedAt,
+ masters: snapshot.masters,
+ generation,
+ scenario,
+ };
+ }
+ throw Error("wallet stopped");
+}
+
+export async function getBalanceRefreshInfo(
+ wex: WalletExecutionContext,
+ req: BalanceRefreshInfoRequest,
+) {
+ return (await currentReport(wex, req.scopeInfo)).info;
+}
+
+export async function observeBalanceRefreshInfo(
+ wex: WalletExecutionContext,
+ req: ObserveBalanceRefreshInfoRequest,
+) {
+ const ws = wex.ws;
+ let last: ScopedReport | undefined;
+ await ws.observations.registerRefreshInfo(
+ req.observationId,
+ req.scopeInfo,
+ async (token) => {
+ const reader = getNormalWalletExecutionContext(ws, token, undefined, {
+ observe() {},
+ });
+ const generation =
+ last &&
+ (await reader.runWalletDbTx((tx) =>
+ reportGeneration(tx, last!.masters),
+ ));
+ const now = AbsoluteTime.toStampMs(AbsoluteTime.now());
+ if (
+ !last ||
+ last.generation !== generation ||
+ last.computedAt > now ||
+ last.nextCheck <= now ||
+ last.scenario !== reader.ws.devExperimentState.refreshScenario
+ )
+ last = await currentReport(reader, req.scopeInfo);
+ return last.info;
+ },
+ () => last?.nextCheck,
+ );
+ return {};
+}
diff --git a/packages/taler-wallet-core/src/requests.ts b/packages/taler-wallet-core/src/requests.ts
@@ -25,6 +25,10 @@ import { repairLegacyRecoupState } from "./recoup.js";
/**
* Imports.
*/
+import {
+ getBalanceRefreshInfo,
+ observeBalanceRefreshInfo,
+} from "./refreshBalance.js";
import { observeTransaction, stopObservation } from "./observe-transaction.js";
import {
AbortTransactionRequest,
@@ -241,6 +245,8 @@ import {
codecForPreparePayTemplateRequest,
codecForPreparePeerPullPaymentRequest,
codecForObserveTransactionRequest,
+ codecForBalanceRefreshInfoRequest,
+ codecForObserveBalanceRefreshInfoRequest,
codecForStopObservationRequest,
codecForPreparePeerPushCreditRequest,
codecForPrepareRefundRequest,
@@ -2752,6 +2758,14 @@ const handlers: { [T in WalletApiOperation]: HandlerWithValidator<T> } = {
codec: codecForGetWithdrawalDetailsForAmountRequest(),
handler: getWithdrawalDetailsForAmount,
},
+ [WalletApiOperation.GetBalanceRefreshInfo]: {
+ codec: codecForBalanceRefreshInfoRequest(),
+ handler: getBalanceRefreshInfo,
+ },
+ [WalletApiOperation.ObserveBalanceRefreshInfo]: {
+ codec: codecForObserveBalanceRefreshInfoRequest(),
+ handler: observeBalanceRefreshInfo,
+ },
[WalletApiOperation.GetBalances]: {
codec: codecForEmptyObject(),
handler: getBalances,
diff --git a/packages/taler-wallet-core/src/versions.ts b/packages/taler-wallet-core/src/versions.ts
@@ -52,7 +52,7 @@ export const WALLET_BANK_CONVERSION_API_PROTOCOL_VERSION = "2:0:0";
/**
* Libtool version of the wallet-core API.
*/
-export const WALLET_CORE_API_PROTOCOL_VERSION = "10:0:0";
+export const WALLET_CORE_API_PROTOCOL_VERSION = "11:0:0";
/**
* Libtool rules:
diff --git a/packages/taler-wallet-core/src/wallet-api-types.ts b/packages/taler-wallet-core/src/wallet-api-types.ts
@@ -171,6 +171,9 @@ import {
PreparePeerPullDebitRequest,
PreparePeerPullDebitResponse,
ObserveTransactionRequest,
+ ObserveBalanceRefreshInfoRequest,
+ BalanceRefreshInfoRequest,
+ WalletRefreshInfo,
StopObservationRequest,
PreparePeerPushCreditRequest,
PreparePeerPushCreditResponse,
@@ -254,6 +257,8 @@ export enum WalletApiOperation {
// Balances
GetBalances = "getBalances",
+ GetBalanceRefreshInfo = "getBalanceRefreshInfo",
+ ObserveBalanceRefreshInfo = "observeBalanceRefreshInfo",
GetBalanceDetail = "getBalanceDetail",
// Misc.
@@ -723,6 +728,18 @@ export type GetBalancesOp = {
response: BalancesResponse;
};
+export type GetBalanceRefreshInfoOp = {
+ op: WalletApiOperation.GetBalanceRefreshInfo;
+ request: BalanceRefreshInfoRequest;
+ response: WalletRefreshInfo | null;
+};
+
+export type ObserveBalanceRefreshInfoOp = {
+ op: WalletApiOperation.ObserveBalanceRefreshInfo;
+ request: ObserveBalanceRefreshInfoRequest;
+ response: EmptyObject;
+};
+
export type GetBalancesDetailOp = {
op: WalletApiOperation.GetBalanceDetail;
request: GetBalanceDetailRequest;
@@ -2184,6 +2201,8 @@ export type WalletOperations = {
[WalletApiOperation.SuspendTransaction]: SuspendTransactionOp;
[WalletApiOperation.ResumeTransaction]: ResumeTransactionOp;
[WalletApiOperation.GetBalances]: GetBalancesOp;
+ [WalletApiOperation.GetBalanceRefreshInfo]: GetBalanceRefreshInfoOp;
+ [WalletApiOperation.ObserveBalanceRefreshInfo]: ObserveBalanceRefreshInfoOp;
[WalletApiOperation.ConvertDepositAmount]: ConvertDepositAmountOp;
[WalletApiOperation.GetMaxDepositAmount]: GetMaxDepositAmountOp;
[WalletApiOperation.GetMaxPeerPushDebitAmount]: GetMaxPeerPushDebitAmountOp;