aboutsummaryrefslogtreecommitdiff
path: root/src/operations/balance.ts
blob: d12fbaf7c9f7a3f9115432a6d00d317ff2f8bc47 (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
/*
 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/>
 */

/**
 * Imports.
 */
import { WalletBalance, WalletBalanceEntry } from "../types/walletTypes";
import { Database } from "../util/query";
import { InternalWalletState } from "./state";
import { Stores, TipRecord, CoinStatus } from "../types/dbTypes";
import * as Amounts from "../util/amounts";
import { AmountJson } from "../util/amounts";
import { Logger } from "../util/logging";

const logger = new Logger("withdraw.ts");

/**
 * Get detailed balance information, sliced by exchange and by currency.
 */
export async function getBalances(
  ws: InternalWalletState,
): Promise<WalletBalance> {
  logger.trace("starting to compute balance");
  /**
   * Add amount to a balance field, both for
   * the slicing by exchange and currency.
   */
  function addTo(
    balance: WalletBalance,
    field: keyof WalletBalanceEntry,
    amount: AmountJson,
    exchange: string,
  ): void {
    const z = Amounts.getZero(amount.currency);
    const balanceIdentity = {
      available: z,
      paybackAmount: z,
      pendingIncoming: z,
      pendingPayment: z,
      pendingIncomingDirty: z,
      pendingIncomingRefresh: z,
      pendingIncomingWithdraw: z,
    };
    let entryCurr = balance.byCurrency[amount.currency];
    if (!entryCurr) {
      balance.byCurrency[amount.currency] = entryCurr = {
        ...balanceIdentity,
      };
    }
    let entryEx = balance.byExchange[exchange];
    if (!entryEx) {
      balance.byExchange[exchange] = entryEx = { ...balanceIdentity };
    }
    entryCurr[field] = Amounts.add(entryCurr[field], amount).amount;
    entryEx[field] = Amounts.add(entryEx[field], amount).amount;
  }

  const balanceStore = {
    byCurrency: {},
    byExchange: {},
  };

  await ws.db.runWithReadTransaction(
    [Stores.coins, Stores.refreshGroups, Stores.reserves, Stores.purchases, Stores.withdrawalSession],
    async tx => {
      await tx.iter(Stores.coins).forEach(c => {
        if (c.suspended) {
          return;
        }
        if (c.status === CoinStatus.Fresh) {
          addTo(balanceStore, "available", c.currentAmount, c.exchangeBaseUrl);
        }
      });
      await tx.iter(Stores.refreshGroups).forEach(r => {
        // Don't count finished refreshes, since the refresh already resulted
        // in coins being added to the wallet.
        if (r.timestampFinished) {
          return;
        }
        for (let i = 0; i < r.oldCoinPubs.length; i++) {
          const session = r.refreshSessionPerCoin[i];
          if (session) {
            addTo(
              balanceStore,
              "pendingIncoming",
              session.amountRefreshOutput,
              session.exchangeBaseUrl,
            );
            addTo(
              balanceStore,
              "pendingIncomingRefresh",
              session.amountRefreshOutput,
              session.exchangeBaseUrl,
            );
          }
        }
      });

      await tx.iter(Stores.withdrawalSession).forEach(wds => {
        let w = wds.totalCoinValue;
        for (let i = 0; i < wds.planchets.length; i++) {
          if (wds.withdrawn[i]) {
            const p = wds.planchets[i];
            if (p) {
              w = Amounts.sub(w, p.coinValue).amount;
            }
          }
        }
        addTo(
          balanceStore,
          "pendingIncoming",
          w,
          wds.exchangeBaseUrl,
        );
      });

      await tx.iter(Stores.purchases).forEach(t => {
        if (t.timestampFirstSuccessfulPay) {
          return;
        }
        for (const c of t.payReq.coins) {
          addTo(
            balanceStore,
            "pendingPayment",
            Amounts.parseOrThrow(c.contribution),
            c.exchange_url,
          );
        }
      });
    },
  );

  logger.trace("computed balances:", balanceStore);
  return balanceStore;
}