commit 1634d090373b06953db5bdded07c57f31b11b46e
parent 7f18eca96616a06f2d2183458e4ce5b085455133
Author: Florian Dold <dold@taler.net>
Date: Wed, 25 Nov 2026 18:09:00 +0100
wallet-core: recover the deposit fee on full coin refunds
The wallet missed the deposit fee the exchange returns when merchant
refunds cover a coin's contribution. Keep confirmed refund IDs and
amounts on the purchase so partial refunds count toward the total and
clearing refund history can't cause a second credit.
Diffstat:
8 files changed, 527 insertions(+), 115 deletions(-)
diff --git a/packages/taler-wallet-core/src/coin-history.ts b/packages/taler-wallet-core/src/coin-history.ts
@@ -30,6 +30,7 @@ import {
throwUnexpectedResponse,
} from "@gnu-taler/taler-util";
import type { WalletDbTransaction } from "./db/transaction.js";
+import { calculateCoinRefund } from "./refund-accounting.js";
import { addConflictingSpend } from "./user-attention.js";
import {
constructTransactionIdentifier,
@@ -170,37 +171,24 @@ export function validateAndRecomputeCoinHistoryBalance(
"coin history refund has no matching deposit",
);
}
- // History reports the net refund. The exchange also returns the
- // deposit fee once gross cumulative refunds cover this deposit.
+ // Exchange history reports the net amount. Merchant permissions use gross.
const grossRefund = Amounts.add(item.amount, item.refund_fee);
- const totalRefund = Amounts.add(deposit.refunded, grossRefund.amount);
- if (
- grossRefund.saturated ||
- totalRefund.saturated ||
- Amounts.cmp(totalRefund.amount, deposit.amount) > 0
- ) {
+ if (grossRefund.saturated) {
throw TalerError.fromDetail(
TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
{},
"coin history refunds exceed their deposit",
);
}
- amount = item.amount;
- if (
- Amounts.cmp(deposit.refunded, deposit.amount) < 0 &&
- Amounts.cmp(totalRefund.amount, deposit.amount) === 0
- ) {
- const withWaivedFee = Amounts.add(amount, deposit.fee);
- if (withWaivedFee.saturated) {
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
- {},
- "refunded deposit fee overflows the coin balance",
- );
- }
- amount = Amounts.stringify(withWaivedFee.amount);
- }
- deposit.refunded = Amounts.stringify(totalRefund.amount);
+ const refund = calculateCoinRefund({
+ contribution: deposit.amount,
+ previousGross: deposit.refunded,
+ grossRefund: grossRefund.amount,
+ refundFee: item.refund_fee,
+ depositFee: deposit.fee,
+ });
+ amount = Amounts.stringify(refund.credit);
+ deposit.refunded = Amounts.stringify(refund.totalGross);
addsValue = true;
break;
}
diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts
@@ -909,6 +909,8 @@ export interface WalletDonationPlanchet {
* "purchases" object stores.
*/
export interface WalletProposalDownloadInfo {
+ /** Refunds for older paid purchases that have no payInfo. */
+ accountedRefunds?: AccountedCoinRefunds;
contractTermsHash: string;
fulfillmentUrl?: string;
currency: string;
@@ -919,7 +921,11 @@ export interface WalletTokenSelection {
tokenPubs: string[];
}
+/** Gross refunds already allocated to recovery, by coin public key and refund ID. */
+export type AccountedCoinRefunds = Record<string, Record<number, AmountString>>;
+
export interface WalletPurchasePayInfo {
+ accountedRefunds?: AccountedCoinRefunds;
/** Frozen before submitting /pay; replay must keep the same wallet-data hash. */
submittedWalletData?: import("@gnu-taler/taler-util").PayWalletData;
/**
diff --git a/packages/taler-wallet-core/src/db/testing/conformance-cases.ts b/packages/taler-wallet-core/src/db/testing/conformance-cases.ts
@@ -171,7 +171,7 @@ const amt = (s: string): AmountString => s as AmountString;
const txnId = (s: string): TransactionIdStr => s as TransactionIdStr;
-function makeDenomination(
+export function makeDenomination(
exchangeBaseUrl: string,
denomPubHash: string,
opts: {
@@ -214,7 +214,7 @@ function makeDenomination(
return denom;
}
-function makeCoin(coinPub: string): WalletCoin {
+export function makeCoin(coinPub: string): WalletCoin {
const coin: WalletCoin = {
coinPub: ck(coinPub),
coinPriv: ck(`priv-${coinPub}`),
@@ -265,7 +265,7 @@ function makeAvail(
return rec;
}
-function makeExchange(baseUrl: string): WalletExchangeEntry {
+export function makeExchange(baseUrl: string): WalletExchangeEntry {
const ex: WalletExchangeEntry = {
baseUrl,
source: ExchangeEntrySource.Builtin,
@@ -283,7 +283,7 @@ function makeExchange(baseUrl: string): WalletExchangeEntry {
return ex;
}
-function makeExchangeDetails(
+export function makeExchangeDetails(
exchangeBaseUrl: string,
masterPublicKey: string,
): WalletExchangeDetails {
@@ -306,7 +306,7 @@ function makeExchangeDetails(
return det;
}
-function makeSignKey(
+export function makeSignKey(
exchangeDetailsRowId: number,
signkeyPub: string,
): WalletExchangeSignkeys {
diff --git a/packages/taler-wallet-core/src/deposits.test.ts b/packages/taler-wallet-core/src/deposits.test.ts
@@ -291,6 +291,18 @@ test("hard-KYC deposit cleanup remains finalizing until recovery completes", ()
test("deposit abort refreshes the amount the refund restored on the coin", () => {
const denom = { feeDeposit: "TESTKUDOS:0.1", feeRefund: "TESTKUDOS:0.02" };
+ for (const [gross, expected] of [
+ ["TESTKUDOS:10", "TESTKUDOS:10.1"],
+ ["TESTKUDOS:0.05", "TESTKUDOS:0"],
+ ["TESTKUDOS:0.1", "TESTKUDOS:0.2"],
+ ]) {
+ const credit = getDepositAbortRefreshAmount(
+ gross,
+ DepositElementStatus.RefundSuccess,
+ { feeRefund: "TESTKUDOS:0.1", feeDeposit: "TESTKUDOS:0.2" },
+ );
+ assert.equal(Amounts.stringify(credit), expected);
+ }
assert.strictEqual(
Amounts.stringify(
getDepositAbortRefreshAmount(
diff --git a/packages/taler-wallet-core/src/deposits.ts b/packages/taler-wallet-core/src/deposits.ts
@@ -153,6 +153,7 @@ import {
createRefreshGroup,
getTotalRefreshCosts,
} from "./refresh.js";
+import { calculateCoinRefund } from "./refund-accounting.js";
import {
BalanceEffect,
applyNotifyTransition,
@@ -1072,11 +1073,13 @@ export function getDepositAbortRefreshAmount(
if (status === DepositElementStatus.RefundNotFound) {
return contrib;
}
- const afterRefundFee = Amounts.sub(contrib, denom.feeRefund);
- if (afterRefundFee.saturated) {
- return Amounts.zeroOfAmount(contrib);
- }
- return Amounts.add(afterRefundFee.amount, denom.feeDeposit).amount;
+ return calculateCoinRefund({
+ contribution: contrib,
+ previousGross: Amounts.zeroOfAmount(contrib),
+ grossRefund: contrib,
+ refundFee: denom.feeRefund,
+ depositFee: denom.feeDeposit,
+ }).credit;
}
export function classifyDepositAbortOutcome(
diff --git a/packages/taler-wallet-core/src/pay-merchant.test.ts b/packages/taler-wallet-core/src/pay-merchant.test.ts
@@ -18,7 +18,10 @@ import {
Amounts,
AmountString,
buildSigPS,
+ Cache,
CancellationToken,
+ Duration,
+ MerchantCoinRefundStatus,
CoinStatus,
DenomKeyType,
LongpollQueue,
@@ -49,6 +52,16 @@ import {
} from "@gnu-taler/taler-util";
import assert from "node:assert";
import { test } from "node:test";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ makeCoin,
+ makeDenomination,
+ makeExchange,
+ makeExchangeDetails,
+ makeSignKey,
+} from "./db/testing/conformance-cases.js";
import {
PurchaseStatus,
ConfigRecordKey,
@@ -1115,6 +1128,240 @@ for (const makeRunner of runnerFactories) {
}
for (const makeRunner of runnerFactories) {
+ test(`${makeRunner.name}: cumulative merchant refunds survive history deletion and restart`, async () => {
+ const directory = await mkdtemp(join(tmpdir(), "wallet-refund-"));
+ const filename = join(directory, "wallet.db");
+ let runner = await makeRunner(filename);
+ const purchase = makeDownloadedPurchase(
+ "cumulative-refunds",
+ PurchaseStatus.PendingAcceptRefund,
+ );
+ const [full, split, unknown] = ["full", "split", "unknown"].map(makeCoin);
+ const baseUrl = full.exchangeBaseUrl;
+ const signPub = encodeCrock(new Uint8Array(32).fill(9));
+ const wex = {
+ ws: {
+ notify() {},
+ denomInfoCache: new Cache(10, Duration.fromSpec({ minutes: 1 })),
+ refreshCostCache: new Cache(10, Duration.fromSpec({ minutes: 1 })),
+ },
+ taskScheduler: { startShepherdTask() {} },
+ cryptoApi: { isValidRefundConfirmation: async () => ({ valid: true }) },
+ runWalletDbTx: <T>(f: (tx: WalletDbTransaction) => Promise<T>) =>
+ runner.runReadWriteTx(f),
+ } as unknown as WalletExecutionContext;
+ const paymentId = new PayMerchantTransactionContext(
+ wex,
+ purchase.proposalId,
+ ).transactionId;
+ const success = (
+ coinPub: string,
+ id: number,
+ amount: AmountString,
+ ): MerchantCoinRefundStatus => ({
+ type: "success",
+ exchange_status: 200,
+ exchange_pub: signPub,
+ exchange_sig: "receipt",
+ coin_pub: coinPub,
+ rtransaction_id: id,
+ refund_amount: amount,
+ execution_time: { t_s: 150 },
+ });
+ const collect = async (refunds: MerchantCoinRefundStatus[]) => {
+ const current = await runner.runReadWriteTx(async (tx) => {
+ const p = (await tx.getPurchase(purchase.proposalId))!;
+ p.purchaseStatus = PurchaseStatus.PendingAcceptRefund;
+ await tx.upsertPurchase(p);
+ return p;
+ });
+ await storeRefunds(wex, current, refunds, RefundReason.NormalRefund);
+ };
+ const removeLedger = () =>
+ runner.runReadWriteTx(async (tx) => {
+ const p = (await tx.getPurchase(purchase.proposalId))!;
+ delete p.payInfo!.accountedRefunds;
+ await tx.upsertPurchase(p);
+ });
+ const recoveryAmounts = () =>
+ runner.runReadWriteTx(async (tx) => {
+ const groups =
+ await tx.getRefreshGroupsByOriginatingTransaction(paymentId);
+ return groups
+ .flatMap((g) =>
+ g.oldCoinPubs.map((pub, i) => [pub, g.inputPerCoin[i]]),
+ )
+ .sort();
+ });
+ try {
+ purchase.payInfo!.payCoinSelection = {
+ coinPubs: [full.coinPub],
+ coinContributions: ["TESTKUDOS:10"],
+ };
+ await runner.runReadWriteTx(async (tx) => {
+ await upsertTestContractTerms(tx, purchase);
+ await tx.upsertPurchase(purchase);
+ const details = makeExchangeDetails(baseUrl, full.exchangeMasterPub);
+ const rowId = await tx.upsertExchangeDetails(details);
+ await tx.upsertExchangeSignKey(makeSignKey(rowId, signPub));
+ await tx.upsertExchange({
+ ...makeExchange(baseUrl),
+ detailsPointer: {
+ masterPublicKey: full.exchangeMasterPub,
+ currency: "TESTKUDOS",
+ updateClock: purchase.timestamp,
+ },
+ });
+ for (const [hash, value] of [
+ [full.denomPubHash, "TESTKUDOS:10"],
+ ["output", "TESTKUDOS:1"],
+ ] as const) {
+ const denom = makeDenomination(baseUrl, hash, {
+ stampExpireWithdraw: 4000000000,
+ });
+ denom.stampExpireLegal = denom.stampExpireDeposit =
+ denom.stampExpireWithdraw;
+ denom.value = value;
+ denom.fees.feeDeposit = "TESTKUDOS:0.2";
+ denom.denominationFamilySerial = await tx.upsertDenominationFamily({
+ familyParams: {
+ exchangeBaseUrl: baseUrl,
+ exchangeMasterPub: full.exchangeMasterPub,
+ value,
+ ...denom.fees,
+ },
+ });
+ await tx.upsertDenomination(denom);
+ }
+ for (const coin of [full, split, unknown]) {
+ await tx.upsertCoin({ ...coin, status: CoinStatus.Dormant });
+ }
+ // Only a spend for this payment proves the contribution of a repaired selection.
+ for (const [coin, transactionId] of [
+ [split, paymentId],
+ [unknown, "txn:payment:other" as TransactionIdStr],
+ ] as const) {
+ await tx.upsertCoinHistory({
+ coinPub: coin.coinPub,
+ history: [{ type: "spend", transactionId, amount: "TESTKUDOS:10" }],
+ });
+ }
+ });
+ const first = success(full.coinPub, 1, "TESTKUDOS:10");
+ const part = success(split.coinPub, 1, "TESTKUDOS:4");
+ const netOnly = success(unknown.coinPub, 1, "TESTKUDOS:10");
+ const middle = success(split.coinPub, 2, "TESTKUDOS:2");
+ const last = success(split.coinPub, 3, "TESTKUDOS:4");
+ await collect([first, part, netOnly, first]);
+ const expected = [
+ [full.coinPub, "TESTKUDOS:10.1"],
+ [split.coinPub, "TESTKUDOS:3.9"],
+ [unknown.coinPub, "TESTKUDOS:9.9"],
+ ];
+ assert.deepEqual(await recoveryAmounts(), expected.sort());
+ const [firstGroup] = await runner.runReadWriteTx((tx) =>
+ tx.getRefundGroupsByProposal(purchase.proposalId),
+ );
+ await removeLedger(); // An existing wallet starts with only successful item rows.
+ await collect([
+ first,
+ { ...middle, type: "failure", exchange_status: 503 },
+ ]);
+ await collect([{ ...last, type: "failure", exchange_status: 503 }]);
+ assert.deepEqual(await recoveryAmounts(), expected);
+ const seeded = await runner.runReadWriteTx((tx) =>
+ tx.getPurchase(purchase.proposalId),
+ );
+ assert.deepEqual(seeded?.payInfo?.accountedRefunds?.[split.coinPub], {
+ 1: "TESTKUDOS:4",
+ });
+
+ await removeLedger(); // Deletion itself may be the first action after an upgrade.
+ await new RefundTransactionContext(
+ wex,
+ firstGroup.refundGroupId,
+ ).userDeleteTransaction();
+ await runner.close();
+ runner = await makeRunner(filename);
+ // Two groups settle together, with the later refund first on the wire.
+ await collect([first, part, netOnly, last, middle, last]);
+ expected.push(
+ [split.coinPub, "TESTKUDOS:1.9"],
+ [split.coinPub, "TESTKUDOS:4.1"],
+ );
+ assert.deepEqual(await recoveryAmounts(), expected.sort());
+ const groups = await runner.runReadWriteTx((tx) =>
+ tx.getRefundGroupsByProposal(purchase.proposalId),
+ );
+ assert.deepEqual(groups.map((g) => g.amountRaw).sort(), [
+ "TESTKUDOS:2",
+ "TESTKUDOS:4",
+ ]);
+ for (const group of groups) {
+ assert.equal(group.status, RefundGroupStatus.Done);
+ await new RefundTransactionContext(
+ wex,
+ group.refundGroupId,
+ ).userDeleteTransaction();
+ }
+ await collect([last, middle, first]);
+ assert.deepEqual(await recoveryAmounts(), expected);
+ await assert.rejects(
+ collect([success(split.coinPub, 4, "TESTKUDOS:1")]),
+ /refunds exceed their deposit/,
+ );
+ assert.deepEqual(await recoveryAmounts(), expected);
+ assert.deepEqual(
+ await runner.runReadWriteTx((tx) =>
+ tx.getRefundGroupsByProposal(purchase.proposalId),
+ ),
+ [],
+ );
+ } finally {
+ await runner.close();
+ await rm(directory, { recursive: true, force: true });
+ }
+ });
+
+ test(`${makeRunner.name}: deleting legacy refund history retains receipts when payment selection is missing`, async () => {
+ const runner = await makeRunner();
+ const purchase = makeDownloadedPurchase("legacy-refund");
+ purchase.payInfo = undefined;
+ const group = makeTestRefundGroup(purchase.proposalId, "legacy-group");
+ const coinPub = encodeCrock(new Uint8Array(32).fill(9));
+ const wex = {
+ runWalletDbTx: runner.runReadWriteTx.bind(runner),
+ } as WalletExecutionContext;
+ try {
+ await runner.runReadWriteTx(async (tx) => {
+ await tx.upsertPurchase(purchase);
+ await tx.upsertRefundGroup(group);
+ await tx.upsertRefundItem({
+ refundGroupId: group.refundGroupId,
+ coinPub,
+ rtxid: 1,
+ status: RefundItemStatus.Done,
+ refundAmount: "TESTKUDOS:3",
+ executionTime: timestampProtocolToDb({ t_s: 1 }),
+ obtainedTime: purchase.timestamp,
+ });
+ });
+ await new RefundTransactionContext(
+ wex,
+ group.refundGroupId,
+ ).userDeleteTransaction();
+ const saved = await runner.runReadWriteTx((tx) =>
+ tx.getPurchase(purchase.proposalId),
+ );
+ assert.equal(saved?.payInfo, undefined);
+ assert.deepEqual(saved?.download?.accountedRefunds, {
+ [coinPub]: { 1: "TESTKUDOS:3" },
+ });
+ } finally {
+ await runner.close();
+ }
+ });
+
test(`${makeRunner.name}: storing a refund records its reason`, async () => {
const runner = await makeRunner();
const purchase = makeDownloadedPurchase(
diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts
@@ -192,6 +192,10 @@ import {
RefreshTransactionContext,
} from "./refresh.js";
import {
+ accountMerchantRefunds,
+ loadAccountedRefunds,
+} from "./refund-accounting.js";
+import {
selectPayTokensInTx,
SelectPayTokensResult,
TokenMerchantVerificationResult,
@@ -1013,15 +1017,19 @@ export class RefundTransactionContext implements TransactionContext {
if (!refundRecord) {
return;
}
+ const purchase = await tx.getPurchase(refundRecord.proposalId);
+ if (
+ purchase &&
+ !purchase.payInfo?.accountedRefunds &&
+ !purchase.download?.accountedRefunds
+ ) {
+ // Deleting the group also deletes its items on both backends.
+ await loadAccountedRefunds(tx, purchase);
+ await tx.upsertPurchase(purchase);
+ }
await tx.deleteRefundGroup(this.refundGroupId);
await this.updateTransactionMeta(tx);
await tx.upsertTombstone({ id: this.transactionId });
- const items = await tx.getRefundItemsByGroup(refundRecord.refundGroupId);
- for (const item of items) {
- if (item.id != null) {
- await tx.deleteRefundItem(item.id);
- }
- }
tx.notify({
type: NotificationType.TransactionStateTransition,
causeHint: "delete",
@@ -4091,6 +4099,9 @@ async function processPurchasePay(
case PurchaseStatus.DialogProposed:
case PurchaseStatus.PendingPaying:
p.payInfo = {
+ ...(p.payInfo?.accountedRefunds && {
+ accountedRefunds: p.payInfo.accountedRefunds,
+ }),
totalPayCost: Amounts.stringify(payCostInfo),
payCoinSelection: {
coinContributions: selectCoinsResult.coinSel.coins.map(
@@ -6265,44 +6276,6 @@ export async function startQueryRefund(
await wex.runWalletDbTx((tx) => startQueryRefundInTx(ctx, tx));
}
-async function computeRefreshRequest(
- wex: WalletExecutionContext,
- tx: WalletDbTransaction,
- items: WalletRefundItem[],
-): Promise<CoinRefreshRequest[]> {
- const refreshAmounts = new Map<string, AmountJson>();
- const coins = await tx.getCoinsByPubs(items.map((item) => item.coinPub));
- const coinsByPub = new Map(coins.map((coin) => [coin.coinPub, coin]));
- const denoms = await getDenomInfos(wex, tx, coins);
- for (const item of items) {
- const coin = coinsByPub.get(item.coinPub);
- if (!coin) {
- throw Error("coin not found");
- }
- const denomInfo = denoms.get(denomRefKey(coin));
- if (!denomInfo) {
- throw Error("denom not found");
- }
- if (item.status === RefundItemStatus.Done) {
- const refundedAmount = Amounts.sub(
- item.refundAmount,
- denomInfo.feeRefund,
- ).amount;
- const previous =
- refreshAmounts.get(item.coinPub) ??
- Amounts.zeroOfAmount(refundedAmount);
- refreshAmounts.set(
- item.coinPub,
- Amounts.add(previous, refundedAmount).amount,
- );
- }
- }
- return Array.from(refreshAmounts, ([coinPub, amount]) => ({
- coinPub,
- amount: Amounts.stringify(amount),
- }));
-}
-
/**
* Compute the refund item status based on the merchant's response.
*/
@@ -6494,37 +6467,34 @@ export async function storeRefunds(
}
let newGroup: WalletRefundGroup | undefined = undefined;
- const newlySuccessfulRefunds = new Set<string>();
- const refundKey = (coinPub: string, rtxid: number) =>
- `${coinPub}\0${rtxid}`;
+ const accounted = await loadAccountedRefunds(tx, myPurchase);
+ const newlySuccessful: WalletRefundItem[] = [];
for (const rf of refunds) {
- const oldItem = await tx.getRefundItemByCoinAndRtxid(
+ if (accounted[rf.coin_pub]?.[rf.rtransaction_id] !== undefined) continue;
+ let item = await tx.getRefundItemByCoinAndRtxid(
rf.coin_pub,
rf.rtransaction_id,
);
- if (oldItem) {
- logger.info("already have refund in database");
- if (oldItem.status === RefundItemStatus.Done) {
+ if (item) {
+ if (item.status === RefundItemStatus.Done) {
continue;
}
if (rf.type === "success") {
- oldItem.status = RefundItemStatus.Done;
- delete oldItem.failReason;
- oldItem.refundAmount = rf.refund_amount;
- oldItem.executionTime = timestampProtocolToDb(rf.execution_time);
- oldItem.obtainedTime = timestampPreciseToDb(now);
- newlySuccessfulRefunds.add(refundKey(oldItem.coinPub, oldItem.rtxid));
+ item.status = RefundItemStatus.Done;
+ delete item.failReason;
+ item.refundAmount = rf.refund_amount;
+ item.executionTime = timestampProtocolToDb(rf.execution_time);
+ item.obtainedTime = timestampPreciseToDb(now);
} else {
if (isTransientRefundStatus(rf.exchange_status)) {
- oldItem.status = RefundItemStatus.Pending;
- delete oldItem.failReason;
+ item.status = RefundItemStatus.Pending;
+ delete item.failReason;
} else {
- oldItem.status = RefundItemStatus.Failed;
- oldItem.failReason = getPermanentRefundReason(rf);
+ item.status = RefundItemStatus.Failed;
+ item.failReason = getPermanentRefundReason(rf);
}
}
- await tx.upsertRefundItem(oldItem);
} else {
// Put refund item into a new group!
if (!newGroup) {
@@ -6541,7 +6511,7 @@ export async function storeRefunds(
};
}
const status: RefundItemStatus = getItemStatus(rf);
- const newItem: WalletRefundItem = {
+ item = {
coinPub: rf.coin_pub,
executionTime: timestampProtocolToDb(rf.execution_time),
obtainedTime: timestampPreciseToDb(now),
@@ -6551,11 +6521,9 @@ export async function storeRefunds(
status,
failReason: getPermanentRefundReason(rf),
};
- if (status === RefundItemStatus.Done) {
- newlySuccessfulRefunds.add(refundKey(newItem.coinPub, newItem.rtxid));
- }
- await tx.upsertRefundItem(newItem);
}
+ await tx.upsertRefundItem(item);
+ if (item.status === RefundItemStatus.Done) newlySuccessful.push(item);
}
// Create the group before the common item-level accounting below.
@@ -6586,6 +6554,14 @@ export async function storeRefunds(
purchase.proposalId,
);
+ const recoveryByGroup = await accountMerchantRefunds(
+ wex,
+ tx,
+ myPurchase,
+ ctx.transactionId,
+ accounted,
+ newlySuccessful,
+ );
let numPendingItemsTotal = 0;
for (const refundGroup of refundGroups) {
const refundCtx = new RefundTransactionContext(
@@ -6607,10 +6583,12 @@ export async function storeRefunds(
myPurchase.purchaseStatus,
);
}
+ const newlyRefundedCoins = recoveryByGroup.get(refundGroup.refundGroupId);
switch (refundGroup.status) {
case RefundGroupStatus.Aborted:
case RefundGroupStatus.Expired:
case RefundGroupStatus.Done:
+ if (newlyRefundedCoins) break;
if (needsHistory) {
await tx.upsertRefundGroup(refundGroup);
await refundCtx.updateTransactionMeta(tx);
@@ -6632,15 +6610,7 @@ export async function storeRefunds(
successfulItems.map((x) => x.refundAmount),
).amount,
);
- const newlySuccessfulItems = successfulItems.filter((x) =>
- newlySuccessfulRefunds.has(refundKey(x.coinPub, x.rtxid)),
- );
- const newlyRefundedCoins = await computeRefreshRequest(
- wex,
- tx,
- newlySuccessfulItems,
- );
- if (newlyRefundedCoins.length > 0) {
+ if (newlyRefundedCoins) {
const outInfo = await calculateRefreshOutput(
wex,
tx,
@@ -6653,10 +6623,6 @@ export async function storeRefunds(
Amounts.sumOrZero(currency, outInfo.outputPerCoin).amount,
).amount,
);
- const paymentTransactionId = constructTransactionIdentifier({
- tag: TransactionType.Payment,
- proposalId: purchase.proposalId,
- });
const refreshResult = await createRefreshGroup(
wex,
tx,
@@ -6665,9 +6631,10 @@ export async function storeRefunds(
RefreshReason.Refund,
// Refunds are pseudo-transactions, so their recovery refresh is
// associated with the payment transaction.
- paymentTransactionId,
+ ctx.transactionId,
);
refundGroup.refreshGroupId = refreshResult.refreshGroupId;
+ recoveryByGroup.delete(refundGroup.refundGroupId);
}
let numPending = 0;
let numFailed = 0;
@@ -6710,6 +6677,10 @@ export async function storeRefunds(
await refundCtx.updateTransactionMeta(tx);
}
}
+ checkDbInvariant(
+ recoveryByGroup.size === 0,
+ "refund does not belong to this payment",
+ );
const shouldCheckAutoRefund =
myPurchase.autoRefundDeadline &&
!AbsoluteTime.isExpired(
diff --git a/packages/taler-wallet-core/src/refund-accounting.ts b/packages/taler-wallet-core/src/refund-accounting.ts
@@ -0,0 +1,185 @@
+/*
+ This file is part of GNU Taler
+ (C) 2026 Taler Systems S.A.
+
+ GNU Taler is free software; you can redistribute it and/or modify it under the
+ terms of the GNU General Public License as published by the Free Software
+ Foundation; either version 3, or (at your option) any later version.
+
+ GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+ A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along with
+ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
+ */
+
+import {
+ AmountJson,
+ AmountLike,
+ Amounts,
+ AmountString,
+ checkDbInvariant,
+ CoinRefreshRequest,
+ TalerError,
+ TalerErrorCode,
+ TransactionIdStr,
+} from "@gnu-taler/taler-util";
+import {
+ AccountedCoinRefunds,
+ RefundItemStatus,
+ WalletPurchase,
+ WalletRefundItem,
+} from "./db/records.js";
+import { WalletDbTransaction } from "./db/transaction.js";
+import {
+ denomRefKey,
+ getDenomInfos,
+ WalletExecutionContext,
+} from "./wallet.js";
+
+/** The exchange waives the deposit fee once cumulative gross refunds cover the coin's contribution. */
+export function calculateCoinRefund(args: {
+ contribution: AmountLike | undefined;
+ previousGross: AmountLike;
+ grossRefund: AmountLike;
+ refundFee: AmountLike;
+ depositFee: AmountLike;
+}): { credit: AmountJson; totalGross: AmountJson } {
+ const total = Amounts.add(args.previousGross, args.grossRefund);
+ if (
+ total.saturated ||
+ (args.contribution !== undefined &&
+ Amounts.cmp(total.amount, args.contribution) > 0)
+ ) {
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
+ {},
+ "cumulative refunds exceed their deposit",
+ );
+ }
+ const net = Amounts.sub(args.grossRefund, args.refundFee);
+ if (
+ !net.saturated &&
+ args.contribution !== undefined &&
+ Amounts.cmp(total.amount, args.contribution) === 0 &&
+ Amounts.isNonZero(args.grossRefund)
+ ) {
+ const withFee = Amounts.add(net.amount, args.depositFee);
+ if (withFee.saturated) {
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
+ {},
+ "refunded deposit fee overflows the coin balance",
+ );
+ }
+ return { credit: withFee.amount, totalGross: total.amount };
+ }
+ return { credit: net.amount, totalGross: total.amount };
+}
+
+/** Seed once, before accepting new items or deleting refund history. The caller persists the purchase. */
+export async function loadAccountedRefunds(
+ tx: WalletDbTransaction,
+ purchase: WalletPurchase,
+): Promise<AccountedCoinRefunds> {
+ const saved =
+ purchase.payInfo?.accountedRefunds ?? purchase.download?.accountedRefunds;
+ if (saved) return saved;
+ const accounted: AccountedCoinRefunds = {};
+ const groups = await tx.getRefundGroupsByProposal(purchase.proposalId);
+ for (const group of groups) {
+ for (const item of await tx.getRefundItemsByGroup(group.refundGroupId)) {
+ if (item.status === RefundItemStatus.Done) {
+ (accounted[item.coinPub] ??= {})[item.rtxid] = item.refundAmount;
+ }
+ }
+ }
+ // A purchase needs a downloaded contract to collect refunds. Legacy purchases
+ // can lack payInfo; preserve that fact and use their existing download JSON.
+ const owner = purchase.payInfo ?? purchase.download;
+ if (owner) owner.accountedRefunds = accounted;
+ return accounted;
+}
+
+/** Allocate all newly confirmed items together, returning refresh inputs by refund group. */
+export async function accountMerchantRefunds(
+ wex: WalletExecutionContext,
+ tx: WalletDbTransaction,
+ purchase: WalletPurchase,
+ paymentId: TransactionIdStr,
+ accounted: AccountedCoinRefunds,
+ items: WalletRefundItem[],
+): Promise<Map<string, CoinRefreshRequest[]>> {
+ const requests = new Map<string, CoinRefreshRequest[]>();
+ if (!items.length) return requests;
+ const byCoin = new Map<string, WalletRefundItem[]>();
+ for (const item of items) {
+ const batch = byCoin.get(item.coinPub);
+ if (batch) batch.push(item);
+ else byCoin.set(item.coinPub, [item]);
+ }
+ const contributions = new Map<string, AmountString>();
+ const selection = purchase.payInfo?.payCoinSelection;
+ selection?.coinPubs.forEach((pub, i) => {
+ contributions.set(pub, selection.coinContributions[i]);
+ });
+ // A repaired selection or a legacy purchase can omit the spent coin.
+ const pubs = Array.from(byCoin.keys());
+ const missing = pubs.filter((pub) => !contributions.get(pub));
+ if (missing.length) {
+ for (const history of await tx.getCoinHistoriesByPubs(missing)) {
+ const spends = history.history.filter(
+ (e) => e.type === "spend" && e.transactionId === paymentId,
+ );
+ if (spends.length === 1 && spends[0].type === "spend") {
+ contributions.set(history.coinPub, spends[0].amount);
+ }
+ }
+ }
+ const coins = await tx.getCoinsByPubs(pubs);
+ checkDbInvariant(coins.length === pubs.length, "refunded coin not found");
+ const denominations = await getDenomInfos(wex, tx, coins);
+ for (const coin of coins) {
+ const denom = denominations.get(denomRefKey(coin));
+ checkDbInvariant(!!denom, "refunded denomination not found");
+ const receipts = (accounted[coin.coinPub] ??= {});
+ const previous = Amounts.sumOrZero(
+ Amounts.currencyOf(denom.value),
+ Object.values(receipts),
+ );
+ checkDbInvariant(!previous.saturated, "stored gross refunds overflow");
+ let totalGross = previous.amount;
+ const creditByGroup = new Map<string, AmountJson>();
+ // Multiple pending groups can settle in one response. Attribute the waiver
+ // in execution order, breaking timestamp ties with the coin's refund ID.
+ const batch = byCoin.get(coin.coinPub)!;
+ batch.sort(
+ (a, b) => a.executionTime - b.executionTime || a.rtxid - b.rtxid,
+ );
+ for (const item of batch) {
+ const result = calculateCoinRefund({
+ contribution: contributions.get(coin.coinPub),
+ previousGross: totalGross,
+ grossRefund: item.refundAmount,
+ refundFee: denom.feeRefund,
+ depositFee: denom.feeDeposit,
+ });
+ totalGross = result.totalGross;
+ const sum = Amounts.add(
+ creditByGroup.get(item.refundGroupId) ??
+ Amounts.zeroOfAmount(totalGross),
+ result.credit,
+ );
+ checkDbInvariant(!sum.saturated, "refund recovery amount overflows");
+ creditByGroup.set(item.refundGroupId, sum.amount);
+ receipts[item.rtxid] = item.refundAmount;
+ }
+ for (const [groupId, credit] of creditByGroup) {
+ const group = requests.get(groupId) ?? [];
+ group.push({ coinPub: coin.coinPub, amount: Amounts.stringify(credit) });
+ requests.set(groupId, group);
+ }
+ }
+ return requests;
+}