commit 38f415f96c53c1cf87b3a39d4a661997c6e22cbe
parent 82bde503a45abaee86f80161aadfa44d22dd4719
Author: Florian Dold <dold@taler.net>
Date: Thu, 26 Nov 2026 04:19:09 +0100
wallet-core: reject a deposit if its quote changed after review
Preview and confirmation select coins separately. Check the reviewed
debit, bank credit, fees and KYC conditions in the same database
transaction that spends the coins, so a changed quote leaves the balance
intact.
Diffstat:
5 files changed, 331 insertions(+), 344 deletions(-)
diff --git a/packages/taler-harness/src/integrationtests/test-deposit.ts b/packages/taler-harness/src/integrationtests/test-deposit.ts
@@ -19,6 +19,7 @@
*/
import {
AmountString,
+ TalerErrorCode,
TransactionMajorState,
TransactionMinorState,
j2s,
@@ -83,11 +84,41 @@ export async function runDepositTest(t: GlobalTestState) {
t.assertDeepEqual(exchangeDiagnostics[0].reasons, []);
t.assertDeepEqual(exchangeDiagnostics[0].material, maxDepositResp.material);
- const depositGroupResult = await walletClient.client.call(
+ const request = { amount: "TESTKUDOS:10" as AmountString, depositPaytoUri };
+ const quote = await walletClient.call(
+ WalletApiOperation.CheckDeposit,
+ request,
+ );
+ // Even a change confined to the fee breakdown requires another review.
+ const rejected = await t.assertThrowsTalerErrorAsync(() =>
+ walletClient.call(WalletApiOperation.CreateDepositGroup, {
+ ...request,
+ expectedQuote: { ...quote, fees: { ...quote.fees, wire: "TESTKUDOS:1" } },
+ }),
+ );
+ t.assertDeepEqual(
+ rejected.errorDetail.code,
+ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
+ );
+ t.assertDeepEqual(rejected.errorDetail.parameter, "expectedQuote");
+ const afterRejection = await walletClient.call(
+ WalletApiOperation.GetBalances,
+ {},
+ );
+ t.assertDeepEqual(afterRejection.balances, bal.balances);
+ const afterRejectionHistory = await walletClient.call(
+ WalletApiOperation.GetTransactionsV2,
+ {},
+ );
+ t.assertTrue(
+ afterRejectionHistory.transactions.every((tx) => tx.type !== "deposit"),
+ );
+
+ const depositGroupResult = await walletClient.call(
WalletApiOperation.CreateDepositGroup,
{
- amount: "TESTKUDOS:10" as AmountString,
- depositPaytoUri,
+ ...request,
+ expectedQuote: quote,
},
);
diff --git a/packages/taler-util/src/types-taler-wallet.ts b/packages/taler-util/src/types-taler-wallet.ts
@@ -29,7 +29,7 @@
/**
* Imports.
*/
-import { AmountJson, codecForAmountString } from "./amounts.js";
+import { AmountJson, Amounts, codecForAmountString } from "./amounts.js";
import {
Codec,
Context,
@@ -3505,6 +3505,9 @@ export interface DepositGroupFees {
export interface CreateDepositGroupRequest {
depositPaytoUri: string;
+ /** Proceed only if the selected coins still give the reviewed amounts, fees and KYC conditions. */
+ expectedQuote?: CheckDepositResponse;
+
/**
* Instructed amount used for deposit coin selection.
*/
@@ -3581,12 +3584,54 @@ export interface CheckDepositResponse {
kycExchanges?: string[];
}
+export function depositQuotesMatch(
+ a: CheckDepositResponse,
+ b: CheckDepositResponse,
+): boolean {
+ const sameAmount = (left?: AmountString, right?: AmountString) =>
+ left === right ||
+ (left !== undefined &&
+ right !== undefined &&
+ Amounts.stringify(left) === Amounts.stringify(right));
+ const exchanges = new Set(a.kycExchanges);
+ const otherExchanges = new Set(b.kycExchanges);
+ return (
+ sameAmount(a.totalDepositCost, b.totalDepositCost) &&
+ sameAmount(a.effectiveDepositAmount, b.effectiveDepositAmount) &&
+ sameAmount(a.fees.coin, b.fees.coin) &&
+ sameAmount(a.fees.wire, b.fees.wire) &&
+ sameAmount(a.fees.refresh, b.fees.refresh) &&
+ sameAmount(a.kycSoftLimit, b.kycSoftLimit) &&
+ sameAmount(a.kycHardLimit, b.kycHardLimit) &&
+ exchanges.size === otherExchanges.size &&
+ [...exchanges].every((exchange) => otherExchanges.has(exchange))
+ );
+}
+
+const codecForDepositQuote = (): Codec<CheckDepositResponse> =>
+ buildCodecForObject<CheckDepositResponse>()
+ .property("totalDepositCost", codecForAmountString())
+ .property("effectiveDepositAmount", codecForAmountString())
+ .property(
+ "fees",
+ buildCodecForObject<DepositGroupFees>()
+ .property("coin", codecForAmountString())
+ .property("wire", codecForAmountString())
+ .property("refresh", codecForAmountString())
+ .build("DepositGroupFees"),
+ )
+ .property("kycSoftLimit", codecOptional(codecForAmountString()))
+ .property("kycHardLimit", codecOptional(codecForAmountString()))
+ .property("kycExchanges", codecOptional(codecForList(codecForString())))
+ .build("DepositQuote");
+
export const codecForCreateDepositGroupRequest =
(): Codec<CreateDepositGroupRequest> =>
buildCodecForObject<CreateDepositGroupRequest>()
.property("restrictScope", codecOptional(codecForScopeInfo()))
.property("amount", codecForAmountString())
.property("depositPaytoUri", codecForString())
+ .property("expectedQuote", codecOptional(codecForDepositQuote()))
.property("transactionId", codecOptional(codecForTransactionIdStr()))
.property("testingFixedPriv", codecOptional(codecForString()))
.property("wireDeadline", codecOptional(codecForTimestamp))
diff --git a/packages/taler-wallet-core/src/deposits.test.ts b/packages/taler-wallet-core/src/deposits.test.ts
@@ -17,6 +17,9 @@
import {
AbsoluteTime,
Amounts,
+ type CheckDepositResponse,
+ codecForCreateDepositGroupRequest,
+ depositQuotesMatch,
HttpStatusCode,
TalerErrorCode,
TalerProtocolTimestamp,
@@ -44,6 +47,58 @@ import {
requireFiniteDepositWireDeadline,
} from "./deposits.js";
+test("deposit approval compares all reviewed amounts, fees and KYC conditions", () => {
+ const approved: CheckDepositResponse = {
+ totalDepositCost: "KUDOS:11",
+ effectiveDepositAmount: "KUDOS:9",
+ fees: { coin: "KUDOS:0.2", wire: "KUDOS:0.8", refresh: "KUDOS:1" },
+ kycSoftLimit: "KUDOS:5",
+ kycHardLimit: "KUDOS:50",
+ kycExchanges: ["https://a.example/", "https://b.example/"],
+ };
+ const req = { amount: "KUDOS:10", depositPaytoUri: "payto://iban/DE123456" };
+ assert.strictEqual(
+ codecForCreateDepositGroupRequest().decode(req).expectedQuote,
+ undefined,
+ );
+ assert.deepEqual(
+ codecForCreateDepositGroupRequest().decode({
+ ...req,
+ expectedQuote: approved,
+ }).expectedQuote,
+ approved,
+ );
+ assert.throws(() =>
+ codecForCreateDepositGroupRequest().decode({
+ ...req,
+ expectedQuote: { ...approved, fees: {} },
+ }),
+ );
+ assert(
+ depositQuotesMatch(approved, {
+ ...approved,
+ totalDepositCost: "KUDOS:11.00",
+ kycExchanges: [...approved.kycExchanges!].reverse(),
+ }),
+ );
+ const changes: Partial<CheckDepositResponse>[] = [
+ { totalDepositCost: "KUDOS:12" },
+ { effectiveDepositAmount: "KUDOS:8" },
+ { fees: { ...approved.fees, coin: "KUDOS:0.3" } },
+ { fees: { ...approved.fees, wire: "KUDOS:0.7" } },
+ { fees: { ...approved.fees, refresh: "KUDOS:2" } },
+ { kycSoftLimit: undefined },
+ { kycHardLimit: "KUDOS:40" },
+ { kycExchanges: ["https://a.example/"] },
+ ];
+ for (const changed of changes) {
+ assert.strictEqual(
+ depositQuotesMatch(approved, { ...approved, ...changed }),
+ false,
+ );
+ }
+});
+
test("direct deposits reject an infinite wire deadline before selection", () => {
assert.throws(
() => requireFiniteDepositWireDeadline(TalerProtocolTimestamp.never()),
diff --git a/packages/taler-wallet-core/src/deposits.ts b/packages/taler-wallet-core/src/deposits.ts
@@ -35,11 +35,9 @@ import {
CoinRefreshRequest,
CreateDepositGroupRequest,
CreateDepositGroupResponse,
- DepositGroupFees,
DepositTransactionTrackingState,
DownloadedContractData,
Duration,
- Exchange,
ExchangeBatchDepositRequest,
ExchangeRefundRequest,
ExchangeWireAccount,
@@ -74,6 +72,7 @@ import {
checkDbInvariant,
checkLogicInvariant,
codecForMerchantContractTerms,
+ depositQuotesMatch,
encodeCrock,
getRandomBytes,
hashWire,
@@ -121,6 +120,7 @@ import {
fetchFreshExchangeWithRetryNow,
findExchangeWireFee,
getExchangeDetailsInTx,
+ loadReadyExchangeSummary,
getLegacyScopesForTransaction,
getScopeForAllExchanges,
markExchangeUsed,
@@ -142,10 +142,7 @@ import {
makeKycHardLimitError,
runKycCheckAlgo,
} from "./kyc.js";
-import {
- generateDepositPermissions,
- getTotalPaymentCost,
-} from "./pay-merchant.js";
+import { generateDepositPermissions } from "./pay-merchant.js";
import { runWithMaybeProgressContext } from "./progress.js";
import {
classifyRecoveryRefresh,
@@ -2730,91 +2727,67 @@ export async function internalCheckDepositGroup(
wex: WalletExecutionContext,
req: CheckDepositRequest,
): Promise<CheckDepositResponse> {
- const p = Paytos.parseOrThrow(req.depositPaytoUri);
- const amount = Amounts.parseOrThrow(req.amount);
- const currency = Amounts.currencyOf(amount);
+ const { wireType, currency, coins } = await selectDepositCoins(wex, req);
+ for (const url of new Set(coins.map((coin) => coin.exchangeBaseUrl))) {
+ await fetchFreshExchange(wex, url);
+ }
+ return wex.runWalletDbTx(async (tx) => {
+ const { quote } = await getDepositQuoteInTx(
+ wex,
+ tx,
+ wireType,
+ currency,
+ coins,
+ );
+ return quote;
+ });
+}
- const exchangeInfos: Exchange[] = await getExchangesForDeposit(wex, {
+async function selectDepositCoins(
+ wex: WalletExecutionContext,
+ req: CheckDepositRequest,
+) {
+ const wireType = Paytos.parseOrThrow(req.depositPaytoUri).targetType!;
+ const amount = Amounts.parseOrThrow(req.amount);
+ const currency = amount.currency;
+ const exchangeInfos = await getExchangesForDeposit(wex, {
currency,
restrictScope: req.restrictScope,
});
-
- if (exchangeInfos.length == 0) {
+ if (!exchangeInfos.length) {
throw TalerError.fromDetail(
TalerErrorCode.WALLET_NO_SUITABLE_EXCHANGE,
- { currency, wireMethod: p.targetType },
+ { currency, wireMethod: wireType },
"no exchange in the wallet can be used for this deposit",
);
}
-
- const depositFeeLimit = amount;
-
- const payCoinSel = await selectPayCoins(wex, {
+ const selection = await selectPayCoins(wex, {
restrictExchanges: {
auditors: [],
- exchanges: exchangeInfos.map((x) => {
- return {
- exchangeBaseUrl: x.url,
- exchangePub: x.master_pub,
- };
- }),
+ exchanges: exchangeInfos.map((x) => ({
+ exchangeBaseUrl: x.url,
+ exchangePub: x.master_pub,
+ })),
},
restrictScope: req.restrictScope,
- restrictWireMethod: p.targetType!,
+ restrictWireMethod: wireType,
depositPaytoUri: req.depositPaytoUri,
- contractTermsAmount: Amounts.parseOrThrow(req.amount),
- depositFeeLimit,
+ contractTermsAmount: amount,
+ depositFeeLimit: amount,
prevPayCoins: [],
});
-
- let selCoins: SelectedProspectiveCoin[] | undefined = undefined;
-
- switch (payCoinSel.type) {
- case "failure":
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE,
- {
- insufficientBalanceDetails: payCoinSel.insufficientBalanceDetails,
- },
- );
- case "success":
- selCoins = payCoinSel.coinSel.coins;
- break;
- default:
- assertUnreachable(payCoinSel);
- }
-
- const totalDepositCost = await getTotalPaymentCost(wex, currency, selCoins);
-
- const effectiveDepositAmount = await getCounterpartyEffectiveDepositAmount(
- wex,
- p.targetType!,
- selCoins,
- );
-
- const usedExchangesSet = new Set<string>();
- for (const c of selCoins) {
- usedExchangesSet.add(c.exchangeBaseUrl);
- }
-
- const exchanges: ReadyExchangeSummary[] = [];
-
- for (const exchangeBaseUrl of usedExchangesSet) {
- exchanges.push(await fetchFreshExchange(wex, exchangeBaseUrl));
+ if (selection.type === "failure") {
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE,
+ { insufficientBalanceDetails: selection.insufficientBalanceDetails },
+ );
}
-
- const fees = await getTotalFeesForDepositAmount(
- wex,
- p.targetType!,
- amount,
- selCoins,
- );
-
return {
- totalDepositCost: Amounts.stringify(totalDepositCost),
- effectiveDepositAmount: Amounts.stringify(effectiveDepositAmount),
- fees,
- ...getDepositLimitInfo(exchanges, effectiveDepositAmount),
+ amount,
+ currency,
+ wireType,
+ exchangeInfos,
+ coins: selection.coinSel.coins,
};
}
@@ -2834,24 +2807,11 @@ async function internalCreateDepositGroup(
wex: WalletExecutionContext,
req: CreateDepositGroupRequest,
): Promise<CreateDepositGroupResponse> {
- const depositPayto = Paytos.parseOrThrow(req.depositPaytoUri);
-
- const amount = Amounts.parseOrThrow(req.amount);
- const currency = amount.currency;
-
requireFiniteDepositWireDeadline(req.wireDeadline);
-
- const exchangeInfos: Exchange[] = await getExchangesForDeposit(wex, {
- currency,
- restrictScope: req.restrictScope,
- });
-
- if (exchangeInfos.length == 0) {
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_NO_SUITABLE_EXCHANGE,
- { currency, wireMethod: depositPayto.targetType },
- "no exchange in the wallet can be used for this deposit",
- );
+ const { amount, currency, wireType, exchangeInfos, coins } =
+ await selectDepositCoins(wex, req);
+ for (const url of new Set(coins.map((coin) => coin.exchangeBaseUrl))) {
+ await fetchFreshExchangeWithRetryNow(wex, url);
}
const now = AbsoluteTime.now();
@@ -2859,75 +2819,6 @@ async function internalCreateDepositGroup(
req.wireDeadline ?? AbsoluteTime.toProtocolTimestamp(now);
const nowRounded = AbsoluteTime.toProtocolTimestamp(now);
- const payCoinSel = await selectPayCoins(wex, {
- restrictExchanges: {
- auditors: [],
- exchanges: exchangeInfos.map((x) => ({
- exchangeBaseUrl: x.url,
- exchangePub: x.master_pub,
- })),
- },
- restrictScope: req.restrictScope,
- restrictWireMethod: depositPayto.targetType!,
- depositPaytoUri: req.depositPaytoUri,
- contractTermsAmount: amount,
- depositFeeLimit: amount,
- prevPayCoins: [],
- });
-
- let coins: SelectedProspectiveCoin[] | undefined = undefined;
-
- switch (payCoinSel.type) {
- case "success":
- coins = payCoinSel.coinSel.coins;
- break;
- case "failure":
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE,
- {
- insufficientBalanceDetails: payCoinSel.insufficientBalanceDetails,
- },
- );
- default:
- assertUnreachable(payCoinSel);
- }
-
- const usedExchangesSet = new Set<string>();
- for (const c of coins) {
- usedExchangesSet.add(c.exchangeBaseUrl);
- }
-
- const exchanges: ReadyExchangeSummary[] = [];
-
- for (const exchangeBaseUrl of usedExchangesSet) {
- exchanges.push(await fetchFreshExchangeWithRetryNow(wex, exchangeBaseUrl));
- }
-
- const contributionsByExchange = new Map<string, AmountJson>();
- for (const coin of coins) {
- const oldAmount =
- contributionsByExchange.get(coin.exchangeBaseUrl) ??
- Amounts.zeroOfAmount(coin.contribution);
- contributionsByExchange.set(
- coin.exchangeBaseUrl,
- Amounts.add(oldAmount, coin.contribution).amount,
- );
- }
- const hardLimitViolation = checkDepositHardLimitExceededPerExchange(
- exchanges,
- contributionsByExchange,
- );
- if (hardLimitViolation) {
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_KYC_LIMIT_EXCEEDED,
- {
- exchangeBaseUrl: hardLimitViolation.exchangeBaseUrl,
- requestedAmount: hardLimitViolation.amount,
- },
- "deposit would exceed a hard limit of the exchange",
- );
- }
-
let merchantPair: EddsaKeyPairStrings;
if (req.testingFixedPriv) {
const merchantPub = await wex.cryptoApi.eddsaGetPublic({
@@ -2961,7 +2852,7 @@ async function internalCreateDepositGroup(
})),
amount: req.amount,
max_fee: Amounts.stringify(amount),
- wire_method: depositPayto.targetType!,
+ wire_method: wireType,
timestamp: nowRounded,
merchant_base_url: "",
summary: "",
@@ -3000,8 +2891,6 @@ async function internalCreateDepositGroup(
);
}
- const totalDepositCost = await getTotalPaymentCost(wex, currency, coins);
-
let depositGroupId: string;
if (req.transactionId) {
const txId = parseTransactionIdentifier(req.transactionId);
@@ -3016,91 +2905,88 @@ async function internalCreateDepositGroup(
depositGroupId = encodeCrock(getRandomBytes(32));
}
- const infoPerExchange: Record<string, WalletDepositInfoPerExchange> = {};
-
- for (let i = 0; i < coins.length; i++) {
- let depPerExchange = infoPerExchange[coins[i].exchangeBaseUrl];
- if (!depPerExchange) {
- infoPerExchange[coins[i].exchangeBaseUrl] = depPerExchange = {
- amountEffective: Amounts.stringify(
- Amounts.zeroOfAmount(totalDepositCost),
- ),
- };
- }
- const contrib = coins[i].contribution;
- depPerExchange.amountEffective = Amounts.stringify(
- Amounts.add(depPerExchange.amountEffective, contrib).amount,
- );
- }
-
- const counterpartyEffectiveDepositAmount =
- await getCounterpartyEffectiveDepositAmount(
- wex,
- depositPayto.targetType!,
- coins,
- );
-
- const depositGroup: WalletDepositGroup = {
- contractTermsHash,
- depositGroupId,
- currency: Amounts.currencyOf(totalDepositCost),
- amount: contractData.contractTerms.amount,
- noncePriv: noncePair.priv,
- noncePub: noncePair.pub,
- timestampCreated: timestampPreciseToDb(
- AbsoluteTime.toPreciseTimestamp(now),
- ),
- timestampFinished: undefined,
- statusPerCoin: undefined,
- payCoinSelection: undefined,
- payCoinSelectionUid: undefined,
- merchantPriv: merchantPair.priv,
- merchantPub: merchantPair.pub,
- totalPayCost: Amounts.stringify(totalDepositCost),
- counterpartyEffectiveDepositAmount: Amounts.stringify(
- counterpartyEffectiveDepositAmount,
- ),
- wireTransferDeadline: timestampProtocolToDb(
- contractTerms.wire_transfer_deadline,
- ),
- wire: {
- payto_uri: req.depositPaytoUri,
- salt: wireSalt,
- },
- timestampLastDepositAttempt: undefined,
- operationStatus: DepositOperationStatus.PendingDeposit,
- infoPerExchange,
- };
-
- if (payCoinSel.type === "success") {
- depositGroup.payCoinSelection = {
- coinContributions: payCoinSel.coinSel.coins.map((x) => x.contribution),
- coinPubs: payCoinSel.coinSel.coins.map((x) => x.coinPub),
- };
- depositGroup.payCoinSelectionUid = encodeCrock(getRandomBytes(32));
- depositGroup.statusPerCoin = payCoinSel.coinSel.coins.map(
- () => DepositElementStatus.DepositPending,
- );
- }
-
const ctx = new DepositTransactionContext(wex, depositGroupId);
const transactionId = ctx.transactionId;
-
const newTxState = await wex.runWalletDbTx(async (tx) => {
const [oldDg, h] = await ctx.getRecordHandle(tx);
if (oldDg != null) {
throw Error("deposit group already exists");
}
- if (depositGroup.payCoinSelection) {
- await spendCoins(wex, tx, {
- transactionId,
- coinPubs: depositGroup.payCoinSelection.coinPubs,
- contributions: depositGroup.payCoinSelection.coinContributions.map(
- (x) => Amounts.parseOrThrow(x),
- ),
- refreshReason: RefreshReason.PayDeposit,
- });
+ const { quote, exchanges, contributions } = await getDepositQuoteInTx(
+ wex,
+ tx,
+ wireType,
+ currency,
+ coins,
+ );
+ if (req.expectedQuote && !depositQuotesMatch(req.expectedQuote, quote)) {
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
+ { parameter: "expectedQuote" },
+ "the reviewed deposit amounts, fees or KYC conditions have changed",
+ );
}
+ const hardLimitViolation = checkDepositHardLimitExceededPerExchange(
+ exchanges,
+ contributions,
+ );
+ if (hardLimitViolation) {
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_KYC_LIMIT_EXCEEDED,
+ {
+ exchangeBaseUrl: hardLimitViolation.exchangeBaseUrl,
+ requestedAmount: hardLimitViolation.amount,
+ },
+ "deposit would exceed a hard limit of the exchange",
+ );
+ }
+ const infoPerExchange: Record<string, WalletDepositInfoPerExchange> = {};
+ for (const [exchange, contribution] of contributions) {
+ infoPerExchange[exchange] = {
+ amountEffective: Amounts.stringify(contribution),
+ };
+ }
+ const depositGroup: WalletDepositGroup = {
+ contractTermsHash,
+ depositGroupId,
+ currency,
+ amount: req.amount,
+ noncePriv: noncePair.priv,
+ noncePub: noncePair.pub,
+ timestampCreated: timestampPreciseToDb(
+ AbsoluteTime.toPreciseTimestamp(now),
+ ),
+ timestampFinished: undefined,
+ statusPerCoin: coins.map(() => DepositElementStatus.DepositPending),
+ payCoinSelection: {
+ coinContributions: coins.map((coin) => coin.contribution),
+ coinPubs: coins.map((coin) => coin.coinPub),
+ },
+ payCoinSelectionUid: encodeCrock(getRandomBytes(32)),
+ merchantPriv: merchantPair.priv,
+ merchantPub: merchantPair.pub,
+ totalPayCost: quote.totalDepositCost,
+ counterpartyEffectiveDepositAmount: quote.effectiveDepositAmount,
+ wireTransferDeadline: timestampProtocolToDb(
+ contractTerms.wire_transfer_deadline,
+ ),
+ wire: {
+ payto_uri: req.depositPaytoUri,
+ salt: wireSalt,
+ },
+ timestampLastDepositAttempt: undefined,
+ operationStatus: DepositOperationStatus.PendingDeposit,
+ infoPerExchange,
+ };
+
+ await spendCoins(wex, tx, {
+ transactionId,
+ coinPubs: coins.map((coin) => coin.coinPub),
+ contributions: coins.map((coin) =>
+ Amounts.parseOrThrow(coin.contribution),
+ ),
+ refreshReason: RefreshReason.PayDeposit,
+ });
await tx.upsertContractTerms({
contractTermsRaw: contractTerms,
h: contractTermsHash,
@@ -3130,114 +3016,83 @@ export function requireFiniteDepositWireDeadline(
}
}
-/**
- * Get the amount that will be deposited on the users bank
- * account after depositing, not considering aggregation.
- */
-async function getCounterpartyEffectiveDepositAmount(
+/** Calculate the preview and committed deposit from one snapshot of fees and exchange limits. */
+async function getDepositQuoteInTx(
wex: WalletExecutionContext,
+ tx: WalletDbTransaction,
wireType: string,
- pcs: SelectedProspectiveCoin[],
-): Promise<AmountJson> {
- const amt: AmountJson[] = [];
- const fees: AmountJson[] = [];
- const exchangeSet: Set<string> = new Set();
-
- await wex.runWalletDbTx(async (tx) => {
- const denoms = await getDenomInfos(wex, tx, pcs);
- for (let i = 0; i < pcs.length; i++) {
- const denom = denoms.get(denomRefKey(pcs[i]));
- if (!denom) {
- throw Error("can't find denomination to calculate deposit amount");
- }
- amt.push(Amounts.parseOrThrow(pcs[i].contribution));
- fees.push(Amounts.parseOrThrow(denom.feeDeposit));
- exchangeSet.add(pcs[i].exchangeBaseUrl);
- }
-
- for (const exchangeUrl of exchangeSet.values()) {
- const exchangeDetails = await getExchangeDetailsInTx(tx, exchangeUrl);
- if (!exchangeDetails) {
- continue;
- }
-
- // FIXME/NOTE: the line below _likely_ throws exception
- // about "find method not found on undefined" when the wireType
- // is not supported by the Exchange.
- const fee = exchangeDetails.wireInfo.feesForType[wireType]?.find((x) => {
- return AbsoluteTime.isBetween(
- AbsoluteTime.now(),
- AbsoluteTime.fromProtocolTimestamp(x.startStamp),
- AbsoluteTime.fromProtocolTimestamp(x.endStamp),
- );
- })?.wireFee;
- if (fee) {
- fees.push(Amounts.parseOrThrow(fee));
- }
+ currency: string,
+ coins: SelectedProspectiveCoin[],
+) {
+ const denoms = await getDenomInfos(wex, tx, coins);
+ const contributions = new Map<string, AmountJson>();
+ const coinFees: AmountString[] = [];
+ const refreshRequests = [];
+ for (const coin of coins) {
+ const denom = denoms.get(denomRefKey(coin));
+ checkDbInvariant(
+ !!denom,
+ "can't find denomination to calculate deposit amount",
+ );
+ contributions.set(
+ coin.exchangeBaseUrl,
+ Amounts.add(
+ contributions.get(coin.exchangeBaseUrl) ??
+ Amounts.zeroOfCurrency(currency),
+ coin.contribution,
+ ).amount,
+ );
+ coinFees.push(denom.feeDeposit);
+ refreshRequests.push({
+ refreshedDenom: denom,
+ amountLeft: Amounts.sub(denom.value, coin.contribution).amount,
+ });
+ }
+ const refreshCosts = await getTotalRefreshCosts(wex, tx, refreshRequests);
+ const exchanges: ReadyExchangeSummary[] = [];
+ const wireFees: AmountString[] = [];
+ const now = AbsoluteTime.now();
+ for (const url of contributions.keys()) {
+ const entry = await tx.getExchange(url);
+ const exchange = entry && (await loadReadyExchangeSummary(tx, entry));
+ const fee = exchange?.wireInfo.feesForType[wireType]?.find((period) =>
+ AbsoluteTime.isBetween(
+ now,
+ AbsoluteTime.fromProtocolTimestamp(period.startStamp),
+ AbsoluteTime.fromProtocolTimestamp(period.endStamp),
+ ),
+ );
+ if (!exchange || !fee) {
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_NO_SUITABLE_EXCHANGE,
+ { currency, wireMethod: wireType },
+ "no current wire fee for the selected exchange",
+ );
}
- });
- const res = Amounts.sub(Amounts.sum(amt).amount, Amounts.sum(fees).amount);
- if (res.saturated) {
+ exchanges.push(exchange);
+ wireFees.push(fee.wireFee);
+ }
+ const total = Amounts.sumOrZero(currency, [...contributions.values()]).amount;
+ const fees = {
+ coin: Amounts.stringify(Amounts.sumOrZero(currency, coinFees).amount),
+ wire: Amounts.stringify(Amounts.sumOrZero(currency, wireFees).amount),
+ refresh: Amounts.stringify(
+ Amounts.sumOrZero(currency, refreshCosts).amount,
+ ),
+ };
+ const effective = Amounts.sub(total, fees.coin, fees.wire);
+ if (effective.saturated) {
throw Error(
"can't calculate deposit amount, the fees exceed the deposited value",
);
}
- return res.amount;
-}
-
-/**
- * Get the fee amount that will be charged when trying to deposit the
- * specified amount using the selected coins and the wire method.
- */
-async function getTotalFeesForDepositAmount(
- wex: WalletExecutionContext,
- wireType: string,
- total: AmountJson,
- pcs: SelectedProspectiveCoin[],
-): Promise<DepositGroupFees> {
- const wireFee: AmountJson[] = [];
- const coinFee: AmountJson[] = [];
- const refreshFee: AmountJson[] = [];
- const exchangeSet: Set<string> = new Set();
-
- await wex.runWalletDbTx(async (tx) => {
- const denoms = await getDenomInfos(wex, tx, pcs);
- const refreshRequests = [];
- for (let i = 0; i < pcs.length; i++) {
- const denom = denoms.get(denomRefKey(pcs[i]));
- if (!denom) {
- throw Error("can't find denomination to calculate deposit amount");
- }
- coinFee.push(Amounts.parseOrThrow(denom.feeDeposit));
- exchangeSet.add(pcs[i].exchangeBaseUrl);
- const amountLeft = Amounts.sub(denom.value, pcs[i].contribution).amount;
- refreshRequests.push({ refreshedDenom: denom, amountLeft });
- }
- refreshFee.push(...(await getTotalRefreshCosts(wex, tx, refreshRequests)));
-
- for (const exchangeUrl of exchangeSet.values()) {
- const exchangeDetails = await getExchangeDetailsInTx(tx, exchangeUrl);
- if (!exchangeDetails) {
- continue;
- }
- const fee = exchangeDetails.wireInfo.feesForType[wireType]?.find((x) => {
- return AbsoluteTime.isBetween(
- AbsoluteTime.now(),
- AbsoluteTime.fromProtocolTimestamp(x.startStamp),
- AbsoluteTime.fromProtocolTimestamp(x.endStamp),
- );
- })?.wireFee;
- if (fee) {
- wireFee.push(Amounts.parseOrThrow(fee));
- }
- }
- });
-
- return {
- coin: Amounts.stringify(Amounts.sumOrZero(total.currency, coinFee).amount),
- wire: Amounts.stringify(Amounts.sumOrZero(total.currency, wireFee).amount),
- refresh: Amounts.stringify(
- Amounts.sumOrZero(total.currency, refreshFee).amount,
+ const quote: CheckDepositResponse = {
+ totalDepositCost: Amounts.stringify(
+ Amounts.add(total, fees.refresh).amount,
),
+ effectiveDepositAmount: Amounts.stringify(effective.amount),
+ fees,
+ ...getDepositLimitInfo(exchanges, effective.amount),
};
+ return { quote, exchanges, contributions };
}
diff --git a/packages/taler-wallet-core/src/wallet-api-types.ts b/packages/taler-wallet-core/src/wallet-api-types.ts
@@ -2038,6 +2038,7 @@ export const walletApiExpectedErrors = {
TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE,
],
[WalletApiOperation.CreateDepositGroup]: [
+ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
TalerErrorCode.GENERIC_PAYTO_URI_MALFORMED,
TalerErrorCode.WALLET_NO_SUITABLE_EXCHANGE,
TalerErrorCode.WALLET_DEPOSIT_GROUP_INSUFFICIENT_BALANCE,