aboutsummaryrefslogtreecommitdiff
path: root/packages/taler-wallet-core/src/balance.ts
blob: 20eb71a7fe8f47ef286e4843b5e95f321b2a5f9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
/*
 This file is part of GNU Taler
 (C) 2019 GNUnet e.V.

 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/>
 */

/**
 * Functions to compute the wallet's balance.
 *
 * There are multiple definition of the wallet's balance.
 * We use the following terminology:
 *
 * - "available": Balance that is available
 *   for spending from transactions in their final state and
 *   expected to be available from pending refreshes.
 *
 * - "pending-incoming": Expected (positive!) delta
 *   to the available balance that we expect to have
 *   after pending operations reach the "done" state.
 *
 * - "pending-outgoing": Amount that is currently allocated
 *   to be spent, but the spend operation could still be aborted
 *   and part of the pending-outgoing amount could be recovered.
 *
 * - "material": Balance that the wallet believes it could spend *right now*,
 *   without waiting for any operations to complete.
 *   This balance type is important when showing "insufficient balance" error messages.
 *
 * - "age-acceptable": Subset of the material balance that can be spent
 *   with age restrictions applied.
 *
 * - "merchant-acceptable": Subset of the material balance that can be spent with a particular
 *   merchant (restricted via min age, exchange, auditor, wire_method).
 *
 * - "merchant-depositable": Subset of the merchant-acceptable balance that the merchant
 *   can accept via their supported wire methods.
 */

/**
 * Imports.
 */
import { GlobalIDB } from "@gnu-taler/idb-bridge";
import {
  AmountJson,
  AmountLike,
  Amounts,
  assertUnreachable,
  BalanceFlag,
  BalancesResponse,
  checkDbInvariant,
  GetBalanceDetailRequest,
  j2s,
  Logger,
  parsePaytoUri,
  ScopeInfo,
  ScopeType,
} from "@gnu-taler/taler-util";
import { ExchangeRestrictionSpec, findMatchingWire } from "./coinSelection.js";
import {
  DepositOperationStatus,
  ExchangeEntryDbRecordStatus,
  OPERATION_STATUS_NONFINAL_FIRST,
  OPERATION_STATUS_NONFINAL_LAST,
  PeerPushDebitStatus,
  RefreshGroupRecord,
  RefreshOperationStatus,
  WalletDbReadOnlyTransaction,
  WithdrawalGroupStatus,
} from "./db.js";
import {
  getExchangeScopeInfo,
  getExchangeWireDetailsInTx,
} from "./exchanges.js";
import { getDenomInfo, WalletExecutionContext } from "./wallet.js";

/**
 * Logger.
 */
const logger = new Logger("operations/balance.ts");

interface WalletBalance {
  scopeInfo: ScopeInfo;
  available: AmountJson;
  pendingIncoming: AmountJson;
  pendingOutgoing: AmountJson;
  flagIncomingKyc: boolean;
  flagIncomingConfirmation: boolean;
  flagOutgoingKyc: boolean;
}

/**
 * Compute the available amount that the wallet expects to get
 * out of a refresh group.
 */
function computeRefreshGroupAvailableAmount(r: RefreshGroupRecord): AmountJson {
  // Don't count finished refreshes, since the refresh already resulted
  // in coins being added to the wallet.
  let available = Amounts.zeroOfCurrency(r.currency);
  if (r.timestampFinished) {
    return available;
  }
  for (let i = 0; i < r.oldCoinPubs.length; i++) {
    available = Amounts.add(available, r.expectedOutputPerCoin[i]).amount;
  }
  return available;
}

function getBalanceKey(scopeInfo: ScopeInfo): string {
  switch (scopeInfo.type) {
    case ScopeType.Auditor:
      return `${scopeInfo.type};${scopeInfo.currency};${scopeInfo.url}`;
    case ScopeType.Exchange:
      return `${scopeInfo.type};${scopeInfo.currency};${scopeInfo.url}`;
    case ScopeType.Global:
      return `${scopeInfo.type};${scopeInfo.currency}`;
  }
}

class BalancesStore {
  private exchangeScopeCache: Record<string, ScopeInfo> = {};
  private balanceStore: Record<string, WalletBalance> = {};

  constructor(
    private wex: WalletExecutionContext,
    private tx: WalletDbReadOnlyTransaction<
      [
        "globalCurrencyAuditors",
        "globalCurrencyExchanges",
        "exchanges",
        "exchangeDetails",
      ]
    >,
  ) {}

  /**
   * Add amount to a balance field, both for
   * the slicing by exchange and currency.
   */
  private async initBalance(
    currency: string,
    exchangeBaseUrl: string,
  ): Promise<WalletBalance> {
    let scopeInfo: ScopeInfo | undefined =
      this.exchangeScopeCache[exchangeBaseUrl];
    if (!scopeInfo) {
      scopeInfo = await getExchangeScopeInfo(
        this.tx,
        exchangeBaseUrl,
        currency,
      );
      this.exchangeScopeCache[exchangeBaseUrl] = scopeInfo;
    }
    const balanceKey = getBalanceKey(scopeInfo);
    const b = this.balanceStore[balanceKey];
    if (!b) {
      const zero = Amounts.zeroOfCurrency(currency);
      this.balanceStore[balanceKey] = {
        scopeInfo,
        available: zero,
        pendingIncoming: zero,
        pendingOutgoing: zero,
        flagIncomingConfirmation: false,
        flagIncomingKyc: false,
        flagOutgoingKyc: false,
      };
    }
    return this.balanceStore[balanceKey];
  }

  async addZero(currency: string, exchangeBaseUrl: string): Promise<void> {
    await this.initBalance(currency, exchangeBaseUrl);
  }

  async addAvailable(
    currency: string,
    exchangeBaseUrl: string,
    amount: AmountLike,
  ): Promise<void> {
    const b = await this.initBalance(currency, exchangeBaseUrl);
    b.available = Amounts.add(b.available, amount).amount;
  }

  async addPendingIncoming(
    currency: string,
    exchangeBaseUrl: string,
    amount: AmountLike,
  ): Promise<void> {
    const b = await this.initBalance(currency, exchangeBaseUrl);
    b.pendingIncoming = Amounts.add(b.pendingIncoming, amount).amount;
  }

  async addPendingOutgoing(
    currency: string,
    exchangeBaseUrl: string,
    amount: AmountLike,
  ): Promise<void> {
    const b = await this.initBalance(currency, exchangeBaseUrl);
    b.pendingOutgoing = Amounts.add(b.pendingOutgoing, amount).amount;
  }

  async setFlagIncomingKyc(
    currency: string,
    exchangeBaseUrl: string,
  ): Promise<void> {
    const b = await this.initBalance(currency, exchangeBaseUrl);
    b.flagIncomingKyc = true;
  }

  async setFlagIncomingConfirmation(
    currency: string,
    exchangeBaseUrl: string,
  ): Promise<void> {
    const b = await this.initBalance(currency, exchangeBaseUrl);
    b.flagIncomingConfirmation = true;
  }

  async setFlagOutgoingKyc(
    currency: string,
    exchangeBaseUrl: string,
  ): Promise<void> {
    const b = await this.initBalance(currency, exchangeBaseUrl);
    b.flagOutgoingKyc = true;
  }

  toBalancesResponse(): BalancesResponse {
    const balancesResponse: BalancesResponse = {
      balances: [],
    };

    const balanceStore = this.balanceStore;

    Object.keys(balanceStore)
      .sort()
      .forEach((c) => {
        const v = balanceStore[c];
        const flags: BalanceFlag[] = [];
        if (v.flagIncomingKyc) {
          flags.push(BalanceFlag.IncomingKyc);
        }
        if (v.flagIncomingConfirmation) {
          flags.push(BalanceFlag.IncomingConfirmation);
        }
        if (v.flagOutgoingKyc) {
          flags.push(BalanceFlag.OutgoingKyc);
        }
        balancesResponse.balances.push({
          scopeInfo: v.scopeInfo,
          available: Amounts.stringify(v.available),
          pendingIncoming: Amounts.stringify(v.pendingIncoming),
          pendingOutgoing: Amounts.stringify(v.pendingOutgoing),
          // FIXME: This field is basically not implemented, do we even need it?
          hasPendingTransactions: false,
          // FIXME: This field is basically not implemented, do we even need it?
          requiresUserInput: false,
          flags,
        });
      });
    return balancesResponse;
  }
}

/**
 * Get balance information.
 */
export async function getBalancesInsideTransaction(
  wex: WalletExecutionContext,
  tx: WalletDbReadOnlyTransaction<
    [
      "exchanges",
      "exchangeDetails",
      "coinAvailability",
      "refreshGroups",
      "depositGroups",
      "withdrawalGroups",
      "globalCurrencyAuditors",
      "globalCurrencyExchanges",
      "peerPushDebit",
    ]
  >,
): Promise<BalancesResponse> {
  const balanceStore: BalancesStore = new BalancesStore(wex, tx);

  const keyRangeActive = GlobalIDB.KeyRange.bound(
    OPERATION_STATUS_NONFINAL_FIRST,
    OPERATION_STATUS_NONFINAL_LAST,
  );

  await tx.exchanges.iter().forEachAsync(async (ex) => {
    if (
      ex.entryStatus === ExchangeEntryDbRecordStatus.Used ||
      ex.tosAcceptedTimestamp != null
    ) {
      const det = await getExchangeWireDetailsInTx(tx, ex.baseUrl);
      if (det) {
        await balanceStore.addZero(det.currency, ex.baseUrl);
      }
    }
  });

  await tx.coinAvailability.iter().forEachAsync(async (ca) => {
    const count = ca.visibleCoinCount ?? 0;
    await balanceStore.addZero(ca.currency, ca.exchangeBaseUrl);
    for (let i = 0; i < count; i++) {
      await balanceStore.addAvailable(
        ca.currency,
        ca.exchangeBaseUrl,
        ca.value,
      );
    }
  });

  await tx.refreshGroups.iter().forEachAsync(async (r) => {
    switch (r.operationStatus) {
      case RefreshOperationStatus.Pending:
      case RefreshOperationStatus.Suspended:
        break;
      default:
        return;
    }
    const perExchange = r.infoPerExchange;
    if (!perExchange) {
      return;
    }
    for (const [e, x] of Object.entries(perExchange)) {
      await balanceStore.addAvailable(r.currency, e, x.outputEffective);
    }
  });

  await tx.withdrawalGroups.indexes.byStatus
    .iter(keyRangeActive)
    .forEachAsync(async (wg) => {
      switch (wg.status) {
        case WithdrawalGroupStatus.AbortedBank:
        case WithdrawalGroupStatus.AbortedExchange:
        case WithdrawalGroupStatus.FailedAbortingBank:
        case WithdrawalGroupStatus.FailedBankAborted:
        case WithdrawalGroupStatus.AbortedOtherWallet:
        case WithdrawalGroupStatus.AbortedUserRefused:
        case WithdrawalGroupStatus.DialogProposed:
        case WithdrawalGroupStatus.Done:
          // Does not count as pendingIncoming
          return;
        case WithdrawalGroupStatus.PendingReady:
        case WithdrawalGroupStatus.AbortingBank:
        case WithdrawalGroupStatus.PendingQueryingStatus:
        case WithdrawalGroupStatus.SuspendedWaitConfirmBank:
        case WithdrawalGroupStatus.SuspendedReady:
        case WithdrawalGroupStatus.SuspendedRegisteringBank:
        case WithdrawalGroupStatus.SuspendedAbortingBank:
        case WithdrawalGroupStatus.SuspendedQueryingStatus:
          // Pending, but no special flag.
          break;
        case WithdrawalGroupStatus.PendingBalanceKyc:
        case WithdrawalGroupStatus.SuspendedBalanceKyc:
        case WithdrawalGroupStatus.SuspendedKyc:
        case WithdrawalGroupStatus.PendingBalanceKycInit:
        case WithdrawalGroupStatus.SuspendedBalanceKycInit:
        case WithdrawalGroupStatus.PendingKyc: {
          checkDbInvariant(
            wg.denomsSel !== undefined,
            "wg in kyc state should have been initialized",
          );
          checkDbInvariant(
            wg.exchangeBaseUrl !== undefined,
            "wg in kyc state should have been initialized",
          );
          const currency = Amounts.currencyOf(wg.denomsSel.totalCoinValue);
          await balanceStore.setFlagIncomingKyc(currency, wg.exchangeBaseUrl);
          break;
        }
        case WithdrawalGroupStatus.PendingRegisteringBank: {
          if (wg.denomsSel && wg.exchangeBaseUrl) {
            const currency = Amounts.currencyOf(wg.denomsSel.totalCoinValue);
            await balanceStore.setFlagIncomingConfirmation(
              currency,
              wg.exchangeBaseUrl,
            );
          }
          break;
        }
        case WithdrawalGroupStatus.PendingWaitConfirmBank: {
          checkDbInvariant(
            wg.denomsSel !== undefined,
            "wg in confirmed state should have been initialized",
          );
          checkDbInvariant(
            wg.exchangeBaseUrl !== undefined,
            "wg in kyc state should have been initialized",
          );
          const currency = Amounts.currencyOf(wg.denomsSel.totalCoinValue);
          await balanceStore.setFlagIncomingConfirmation(
            currency,
            wg.exchangeBaseUrl,
          );
          break;
        }
        default:
          assertUnreachable(wg.status);
      }
      if (wg.denomsSel && wg.exchangeBaseUrl) {
        // only inform pending incoming if amount and exchange has been selected
        const currency = Amounts.currencyOf(wg.denomsSel.totalCoinValue);
        await balanceStore.addPendingIncoming(
          currency,
          wg.exchangeBaseUrl,
          wg.denomsSel.totalCoinValue,
        );
      }
    });

  await tx.peerPushDebit.indexes.byStatus
    .iter(keyRangeActive)
    .forEachAsync(async (ppdRecord) => {
      switch (ppdRecord.status) {
        case PeerPushDebitStatus.AbortingDeletePurse:
        case PeerPushDebitStatus.SuspendedAbortingDeletePurse:
        case PeerPushDebitStatus.PendingReady:
        case PeerPushDebitStatus.SuspendedReady:
        case PeerPushDebitStatus.PendingCreatePurse:
        case PeerPushDebitStatus.SuspendedCreatePurse: {
          const currency = Amounts.currencyOf(ppdRecord.amount);
          await balanceStore.addPendingOutgoing(
            currency,
            ppdRecord.exchangeBaseUrl,
            ppdRecord.totalCost,
          );
          break;
        }
      }
    });

  await tx.depositGroups.indexes.byStatus
    .iter(keyRangeActive)
    .forEachAsync(async (dgRecord) => {
      const perExchange = dgRecord.infoPerExchange;
      if (!perExchange) {
        return;
      }
      for (const [e, x] of Object.entries(perExchange)) {
        const currency = Amounts.currencyOf(dgRecord.amount);
        switch (dgRecord.operationStatus) {
          case DepositOperationStatus.SuspendedAggregateKyc:
          case DepositOperationStatus.PendingAggregateKyc:
            await balanceStore.setFlagOutgoingKyc(currency, e);
        }
        switch (dgRecord.operationStatus) {
          case DepositOperationStatus.SuspendedAggregateKyc:
          case DepositOperationStatus.PendingAggregateKyc:
          case DepositOperationStatus.PendingTrack:
          case DepositOperationStatus.SuspendedAborting:
          case DepositOperationStatus.SuspendedDeposit:
          case DepositOperationStatus.SuspendedTrack:
          case DepositOperationStatus.PendingDeposit: {
            const perExchange = dgRecord.infoPerExchange;
            if (perExchange) {
              for (const [e, v] of Object.entries(perExchange)) {
                await balanceStore.addPendingOutgoing(
                  currency,
                  e,
                  v.amountEffective,
                );
              }
            }
          }
        }
      }
    });

  return balanceStore.toBalancesResponse();
}

/**
 * Get detailed balance information, sliced by exchange and by currency.
 */
export async function getBalances(
  wex: WalletExecutionContext,
): Promise<BalancesResponse> {
  logger.trace("starting to compute balance");

  const wbal = await wex.db.runReadWriteTx(
    {
      storeNames: [
        "coinAvailability",
        "coins",
        "depositGroups",
        "exchangeDetails",
        "exchanges",
        "globalCurrencyAuditors",
        "globalCurrencyExchanges",
        "purchases",
        "refreshGroups",
        "withdrawalGroups",
        "peerPushDebit",
      ],
    },
    async (tx) => {
      return getBalancesInsideTransaction(wex, tx);
    },
  );

  logger.trace("finished computing wallet balance");

  return wbal;
}

export interface PaymentRestrictionsForBalance {
  currency: string;
  minAge: number;
  restrictExchanges: ExchangeRestrictionSpec | undefined;
  restrictWireMethods: string[] | undefined;
  depositPaytoUri: string | undefined;
}

export interface AcceptableExchanges {
  /**
   * Exchanges accepted by the merchant, but wire method might not match.
   */
  acceptableExchanges: string[];

  /**
   * Exchanges accepted by the merchant, including a matching
   * wire method, i.e. the merchant can deposit coins there.
   */
  depositableExchanges: string[];
}

export interface PaymentBalanceDetails {
  /**
   * Balance of type "available" (see balance.ts for definition).
   */
  balanceAvailable: AmountJson;

  /**
   * Balance of type "material" (see balance.ts for definition).
   */
  balanceMaterial: AmountJson;

  /**
   * Balance of type "age-acceptable" (see balance.ts for definition).
   */
  balanceAgeAcceptable: AmountJson;

  /**
   * Balance of type "receiver-acceptable" (see balance.ts for definition).
   */
  balanceReceiverAcceptable: AmountJson;

  /**
   * Balance of type "receiver-depositable" (see balance.ts for definition).
   */
  balanceReceiverDepositable: AmountJson;

  /**
   * Balance that's depositable with the exchange.
   * This balance is reduced by the exchange's debit restrictions
   * and wire fee configuration.
   */
  balanceExchangeDepositable: AmountJson;

  /**
   * Estimated maximum amount that the wallet could pay for, under the assumption
   * that the merchant pays absolutely no fees.
   */
  maxMerchantEffectiveDepositAmount: AmountJson;
}

export async function getPaymentBalanceDetails(
  wex: WalletExecutionContext,
  req: PaymentRestrictionsForBalance,
): Promise<PaymentBalanceDetails> {
  return await wex.db.runReadOnlyTx(
    {
      storeNames: [
        "coinAvailability",
        "refreshGroups",
        "exchanges",
        "exchangeDetails",
        "denominations",
      ],
    },
    async (tx) => {
      return getPaymentBalanceDetailsInTx(wex, tx, req);
    },
  );
}

export async function getPaymentBalanceDetailsInTx(
  wex: WalletExecutionContext,
  tx: WalletDbReadOnlyTransaction<
    [
      "coinAvailability",
      "refreshGroups",
      "exchanges",
      "exchangeDetails",
      "denominations",
    ]
  >,
  req: PaymentRestrictionsForBalance,
): Promise<PaymentBalanceDetails> {
  const d: PaymentBalanceDetails = {
    balanceAvailable: Amounts.zeroOfCurrency(req.currency),
    balanceMaterial: Amounts.zeroOfCurrency(req.currency),
    balanceAgeAcceptable: Amounts.zeroOfCurrency(req.currency),
    balanceReceiverAcceptable: Amounts.zeroOfCurrency(req.currency),
    balanceReceiverDepositable: Amounts.zeroOfCurrency(req.currency),
    maxMerchantEffectiveDepositAmount: Amounts.zeroOfCurrency(req.currency),
    balanceExchangeDepositable: Amounts.zeroOfCurrency(req.currency),
  };

  logger.info(`computing balance details for ${j2s(req)}`);

  const availableCoins = await tx.coinAvailability.getAll();

  for (const ca of availableCoins) {
    if (ca.currency != req.currency) {
      continue;
    }

    const denom = await getDenomInfo(
      wex,
      tx,
      ca.exchangeBaseUrl,
      ca.denomPubHash,
    );
    if (!denom) {
      continue;
    }

    const wireDetails = await getExchangeWireDetailsInTx(
      tx,
      ca.exchangeBaseUrl,
    );
    if (!wireDetails) {
      continue;
    }

    const singleCoinAmount: AmountJson = Amounts.parseOrThrow(ca.value);
    const coinAmount: AmountJson = Amounts.mult(
      singleCoinAmount,
      ca.freshCoinCount,
    ).amount;

    let wireOkay = false;
    if (req.restrictWireMethods == null) {
      wireOkay = true;
    } else {
      for (const wm of req.restrictWireMethods) {
        const wmf = findMatchingWire(wm, req.depositPaytoUri, wireDetails);
        if (wmf) {
          wireOkay = true;
          break;
        }
      }
    }

    if (wireOkay) {
      d.balanceExchangeDepositable = Amounts.add(
        d.balanceExchangeDepositable,
        coinAmount,
      ).amount;
    }

    let ageOkay = ca.maxAge === 0 || ca.maxAge > req.minAge;

    let merchantExchangeAcceptable = false;

    if (!req.restrictExchanges) {
      merchantExchangeAcceptable = true;
    } else {
      for (const ex of req.restrictExchanges.exchanges) {
        if (ex.exchangeBaseUrl === ca.exchangeBaseUrl) {
          merchantExchangeAcceptable = true;
          break;
        }
      }
      for (const acceptedAuditor of req.restrictExchanges.auditors) {
        for (const exchangeAuditor of wireDetails.auditors) {
          if (acceptedAuditor.auditorBaseUrl === exchangeAuditor.auditor_url) {
            merchantExchangeAcceptable = true;
            break;
          }
        }
      }
    }

    const merchantExchangeDepositable = merchantExchangeAcceptable && wireOkay;

    d.balanceAvailable = Amounts.add(d.balanceAvailable, coinAmount).amount;
    d.balanceMaterial = Amounts.add(d.balanceMaterial, coinAmount).amount;
    if (ageOkay) {
      d.balanceAgeAcceptable = Amounts.add(
        d.balanceAgeAcceptable,
        coinAmount,
      ).amount;
      if (merchantExchangeAcceptable) {
        d.balanceReceiverAcceptable = Amounts.add(
          d.balanceReceiverAcceptable,
          coinAmount,
        ).amount;
        if (merchantExchangeDepositable) {
          d.balanceReceiverDepositable = Amounts.add(
            d.balanceReceiverDepositable,
            coinAmount,
          ).amount;
        }
      }
    }

    if (
      ageOkay &&
      wireOkay &&
      merchantExchangeAcceptable &&
      merchantExchangeDepositable
    ) {
      d.maxMerchantEffectiveDepositAmount = Amounts.add(
        d.maxMerchantEffectiveDepositAmount,
        Amounts.mult(ca.value, ca.freshCoinCount).amount,
      ).amount;

      d.maxMerchantEffectiveDepositAmount = Amounts.sub(
        d.maxMerchantEffectiveDepositAmount,
        Amounts.mult(denom.feeDeposit, ca.freshCoinCount).amount,
      ).amount;
    }
  }

  await tx.refreshGroups.iter().forEach((r) => {
    if (r.currency != req.currency) {
      return;
    }
    d.balanceAvailable = Amounts.add(
      d.balanceAvailable,
      computeRefreshGroupAvailableAmount(r),
    ).amount;
  });

  return d;
}

export async function getBalanceDetail(
  wex: WalletExecutionContext,
  req: GetBalanceDetailRequest,
): Promise<PaymentBalanceDetails> {
  const exchanges: { exchangeBaseUrl: string; exchangePub: string }[] = [];
  const wires = new Array<string>();
  await wex.db.runReadOnlyTx(
    { storeNames: ["exchanges", "exchangeDetails"] },
    async (tx) => {
      const allExchanges = await tx.exchanges.iter().toArray();
      for (const e of allExchanges) {
        const details = await getExchangeWireDetailsInTx(tx, e.baseUrl);
        if (!details || req.currency !== details.currency) {
          continue;
        }
        details.wireInfo.accounts.forEach((a) => {
          const payto = parsePaytoUri(a.payto_uri);
          if (payto && !wires.includes(payto.targetType)) {
            wires.push(payto.targetType);
          }
        });
        exchanges.push({
          exchangePub: details.masterPublicKey,
          exchangeBaseUrl: e.baseUrl,
        });
      }
    },
  );

  return await getPaymentBalanceDetails(wex, {
    currency: req.currency,
    restrictExchanges: {
      auditors: [],
      exchanges,
    },
    restrictWireMethods: wires,
    minAge: 0,
    depositPaytoUri: undefined,
  });
}