@otoplo/wallet-common 0.5.2 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/index.d.ts +889 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +259 -195
  4. package/dist/index.js.map +1 -1
  5. package/package.json +8 -9
  6. package/src/services/rostrum.ts +42 -22
  7. package/src/services/wallet.ts +758 -694
  8. package/dist/types/index.d.ts +0 -5
  9. package/dist/types/index.d.ts.map +0 -1
  10. package/dist/types/persistence/index.d.ts +0 -3
  11. package/dist/types/persistence/index.d.ts.map +0 -1
  12. package/dist/types/persistence/repository.d.ts +0 -43
  13. package/dist/types/persistence/repository.d.ts.map +0 -1
  14. package/dist/types/persistence/wallet-db.d.ts +0 -44
  15. package/dist/types/persistence/wallet-db.d.ts.map +0 -1
  16. package/dist/types/services/asset.d.ts +0 -21
  17. package/dist/types/services/asset.d.ts.map +0 -1
  18. package/dist/types/services/cache.d.ts +0 -14
  19. package/dist/types/services/cache.d.ts.map +0 -1
  20. package/dist/types/services/discovery.d.ts +0 -18
  21. package/dist/types/services/discovery.d.ts.map +0 -1
  22. package/dist/types/services/index.d.ts +0 -10
  23. package/dist/types/services/index.d.ts.map +0 -1
  24. package/dist/types/services/key.d.ts +0 -17
  25. package/dist/types/services/key.d.ts.map +0 -1
  26. package/dist/types/services/market.d.ts +0 -33
  27. package/dist/types/services/market.d.ts.map +0 -1
  28. package/dist/types/services/rostrum.d.ts +0 -39
  29. package/dist/types/services/rostrum.d.ts.map +0 -1
  30. package/dist/types/services/session.d.ts +0 -48
  31. package/dist/types/services/session.d.ts.map +0 -1
  32. package/dist/types/services/transaction.d.ts +0 -41
  33. package/dist/types/services/transaction.d.ts.map +0 -1
  34. package/dist/types/services/tx-transformer.d.ts +0 -22
  35. package/dist/types/services/tx-transformer.d.ts.map +0 -1
  36. package/dist/types/services/wallet.d.ts +0 -107
  37. package/dist/types/services/wallet.d.ts.map +0 -1
  38. package/dist/types/types/dapp.types.d.ts +0 -19
  39. package/dist/types/types/dapp.types.d.ts.map +0 -1
  40. package/dist/types/types/db.types.d.ts +0 -138
  41. package/dist/types/types/db.types.d.ts.map +0 -1
  42. package/dist/types/types/index.d.ts +0 -6
  43. package/dist/types/types/index.d.ts.map +0 -1
  44. package/dist/types/types/notification.types.d.ts +0 -21
  45. package/dist/types/types/notification.types.d.ts.map +0 -1
  46. package/dist/types/types/rostrum.types.d.ts +0 -132
  47. package/dist/types/types/rostrum.types.d.ts.map +0 -1
  48. package/dist/types/types/wallet.types.d.ts +0 -80
  49. package/dist/types/types/wallet.types.d.ts.map +0 -1
  50. package/dist/types/utils/asset.d.ts +0 -5
  51. package/dist/types/utils/asset.d.ts.map +0 -1
  52. package/dist/types/utils/common.d.ts +0 -64
  53. package/dist/types/utils/common.d.ts.map +0 -1
  54. package/dist/types/utils/enums.d.ts +0 -16
  55. package/dist/types/utils/enums.d.ts.map +0 -1
  56. package/dist/types/utils/index.d.ts +0 -7
  57. package/dist/types/utils/index.d.ts.map +0 -1
  58. package/dist/types/utils/keypath.d.ts +0 -5
  59. package/dist/types/utils/keypath.d.ts.map +0 -1
  60. package/dist/types/utils/seed.d.ts +0 -5
  61. package/dist/types/utils/seed.d.ts.map +0 -1
  62. package/dist/types/utils/vault.d.ts +0 -10
  63. package/dist/types/utils/vault.d.ts.map +0 -1
@@ -1,694 +1,758 @@
1
- import type { WalletDB } from "../persistence";
2
- import type { Account, AccountDTO, AddressDTO, AddressKey, Balance, ITXHistory, RostrumParams, VaultDTO, VaultInfo } from "../types";
3
- import { AccountType, HD_WALLET_ID, keyPathToString, KeySpace, sumBalance, sumTokensBalance } from "../utils";
4
- import type { AssetService } from "./asset";
5
- import { WalletDiscoveryService } from "./discovery";
6
- import { KeyManager } from "./key";
7
- import type { RostrumService } from "./rostrum";
8
- import type { SessionManager } from "./session";
9
- import type { TransactionService } from "./transaction";
10
-
11
- type WalletAddress = AccountDTO | AddressDTO | VaultDTO;
12
-
13
- export interface AddressHistory {
14
- address: WalletAddress;
15
- txs: ITXHistory[];
16
- }
17
-
18
- interface UpdateInfo {
19
- address: WalletAddress;
20
- result: string
21
- }
22
-
23
- export type WalletEvent =
24
- | { type: 'new_tip'; tip: number; }
25
- | { type: 'new_account'; account: Account; }
26
- | { type: 'new_vault'; vault: VaultInfo; }
27
- | { type: 'sync_wallet'; loading: boolean; }
28
- | { type: 'clear_wallet'; }
29
- | { type: 'account_balance_updated'; accountId: number; balance: Balance, tokensBalance: Record<string, Balance>; }
30
- | { type: 'vault_balance_updated'; address: string, balance: Balance; }
31
-
32
- export type WalletUpdateCallback = (event: WalletEvent) => void;
33
-
34
- export class WalletManager {
35
-
36
- private static readonly DEBOUNCE_MS = 2000;
37
-
38
- private addressResolvers: Map<string, () => void>;
39
- private discoveryResolver?: () => void;
40
-
41
- public accounts: Map<number, AccountDTO>;
42
- public accountsAddressToId: Map<string, number>;
43
-
44
- public receiveAddresses: AddressDTO[];
45
- public changeAddresses: AddressDTO[];
46
-
47
- public vaults: Map<string, VaultDTO>;
48
-
49
- private pendingUpdates: Map<string, UpdateInfo>;
50
- private updateTimer?: number;
51
-
52
- private updateCallback?: WalletUpdateCallback;
53
-
54
- private isConnected = false;
55
-
56
- private isSubscribed = false;
57
-
58
- private readonly discoveryService: WalletDiscoveryService;
59
-
60
- public constructor(
61
- private readonly keyManager: KeyManager,
62
- private readonly walletDb: WalletDB,
63
- private readonly rostrumService: RostrumService,
64
- private readonly assetService: AssetService,
65
- private readonly transactionService: TransactionService,
66
- private readonly sessionManager: SessionManager,
67
- ) {
68
- this.discoveryService = new WalletDiscoveryService(this.rostrumService, this.keyManager);
69
- this.accounts = new Map();
70
- this.accountsAddressToId = new Map();
71
- this.receiveAddresses = [];
72
- this.changeAddresses = [];
73
- this.vaults = new Map();
74
- this.pendingUpdates = new Map();
75
- this.addressResolvers = new Map();
76
- }
77
-
78
- public clear(): void {
79
- this.accounts.clear();
80
- this.accountsAddressToId.clear();
81
- this.receiveAddresses = [];
82
- this.changeAddresses = [];
83
- this.vaults.clear();
84
- this.pendingUpdates.clear();
85
- this.addressResolvers.clear();
86
- this.notify({ type: 'clear_wallet' });
87
- }
88
-
89
- public onUpdate(callback: WalletUpdateCallback): void {
90
- this.updateCallback = callback;
91
- }
92
-
93
- private notify(event: WalletEvent): void {
94
- this.updateCallback?.(event);
95
- }
96
-
97
- private getAllAddresses(): WalletAddress[] {
98
- return [...this.receiveAddresses, ...this.changeAddresses, ...this.accounts.values(), ...this.vaults.values()];
99
- }
100
-
101
- public getMainAddresses(): AddressDTO[] {
102
- return [...this.receiveAddresses, ...this.changeAddresses];
103
- }
104
-
105
- public getReceiveAddress(accountId = HD_WALLET_ID): string {
106
- if (accountId != HD_WALLET_ID) {
107
- return this.accounts.get(accountId)!.address;
108
- }
109
- return this.receiveAddresses.find(addr => !addr.used)!.address;
110
- }
111
-
112
- public getChangeAddress(accountId = HD_WALLET_ID): string {
113
- if (accountId != HD_WALLET_ID) {
114
- return this.accounts.get(accountId)!.address;
115
- }
116
- return this.changeAddresses.find(addr => !addr.used)!.address;
117
- }
118
-
119
- public getUsedAddressKeys(accountId = HD_WALLET_ID): AddressKey[] {
120
- if (accountId != HD_WALLET_ID) {
121
- const account = this.accounts.get(accountId)!;
122
- return [{
123
- address: account.address,
124
- keyPath: keyPathToString(AccountType.DAPP, 0, account.id),
125
- balance: account.balance,
126
- tokensBalance: account.tokensBalance
127
- }];
128
- }
129
-
130
- return this.getMainAddresses().filter(addr => addr.used).map(addr => ({
131
- address: addr.address,
132
- keyPath: keyPathToString(AccountType.MAIN, addr.space, addr.idx),
133
- balance: addr.balance,
134
- tokensBalance: addr.tokensBalance
135
- }));
136
- }
137
-
138
- public async reloadRostrum(params?: RostrumParams): Promise<void> {
139
- if (params) {
140
- await this.rostrumService.setCurrentInstance(params);
141
- }
142
- await this.disconnectRostrum();
143
- await this.initRostrum();
144
- await this.subscribeAllAddresses();
145
- }
146
-
147
- public async initRostrum(): Promise<void> {
148
- if (this.isConnected) {
149
- return;
150
- }
151
- await this.rostrumService.connect();
152
- await this.rostrumService.subscribeHeaders(tip => this.notify({ type: 'new_tip', tip }));
153
- this.isConnected = true;
154
- }
155
-
156
- public async disconnectRostrum(): Promise<void> {
157
- await this.rostrumService.disconnect(true);
158
- this.isConnected = false;
159
- this.isSubscribed = false;
160
- }
161
-
162
- public async discoverWallet(): Promise<void> {
163
- const rIndexPromise = this.discoveryService.discoverWalletIndex(AccountType.MAIN, KeySpace.RECEIVE);
164
- const cIndexPromise = this.discoveryService.discoverWalletIndex(AccountType.MAIN, KeySpace.CHANGE);
165
- const dappIndexPromise = this.discoveryService.discoverWalletIndex(AccountType.DAPP, KeySpace.RECEIVE);
166
- const vaultsPromise = this.discoveryService.discoverVaults();
167
-
168
- const [rIndex, cIndex, dappIndex, vaults] = await Promise.all([rIndexPromise, cIndexPromise, dappIndexPromise, vaultsPromise]);
169
-
170
- this.receiveAddresses = this.deriveAddresses(KeySpace.RECEIVE, 0, rIndex + KeyManager.GAP_LIMIT + 1);
171
- this.changeAddresses = this.deriveAddresses(KeySpace.CHANGE, 0, cIndex + KeyManager.GAP_LIMIT + 1);
172
- this.accounts = this.deriveAccounts(0, dappIndex < 0 ? 1 : dappIndex + 1);
173
- this.accounts.forEach(entry => this.accountsAddressToId.set(entry.address, entry.id));
174
- this.vaults = vaults;
175
-
176
- await this.saveAddresses(this.receiveAddresses);
177
- await this.saveAddresses(this.changeAddresses);
178
- await this.saveAccounts(this.accounts);
179
- await this.saveVaults(this.vaults);
180
-
181
- this.initState();
182
- }
183
-
184
- public async loadWallet(): Promise<void> {
185
- this.receiveAddresses = await this.walletDb.getReceiveAddresses();
186
- this.changeAddresses = await this.walletDb.getChangeAddresses();
187
-
188
- const accs = await this.walletDb.getAccounts();
189
- this.accounts = new Map(accs.map(a => [a.id, a]));
190
- this.accountsAddressToId = new Map(accs.map(a => [a.address, a.id]));
191
-
192
- const vaults = await this.walletDb.getVaults();
193
- this.vaults = new Map(vaults.map(v => [v.address, v]));
194
-
195
- this.initState();
196
- }
197
-
198
- public initialSync(): Promise<void> {
199
- return this.subscribeAllAddresses(true);
200
- }
201
-
202
- public reconnectSync(): Promise<[void, void]> {
203
- return Promise.all([
204
- this.sessionManager.reload(this.accounts),
205
- this.subscribeAllAddresses()
206
- ]);
207
- }
208
-
209
- private async subscribeAllAddresses(isInit?: boolean): Promise<void> {
210
- if (this.isSubscribed) {
211
- return;
212
- }
213
- this.isSubscribed = true;
214
- await this.subscribeAddresses(this.getAllAddresses(), isInit);
215
- }
216
-
217
- private initState(): void {
218
- const walletAddresses = this.getMainAddresses();
219
-
220
- this.notify({
221
- type: 'new_account',
222
- account: {
223
- id: HD_WALLET_ID,
224
- name: 'HD Wallet',
225
- address: this.getReceiveAddress(),
226
- balance: sumBalance(walletAddresses.map(a => a.balance)),
227
- tokensBalance: sumTokensBalance(walletAddresses.map(a => a.tokensBalance)),
228
- sessions: {}
229
- }
230
- });
231
-
232
- for (const account of this.accounts.values()) {
233
- this.notify({
234
- type: 'new_account',
235
- account: {
236
- id: account.id,
237
- name: account.name,
238
- address: account.address,
239
- balance: account.balance,
240
- tokensBalance: account.tokensBalance,
241
- sessions: {}
242
- }
243
- });
244
- }
245
-
246
- for (const vault of this.vaults.values()) {
247
- this.notify({
248
- type: 'new_vault',
249
- vault: {
250
- address: vault.address,
251
- balance: vault.balance,
252
- block: vault.block,
253
- index: vault.idx
254
- }
255
- });
256
- }
257
- }
258
-
259
- private deriveAddresses(space: KeySpace, startIndex: number, count: number): AddressDTO[] {
260
- const newAddresses: AddressDTO[] = [];
261
- for (let i = startIndex; i < startIndex + count; i++) {
262
- const addressDTO: AddressDTO = {
263
- address: this.keyManager.deriveAddress(AccountType.MAIN, space, i),
264
- space: space,
265
- idx: i,
266
- used: false,
267
- height: 0,
268
- statusHash: '',
269
- balance: { confirmed: "0", unconfirmed: "0" },
270
- tokensBalance: {},
271
- type: AccountType.MAIN
272
- };
273
-
274
- newAddresses.push(addressDTO);
275
- }
276
-
277
- return newAddresses;
278
- }
279
-
280
- private deriveAccounts(startIndex: number, count: number): Map<number, AccountDTO> {
281
- const newAccounts = new Map<number, AccountDTO>();
282
- for (let i = startIndex; i < startIndex + count; i++) {
283
- const account: AccountDTO = {
284
- id: i,
285
- name: `Account ${i + 1}`,
286
- address: this.keyManager.deriveAddress(AccountType.DAPP, KeySpace.RECEIVE, i),
287
- height: 0,
288
- hidden: 0,
289
- statusHash: '',
290
- balance: { confirmed: "0", unconfirmed: "0" },
291
- tokensBalance: {},
292
- type: AccountType.DAPP
293
- };
294
-
295
- newAccounts.set(account.id, account);
296
- }
297
-
298
- return newAccounts;
299
- }
300
-
301
- private async saveAddresses(addresses: AddressDTO[]): Promise<void> {
302
- for (const addr of addresses) {
303
- await this.walletDb.saveAddress(addr);
304
- }
305
- }
306
-
307
- private async saveAccounts(accounts: Map<number, AccountDTO>): Promise<void> {
308
- for (const acc of accounts.values()) {
309
- await this.walletDb.saveAccount(acc);
310
- }
311
- }
312
-
313
- private async saveVaults(vaults: Map<string, VaultDTO>): Promise<void> {
314
- for (const vault of vaults.values()) {
315
- await this.walletDb.saveVault(vault);
316
- }
317
- }
318
-
319
- private async subscribeAddresses(addresses: WalletAddress[], isInit = false): Promise<void> {
320
- const subscriptionPromises = addresses.map(async addr => {
321
- const result = await this.rostrumService.subscribeAddress(addr.address, this.onSubscribeEvent);
322
- return { addr, result };
323
- });
324
-
325
- const initPromises: Promise<void>[] = [];
326
- const subscriptionResults = await Promise.all(subscriptionPromises);
327
-
328
- for (const { addr, result } of subscriptionResults) {
329
- if (result && typeof result === 'string' && addr.statusHash != result) {
330
- if (isInit) {
331
- const p = new Promise<void>((resolve) => {
332
- this.addressResolvers.set(addr.address, resolve);
333
- });
334
- initPromises.push(p);
335
-
336
- if (!this.discoveryResolver) {
337
- const discoveryPromise = new Promise<void>((resolve) => {
338
- this.discoveryResolver = resolve;
339
- });
340
- initPromises.push(discoveryPromise);
341
- }
342
- }
343
- this.registerUpdate({address: addr, result});
344
- }
345
- }
346
-
347
- await Promise.all(initPromises);
348
- }
349
-
350
- private onSubscribeEvent = (data: unknown): void => {
351
- if (!Array.isArray(data) || data.length < 2) {
352
- return;
353
- }
354
-
355
- const [address, hash] = data as [string, string];
356
- const allAddresses = this.getAllAddresses();
357
- const addrDTO = allAddresses.find(a => a.address === address);
358
-
359
- if (addrDTO && addrDTO.statusHash !== hash) {
360
- this.registerUpdate({address: addrDTO, result: hash});
361
- }
362
- }
363
-
364
- private registerUpdate(updateInfo: UpdateInfo): void {
365
- this.pendingUpdates.set(updateInfo.address.address, updateInfo);
366
-
367
- clearTimeout(this.updateTimer);
368
- this.updateTimer = setTimeout(() => {
369
- this.processPendingUpdates();
370
- }, WalletManager.DEBOUNCE_MS);
371
- }
372
-
373
- private async processPendingUpdates(): Promise<void> {
374
- if (this.pendingUpdates.size === 0) {
375
- return;
376
- }
377
-
378
- try {
379
- this.notify({ type: 'sync_wallet', loading: true });
380
- console.log(`Processing ${this.pendingUpdates.size} pending updates...`);
381
-
382
- const updates = Array.from(this.pendingUpdates);
383
- this.pendingUpdates.clear();
384
-
385
- const accountsHistoryPromises: Promise<AddressHistory>[] = [];
386
- const vaultsHistoryPromises: Promise<AddressHistory>[] = [];
387
- const walletHistoryPromises: Promise<AddressHistory>[] = [];
388
- for (const [, update] of updates) {
389
- if (this.isAccountAddress(update.address)) {
390
- const p = this.fetchAndUpdateAccount(update.address, update.result);
391
- accountsHistoryPromises.push(p);
392
- } else if (this.isVaultAddress(update.address)) {
393
- const p = this.fetchAndUpdateVault(update.address, update.result);
394
- vaultsHistoryPromises.push(p);
395
- } else {
396
- const p = this.fetchAndUpdateAddress(update.address, update.result);
397
- walletHistoryPromises.push(p);
398
- }
399
- }
400
-
401
- let initResolved = false;
402
- if (this.addressResolvers.size > 0) {
403
- for (const [address,] of updates) {
404
- const resolver = this.addressResolvers.get(address);
405
- if (resolver) {
406
- resolver();
407
- this.addressResolvers.delete(address);
408
- }
409
- }
410
- initResolved = this.addressResolvers.size === 0;
411
- }
412
-
413
- const accountsTxs = await Promise.all(accountsHistoryPromises);
414
- await Promise.all(vaultsHistoryPromises);
415
- const walletTxs = await Promise.all(walletHistoryPromises);
416
-
417
- const postPromises: Promise<void>[] = [this.postProcessWalletUpdate(walletTxs), this.postProcessAccountsUpdate(accountsTxs)];
418
- if (initResolved) {
419
- postPromises.push(this.recoverTokens());
420
- }
421
- await Promise.all(postPromises);
422
-
423
- if (initResolved && this.discoveryResolver) {
424
- this.discoveryResolver();
425
- this.discoveryResolver = undefined;
426
- }
427
- } catch (e) {
428
- console.error('Error processing pending updates:', e);
429
- } finally {
430
- this.notify({ type: 'sync_wallet', loading: false });
431
- }
432
- }
433
-
434
- private async postProcessWalletUpdate(history: AddressHistory[]): Promise<void> {
435
- if (history.length === 0) {
436
- return;
437
- }
438
-
439
- const txHistoryMap = new Map<string, ITXHistory>();
440
- for (const { txs } of history) {
441
- for (const tx of txs) {
442
- txHistoryMap.set(tx.tx_hash, tx);
443
- }
444
- }
445
- const txHistory = Array.from(txHistoryMap.values());
446
-
447
- await this.checkGapLimit(KeySpace.RECEIVE);
448
- await this.checkGapLimit(KeySpace.CHANGE);
449
-
450
- const walletAddresses = this.getMainAddresses();
451
- const walletBalance = sumBalance(walletAddresses.map(a => a.balance));
452
- const walletTokenBalances = sumTokensBalance(walletAddresses.map(a => a.tokensBalance));
453
-
454
- this.notify({ type: 'account_balance_updated', accountId: HD_WALLET_ID, balance: walletBalance, tokensBalance: walletTokenBalances });
455
-
456
- await this.postProcessActivity(HD_WALLET_ID, txHistory, walletAddresses.map(a => a.address), walletTokenBalances);
457
- }
458
-
459
- private async postProcessAccountsUpdate(history: AddressHistory[]): Promise<void> {
460
- if (history.length === 0) {
461
- return;
462
- }
463
-
464
- const activityPromises: Promise<void>[] = [];
465
- for (const { address, txs } of history) {
466
- const account = address as AccountDTO;
467
-
468
- this.notify({ type: 'account_balance_updated', accountId: account.id, balance: account.balance, tokensBalance: account.tokensBalance });
469
-
470
- const p = this.postProcessActivity(account.id, txs, [account.address], account.tokensBalance);
471
- activityPromises.push(p);
472
- }
473
- await Promise.all(activityPromises);
474
- }
475
-
476
- private async postProcessActivity(accountId: number, txHistory: ITXHistory[], addresses: string[], tokensBalance: Record<string, Balance>): Promise<void> {
477
- const postPromises: Promise<void>[] = [];
478
- const nftPromise = this.assetService.syncNfts(accountId, tokensBalance);
479
- for (const tx of txHistory) {
480
- const p = this.transactionService.classifyAndSaveTransaction(accountId, tx.tx_hash, addresses);
481
- postPromises.push(p);
482
- }
483
- postPromises.push(nftPromise);
484
- await Promise.all(postPromises);
485
- }
486
-
487
- private async fetchAndUpdateAddress(addrDTO: AddressDTO, hash: string): Promise<AddressHistory> {
488
- addrDTO.statusHash = hash;
489
- addrDTO.balance = await this.rostrumService.getBalance(addrDTO.address);
490
- addrDTO.tokensBalance = await this.rostrumService.getTokensBalance(addrDTO.address);
491
-
492
- const history = await this.transactionService.fetchTransactionsHistory(addrDTO.address, addrDTO.height);
493
- addrDTO.height = history.lastHeight;
494
- if (!addrDTO.used) {
495
- addrDTO.used = history.txs.length > 0;
496
- }
497
-
498
- await this.walletDb.saveAddress(addrDTO);
499
-
500
- return { address: addrDTO, txs: history.txs };
501
- }
502
-
503
- private async fetchAndUpdateAccount(account: AccountDTO, hash: string): Promise<AddressHistory> {
504
- account.statusHash = hash;
505
- account.balance = await this.rostrumService.getBalance(account.address);
506
- account.tokensBalance = await this.rostrumService.getTokensBalance(account.address);
507
-
508
- const history = await this.transactionService.fetchTransactionsHistory(account.address, account.height);
509
- account.height = history.lastHeight;
510
-
511
- await this.walletDb.saveAccount(account);
512
-
513
- return { address: account, txs: history.txs };
514
- }
515
-
516
- private async fetchAndUpdateVault(vault: VaultDTO, hash: string): Promise<AddressHistory> {
517
- vault.statusHash = hash;
518
- vault.balance = await this.rostrumService.getBalance(vault.address);
519
-
520
- const history = await this.transactionService.fetchTransactionsHistory(vault.address, vault.height);
521
- vault.height = history.lastHeight;
522
-
523
- await this.walletDb.saveVault(vault);
524
- this.notify({ type: 'vault_balance_updated', address: vault.address, balance: vault.balance });
525
-
526
- return { address: vault, txs: history.txs };
527
- }
528
-
529
- private async checkGapLimit(keySpace: KeySpace): Promise<void> {
530
- const addresses = keySpace === KeySpace.RECEIVE
531
- ? this.receiveAddresses
532
- : this.changeAddresses;
533
-
534
- const spaceName = keySpace === KeySpace.RECEIVE ? 'Receive' : 'Change';
535
- const unused = addresses.filter(a => !a.used).length;
536
-
537
- if (unused < KeyManager.GAP_LIMIT) {
538
- const needed = KeyManager.GAP_LIMIT - unused;
539
- const lastIndex = addresses[addresses.length - 1].idx;
540
-
541
- console.log(`Deriving ${needed} more ${spaceName} addresses...`);
542
-
543
- const newAddresses = this.deriveAddresses(keySpace, lastIndex + 1, needed);
544
-
545
- if (keySpace === KeySpace.RECEIVE) {
546
- this.receiveAddresses.push(...newAddresses);
547
- } else {
548
- this.changeAddresses.push(...newAddresses);
549
- }
550
-
551
- await this.saveAddresses(newAddresses);
552
- await this.subscribeAddresses(newAddresses);
553
- }
554
- }
555
-
556
- public async addNewAccount(id: number, name: string): Promise<void> {
557
- const address = this.keyManager.deriveAddress(AccountType.DAPP, KeySpace.RECEIVE, id);
558
-
559
- const account: AccountDTO = {
560
- id: id,
561
- name: name,
562
- address: address,
563
- height: 0,
564
- hidden: 0,
565
- statusHash: '',
566
- balance: { confirmed: "0", unconfirmed: "0" },
567
- tokensBalance: {},
568
- type: AccountType.DAPP
569
- };
570
-
571
- this.accounts.set(id, account);
572
- this.accountsAddressToId.set(address, id);
573
- await this.walletDb.saveAccount(account);
574
-
575
- this.notify({
576
- type: 'new_account',
577
- account: {
578
- id: account.id,
579
- name: account.name,
580
- address: account.address,
581
- balance: account.balance,
582
- tokensBalance: account.tokensBalance,
583
- sessions: {}
584
- }
585
- });
586
- await this.subscribeAddresses([account]);
587
- }
588
-
589
- public async updateAccountName(id: number, name: string): Promise<void> {
590
- if (!name) {
591
- return;
592
- }
593
-
594
- const account = this.accounts.get(id)!;
595
- account.name = name;
596
-
597
- await this.walletDb.updateAccountName(id, name);
598
- }
599
-
600
- public rescanAccount(id: number): void {
601
- if (id == HD_WALLET_ID) {
602
- const addrs = this.getMainAddresses();
603
- for (const addr of addrs) {
604
- addr.height = 0;
605
- this.registerUpdate({address: addr, result: addr.statusHash});
606
- }
607
- } else {
608
- const account = this.accounts.get(id)!
609
- account.height = 0;
610
- this.registerUpdate({address: account, result: account.statusHash});
611
- }
612
- }
613
-
614
- public rescanVaults(): Promise<AddressHistory[]> {
615
- const vaultsPromises: Promise<AddressHistory>[] = [];
616
- for (const vault of this.vaults.values()) {
617
- const p = this.fetchAndUpdateVault(vault, vault.statusHash);
618
- vaultsPromises.push(p);
619
- }
620
- return Promise.all(vaultsPromises);
621
- }
622
-
623
- public getVaultNextIndex(): number {
624
- if (this.vaults.size == 0) {
625
- return 0;
626
- }
627
- return Math.max(...Array.from(this.vaults.values(), v => v.idx)) + 1;
628
- }
629
-
630
- public async addNewVault(address: string, block: number, index: number): Promise<void> {
631
- const vault: VaultDTO = {
632
- address: address,
633
- block: block,
634
- idx: index,
635
- height: 0,
636
- statusHash: '',
637
- balance: { confirmed: "0", unconfirmed: "0" },
638
- tokensBalance: {},
639
- type: AccountType.VAULT
640
- };
641
- await this.addVault(vault);
642
- }
643
-
644
- private async addVault(vault: VaultDTO): Promise<void> {
645
- this.vaults.set(vault.address, vault);
646
- await this.walletDb.saveVault(vault);
647
-
648
- this.notify({
649
- type: 'new_vault',
650
- vault: {
651
- address: vault.address,
652
- balance: vault.balance,
653
- block: vault.block,
654
- index: vault.idx
655
- }
656
- });
657
- await this.subscribeAddresses([vault]);
658
- }
659
-
660
- public async recoverVaults(): Promise<boolean> {
661
- let found = false;
662
- const vaults = await this.discoveryService.discoverVaults();
663
- const promises: Promise<void>[] = [];
664
- for (const [address, vault] of vaults) {
665
- if (!this.vaults.has(address)) {
666
- found = true;
667
- promises.push(this.addVault(vault));
668
- }
669
- }
670
- await Promise.all(promises);
671
- return found;
672
- }
673
-
674
- private async recoverTokens(): Promise<void> {
675
- const tokensLoadPromises: Promise<void>[] = [];
676
- tokensLoadPromises.push(this.assetService.syncTokens(HD_WALLET_ID, sumTokensBalance(this.getMainAddresses().map(a => a.tokensBalance))));
677
- for (const account of this.accounts.values()) {
678
- tokensLoadPromises.push(this.assetService.syncTokens(account.id, account.tokensBalance));
679
- }
680
- await Promise.all(tokensLoadPromises);
681
- }
682
-
683
- private isVaultAddress(address: AccountDTO | AddressDTO | VaultDTO): address is VaultDTO {
684
- return address.type == AccountType.VAULT;
685
- }
686
-
687
- private isAccountAddress(address: AccountDTO | AddressDTO | VaultDTO): address is AccountDTO {
688
- return address.type == AccountType.DAPP;
689
- }
690
-
691
- private isMainAddress(address: AccountDTO | AddressDTO | VaultDTO): address is AddressDTO {
692
- return address.type == AccountType.MAIN;
693
- }
694
- }
1
+ import type { WalletDB } from "../persistence";
2
+ import type { Account, AccountDTO, AddressDTO, AddressKey, Balance, ITXHistory, RostrumParams, VaultDTO, VaultInfo } from "../types";
3
+ import { AccountType, HD_WALLET_ID, keyPathToString, KeySpace, sumBalance, sumTokensBalance } from "../utils";
4
+ import type { AssetService } from "./asset";
5
+ import { WalletDiscoveryService } from "./discovery";
6
+ import { KeyManager } from "./key";
7
+ import type { RostrumService } from "./rostrum";
8
+ import type { SessionManager } from "./session";
9
+ import type { TransactionService } from "./transaction";
10
+
11
+ type WalletAddress = AccountDTO | AddressDTO | VaultDTO;
12
+
13
+ export interface AddressHistory {
14
+ address: WalletAddress;
15
+ txs: ITXHistory[];
16
+ }
17
+
18
+ interface UpdateInfo {
19
+ address: WalletAddress;
20
+ result: string
21
+ }
22
+
23
+ export type WalletEvent =
24
+ | { type: 'new_tip'; tip: number; }
25
+ | { type: 'new_account'; account: Account; }
26
+ | { type: 'new_vault'; vault: VaultInfo; }
27
+ | { type: 'sync_wallet'; loading: boolean; }
28
+ | { type: 'clear_wallet'; }
29
+ | { type: 'account_balance_updated'; accountId: number; balance: Balance, tokensBalance: Record<string, Balance>; }
30
+ | { type: 'vault_balance_updated'; address: string, balance: Balance; }
31
+
32
+ export type WalletUpdateCallback = (event: WalletEvent) => void;
33
+
34
+ export class WalletManager {
35
+
36
+ private static readonly DEBOUNCE_MS = 1000;
37
+
38
+ /** Delay before the first `connect` retry, in milliseconds. Doubles after each failed attempt. */
39
+ private static readonly RETRY_DELAY_MS = 1000;
40
+
41
+ /** Upper bound for the delay between `connect` retries, in milliseconds. */
42
+ private static readonly MAX_RETRY_DELAY_MS = 10_000;
43
+
44
+ public accounts: Map<number, AccountDTO>;
45
+ public accountsAddressToId: Map<string, number>;
46
+
47
+ public receiveAddresses: AddressDTO[];
48
+ public changeAddresses: AddressDTO[];
49
+
50
+ public vaults: Map<string, VaultDTO>;
51
+
52
+ private pendingUpdates: Map<string, UpdateInfo>;
53
+ private updateTimer?: number;
54
+ private updatesStarted = false;
55
+
56
+ private updateCallback?: WalletUpdateCallback;
57
+
58
+ private isConnected = false;
59
+
60
+ private isSubscribed = false;
61
+
62
+ // Incremented by disconnectRostrum(), so a running connect() loop from before knows to stop.
63
+ private connectionId = 0;
64
+ // The connect() loop in progress, shared by concurrent calls.
65
+ private connecting?: { id: number; promise: Promise<void> };
66
+ // Ends the wait before the next connect() attempt.
67
+ private retryNow?: () => void;
68
+
69
+ private readonly discoveryService: WalletDiscoveryService;
70
+
71
+ public constructor(
72
+ private readonly keyManager: KeyManager,
73
+ private readonly walletDb: WalletDB,
74
+ private readonly rostrumService: RostrumService,
75
+ private readonly assetService: AssetService,
76
+ private readonly transactionService: TransactionService,
77
+ private readonly sessionManager: SessionManager,
78
+ ) {
79
+ this.discoveryService = new WalletDiscoveryService(this.rostrumService, this.keyManager);
80
+ this.accounts = new Map();
81
+ this.accountsAddressToId = new Map();
82
+ this.receiveAddresses = [];
83
+ this.changeAddresses = [];
84
+ this.vaults = new Map();
85
+ this.pendingUpdates = new Map();
86
+ }
87
+
88
+ public clear(): void {
89
+ this.accounts.clear();
90
+ this.accountsAddressToId.clear();
91
+ this.receiveAddresses = [];
92
+ this.changeAddresses = [];
93
+ this.vaults.clear();
94
+ this.stopUpdates();
95
+ this.notify({ type: 'clear_wallet' });
96
+ }
97
+
98
+ public onUpdate(callback: WalletUpdateCallback): void {
99
+ this.updateCallback = callback;
100
+ }
101
+
102
+ private notify(event: WalletEvent): void {
103
+ this.updateCallback?.(event);
104
+ }
105
+
106
+ private getAllAddresses(): WalletAddress[] {
107
+ return [...this.receiveAddresses, ...this.changeAddresses, ...this.accounts.values(), ...this.vaults.values()];
108
+ }
109
+
110
+ public getMainAddresses(): AddressDTO[] {
111
+ return [...this.receiveAddresses, ...this.changeAddresses];
112
+ }
113
+
114
+ public getReceiveAddress(accountId = HD_WALLET_ID): string {
115
+ if (accountId != HD_WALLET_ID) {
116
+ return this.accounts.get(accountId)!.address;
117
+ }
118
+ return this.receiveAddresses.find(addr => !addr.used)!.address;
119
+ }
120
+
121
+ public getChangeAddress(accountId = HD_WALLET_ID): string {
122
+ if (accountId != HD_WALLET_ID) {
123
+ return this.accounts.get(accountId)!.address;
124
+ }
125
+ return this.changeAddresses.find(addr => !addr.used)!.address;
126
+ }
127
+
128
+ public getUsedAddressKeys(accountId = HD_WALLET_ID): AddressKey[] {
129
+ if (accountId != HD_WALLET_ID) {
130
+ const account = this.accounts.get(accountId)!;
131
+ return [{
132
+ address: account.address,
133
+ keyPath: keyPathToString(AccountType.DAPP, 0, account.id),
134
+ balance: account.balance,
135
+ tokensBalance: account.tokensBalance
136
+ }];
137
+ }
138
+
139
+ return this.getMainAddresses().filter(addr => addr.used).map(addr => ({
140
+ address: addr.address,
141
+ keyPath: keyPathToString(AccountType.MAIN, addr.space, addr.idx),
142
+ balance: addr.balance,
143
+ tokensBalance: addr.tokensBalance
144
+ }));
145
+ }
146
+
147
+ public async reloadRostrum(params?: RostrumParams): Promise<void> {
148
+ if (params) {
149
+ await this.rostrumService.setCurrentInstance(params);
150
+ }
151
+ await this.disconnectRostrum();
152
+ await this.initRostrum();
153
+ this.startUpdates();
154
+ await this.subscribeAllAddresses();
155
+ }
156
+
157
+ public async initRostrum(): Promise<void> {
158
+ if (this.isConnected) {
159
+ return;
160
+ }
161
+ await this.rostrumService.connect();
162
+ await this.rostrumService.subscribeHeaders(tip => this.notify({ type: 'new_tip', tip }));
163
+ this.isConnected = true;
164
+ }
165
+
166
+ /**
167
+ * Connects and syncs the loaded wallet, retrying with exponential backoff until it succeeds or
168
+ * `disconnectRostrum()` is called. Never throws.
169
+ *
170
+ * Each attempt skips what's already done (connected, subscribed), so a retry continues where the last one failed.
171
+ * Calling it while waiting to retry makes the next attempt immediately (e.g. when the app returns to the foreground).
172
+ *
173
+ * For flows where the user is waiting on the result (e.g. discovery), use `initRostrum()`, which makes a single attempt.
174
+ *
175
+ * @returns resolves once connected and synced, or when stopped by `disconnectRostrum()`.
176
+ */
177
+ public connect(): Promise<void> {
178
+ if (this.connecting?.id === this.connectionId) {
179
+ this.retryNow?.();
180
+ return this.connecting.promise;
181
+ }
182
+
183
+ const connecting = { id: this.connectionId, promise: this.connectLoop(this.connectionId) };
184
+ this.connecting = connecting;
185
+ void connecting.promise.finally(() => {
186
+ if (this.connecting === connecting) {
187
+ this.connecting = undefined;
188
+ }
189
+ });
190
+ return connecting.promise;
191
+ }
192
+
193
+ private async connectLoop(id: number): Promise<void> {
194
+ let delay = WalletManager.RETRY_DELAY_MS;
195
+ while (id === this.connectionId) {
196
+ try {
197
+ await this.initRostrum();
198
+ await this.reconnectSync();
199
+ return;
200
+ } catch (e) {
201
+ console.info(`Connection failed, retrying in ${delay}ms:`, e instanceof Error ? e.message : e);
202
+ }
203
+ if (id !== this.connectionId) {
204
+ return;
205
+ }
206
+ await new Promise<void>(resolve => {
207
+ const timer = setTimeout(() => this.retryNow?.(), delay);
208
+ this.retryNow = () => {
209
+ clearTimeout(timer);
210
+ this.retryNow = undefined;
211
+ resolve();
212
+ };
213
+ });
214
+ delay = Math.min(delay * 2, WalletManager.MAX_RETRY_DELAY_MS);
215
+ }
216
+ }
217
+
218
+ public async disconnectRostrum(): Promise<void> {
219
+ // Stops a connect() loop: it ends its wait and sees it's no longer current.
220
+ this.connectionId++;
221
+ this.retryNow?.();
222
+ await this.rostrumService.disconnect();
223
+ this.isConnected = false;
224
+ this.isSubscribed = false;
225
+ this.stopUpdates();
226
+ }
227
+
228
+ public async discoverWallet(): Promise<void> {
229
+ const rIndexPromise = this.discoveryService.discoverWalletIndex(AccountType.MAIN, KeySpace.RECEIVE);
230
+ const cIndexPromise = this.discoveryService.discoverWalletIndex(AccountType.MAIN, KeySpace.CHANGE);
231
+ const dappIndexPromise = this.discoveryService.discoverWalletIndex(AccountType.DAPP, KeySpace.RECEIVE);
232
+ const vaultsPromise = this.discoveryService.discoverVaults();
233
+
234
+ const [rIndex, cIndex, dappIndex, vaults] = await Promise.all([rIndexPromise, cIndexPromise, dappIndexPromise, vaultsPromise]);
235
+
236
+ this.receiveAddresses = this.deriveAddresses(KeySpace.RECEIVE, 0, rIndex + KeyManager.GAP_LIMIT + 1);
237
+ this.changeAddresses = this.deriveAddresses(KeySpace.CHANGE, 0, cIndex + KeyManager.GAP_LIMIT + 1);
238
+ this.accounts = this.deriveAccounts(0, dappIndex < 0 ? 1 : dappIndex + 1);
239
+ this.accounts.forEach(entry => this.accountsAddressToId.set(entry.address, entry.id));
240
+ this.vaults = vaults;
241
+
242
+ await this.saveAddresses(this.receiveAddresses);
243
+ await this.saveAddresses(this.changeAddresses);
244
+ await this.saveAccounts(this.accounts);
245
+ await this.saveVaults(this.vaults);
246
+
247
+ this.initState();
248
+ }
249
+
250
+ public async loadWallet(): Promise<void> {
251
+ this.receiveAddresses = await this.walletDb.getReceiveAddresses();
252
+ this.changeAddresses = await this.walletDb.getChangeAddresses();
253
+
254
+ const accs = await this.walletDb.getAccounts();
255
+ this.accounts = new Map(accs.map(a => [a.id, a]));
256
+ this.accountsAddressToId = new Map(accs.map(a => [a.address, a.id]));
257
+
258
+ const vaults = await this.walletDb.getVaults();
259
+ this.vaults = new Map(vaults.map(v => [v.address, v]));
260
+
261
+ this.initState();
262
+ }
263
+
264
+ /**
265
+ * First sync after discovery: subscriptions only queue updates, which are then processed
266
+ * in one batch before the update loop starts.
267
+ */
268
+ public async initialSync(): Promise<void> {
269
+ await this.subscribeAllAddresses();
270
+ await this.processPendingUpdates(true);
271
+ this.startUpdates();
272
+ }
273
+
274
+ public reconnectSync(): Promise<[void, void]> {
275
+ this.startUpdates();
276
+ return Promise.all([
277
+ this.sessionManager.reload(this.accounts),
278
+ this.subscribeAllAddresses()
279
+ ]);
280
+ }
281
+
282
+ private async subscribeAllAddresses(): Promise<void> {
283
+ if (this.isSubscribed) {
284
+ return;
285
+ }
286
+ // Set before subscribing, so concurrent calls don't subscribe twice.
287
+ this.isSubscribed = true;
288
+ try {
289
+ await this.subscribeAddresses(this.getAllAddresses());
290
+ } catch (e) {
291
+ // Not (fully) subscribed: the next call tries again.
292
+ this.isSubscribed = false;
293
+ throw e;
294
+ }
295
+ }
296
+
297
+ private initState(): void {
298
+ const walletAddresses = this.getMainAddresses();
299
+
300
+ this.notify({
301
+ type: 'new_account',
302
+ account: {
303
+ id: HD_WALLET_ID,
304
+ name: 'HD Wallet',
305
+ address: this.getReceiveAddress(),
306
+ balance: sumBalance(walletAddresses.map(a => a.balance)),
307
+ tokensBalance: sumTokensBalance(walletAddresses.map(a => a.tokensBalance)),
308
+ sessions: {}
309
+ }
310
+ });
311
+
312
+ for (const account of this.accounts.values()) {
313
+ this.notify({
314
+ type: 'new_account',
315
+ account: {
316
+ id: account.id,
317
+ name: account.name,
318
+ address: account.address,
319
+ balance: account.balance,
320
+ tokensBalance: account.tokensBalance,
321
+ sessions: {}
322
+ }
323
+ });
324
+ }
325
+
326
+ for (const vault of this.vaults.values()) {
327
+ this.notify({
328
+ type: 'new_vault',
329
+ vault: {
330
+ address: vault.address,
331
+ balance: vault.balance,
332
+ block: vault.block,
333
+ index: vault.idx
334
+ }
335
+ });
336
+ }
337
+ }
338
+
339
+ private deriveAddresses(space: KeySpace, startIndex: number, count: number): AddressDTO[] {
340
+ const newAddresses: AddressDTO[] = [];
341
+ for (let i = startIndex; i < startIndex + count; i++) {
342
+ const addressDTO: AddressDTO = {
343
+ address: this.keyManager.deriveAddress(AccountType.MAIN, space, i),
344
+ space: space,
345
+ idx: i,
346
+ used: false,
347
+ height: 0,
348
+ statusHash: '',
349
+ balance: { confirmed: "0", unconfirmed: "0" },
350
+ tokensBalance: {},
351
+ type: AccountType.MAIN
352
+ };
353
+
354
+ newAddresses.push(addressDTO);
355
+ }
356
+
357
+ return newAddresses;
358
+ }
359
+
360
+ private deriveAccounts(startIndex: number, count: number): Map<number, AccountDTO> {
361
+ const newAccounts = new Map<number, AccountDTO>();
362
+ for (let i = startIndex; i < startIndex + count; i++) {
363
+ const account: AccountDTO = {
364
+ id: i,
365
+ name: `Account ${i + 1}`,
366
+ address: this.keyManager.deriveAddress(AccountType.DAPP, KeySpace.RECEIVE, i),
367
+ height: 0,
368
+ hidden: 0,
369
+ statusHash: '',
370
+ balance: { confirmed: "0", unconfirmed: "0" },
371
+ tokensBalance: {},
372
+ type: AccountType.DAPP
373
+ };
374
+
375
+ newAccounts.set(account.id, account);
376
+ }
377
+
378
+ return newAccounts;
379
+ }
380
+
381
+ private async saveAddresses(addresses: AddressDTO[]): Promise<void> {
382
+ for (const addr of addresses) {
383
+ await this.walletDb.saveAddress(addr);
384
+ }
385
+ }
386
+
387
+ private async saveAccounts(accounts: Map<number, AccountDTO>): Promise<void> {
388
+ for (const acc of accounts.values()) {
389
+ await this.walletDb.saveAccount(acc);
390
+ }
391
+ }
392
+
393
+ private async saveVaults(vaults: Map<string, VaultDTO>): Promise<void> {
394
+ for (const vault of vaults.values()) {
395
+ await this.walletDb.saveVault(vault);
396
+ }
397
+ }
398
+
399
+ /**
400
+ * The subscribe callback (onSubscribeEvent) receives each address's initial status,
401
+ * so changed addresses are registered for update from there.
402
+ */
403
+ private async subscribeAddresses(addresses: WalletAddress[]): Promise<void> {
404
+ await Promise.all(addresses.map(addr => this.rostrumService.subscribeAddress(addr.address, this.onSubscribeEvent)));
405
+ }
406
+
407
+ private onSubscribeEvent = (address: string, status: string | null): void => {
408
+ if (typeof status !== 'string') {
409
+ // null status: the address has no history
410
+ return;
411
+ }
412
+
413
+ const allAddresses = this.getAllAddresses();
414
+ const addrDTO = allAddresses.find(a => a.address === address);
415
+
416
+ if (addrDTO && addrDTO.statusHash !== status) {
417
+ this.registerUpdate({address: addrDTO, result: status});
418
+ }
419
+ }
420
+
421
+ private registerUpdate(updateInfo: UpdateInfo): void {
422
+ this.pendingUpdates.set(updateInfo.address.address, updateInfo);
423
+ // before the loop starts (e.g. during initial sync), updates are only queued
424
+ if (this.updatesStarted) {
425
+ this.scheduleUpdates();
426
+ }
427
+ }
428
+
429
+ private scheduleUpdates(): void {
430
+ clearTimeout(this.updateTimer);
431
+ this.updateTimer = setTimeout(() => {
432
+ this.processPendingUpdates();
433
+ }, WalletManager.DEBOUNCE_MS);
434
+ }
435
+
436
+ private startUpdates(): void {
437
+ if (this.updatesStarted) {
438
+ return;
439
+ }
440
+ this.updatesStarted = true;
441
+ // process anything that was queued while the loop was stopped
442
+ if (this.pendingUpdates.size > 0) {
443
+ this.scheduleUpdates();
444
+ }
445
+ }
446
+
447
+ private stopUpdates(): void {
448
+ this.updatesStarted = false;
449
+ clearTimeout(this.updateTimer);
450
+ this.updateTimer = undefined;
451
+ this.pendingUpdates.clear();
452
+ }
453
+
454
+ private async processPendingUpdates(recoverTokens = false): Promise<void> {
455
+ if (this.pendingUpdates.size === 0) {
456
+ return;
457
+ }
458
+
459
+ try {
460
+ this.notify({ type: 'sync_wallet', loading: true });
461
+ console.log(`Processing ${this.pendingUpdates.size} pending updates...`);
462
+
463
+ const updates = Array.from(this.pendingUpdates);
464
+ this.pendingUpdates.clear();
465
+
466
+ const accountsHistoryPromises: Promise<AddressHistory>[] = [];
467
+ const vaultsHistoryPromises: Promise<AddressHistory>[] = [];
468
+ const walletHistoryPromises: Promise<AddressHistory>[] = [];
469
+ for (const [, update] of updates) {
470
+ if (this.isAccountAddress(update.address)) {
471
+ const p = this.fetchAndUpdateAccount(update.address, update.result);
472
+ accountsHistoryPromises.push(p);
473
+ } else if (this.isVaultAddress(update.address)) {
474
+ const p = this.fetchAndUpdateVault(update.address, update.result);
475
+ vaultsHistoryPromises.push(p);
476
+ } else {
477
+ const p = this.fetchAndUpdateAddress(update.address, update.result);
478
+ walletHistoryPromises.push(p);
479
+ }
480
+ }
481
+
482
+ const accountsTxs = await Promise.all(accountsHistoryPromises);
483
+ await Promise.all(vaultsHistoryPromises);
484
+ const walletTxs = await Promise.all(walletHistoryPromises);
485
+
486
+ const postPromises: Promise<void>[] = [this.postProcessWalletUpdate(walletTxs), this.postProcessAccountsUpdate(accountsTxs)];
487
+ if (recoverTokens) {
488
+ postPromises.push(this.recoverTokens());
489
+ }
490
+ await Promise.all(postPromises);
491
+ } catch (e) {
492
+ console.error('Error processing pending updates:', e);
493
+ } finally {
494
+ this.notify({ type: 'sync_wallet', loading: false });
495
+ }
496
+ }
497
+
498
+ private async postProcessWalletUpdate(history: AddressHistory[]): Promise<void> {
499
+ if (history.length === 0) {
500
+ return;
501
+ }
502
+
503
+ const txHistoryMap = new Map<string, ITXHistory>();
504
+ for (const { txs } of history) {
505
+ for (const tx of txs) {
506
+ txHistoryMap.set(tx.tx_hash, tx);
507
+ }
508
+ }
509
+ const txHistory = Array.from(txHistoryMap.values());
510
+
511
+ await this.checkGapLimit(KeySpace.RECEIVE);
512
+ await this.checkGapLimit(KeySpace.CHANGE);
513
+
514
+ const walletAddresses = this.getMainAddresses();
515
+ const walletBalance = sumBalance(walletAddresses.map(a => a.balance));
516
+ const walletTokenBalances = sumTokensBalance(walletAddresses.map(a => a.tokensBalance));
517
+
518
+ this.notify({ type: 'account_balance_updated', accountId: HD_WALLET_ID, balance: walletBalance, tokensBalance: walletTokenBalances });
519
+
520
+ await this.postProcessActivity(HD_WALLET_ID, txHistory, walletAddresses.map(a => a.address), walletTokenBalances);
521
+ }
522
+
523
+ private async postProcessAccountsUpdate(history: AddressHistory[]): Promise<void> {
524
+ if (history.length === 0) {
525
+ return;
526
+ }
527
+
528
+ const activityPromises: Promise<void>[] = [];
529
+ for (const { address, txs } of history) {
530
+ const account = address as AccountDTO;
531
+
532
+ this.notify({ type: 'account_balance_updated', accountId: account.id, balance: account.balance, tokensBalance: account.tokensBalance });
533
+
534
+ const p = this.postProcessActivity(account.id, txs, [account.address], account.tokensBalance);
535
+ activityPromises.push(p);
536
+ }
537
+ await Promise.all(activityPromises);
538
+ }
539
+
540
+ private async postProcessActivity(accountId: number, txHistory: ITXHistory[], addresses: string[], tokensBalance: Record<string, Balance>): Promise<void> {
541
+ const postPromises: Promise<void>[] = [];
542
+ const nftPromise = this.assetService.syncNfts(accountId, tokensBalance);
543
+ for (const tx of txHistory) {
544
+ const p = this.transactionService.classifyAndSaveTransaction(accountId, tx.tx_hash, addresses);
545
+ postPromises.push(p);
546
+ }
547
+ postPromises.push(nftPromise);
548
+ await Promise.all(postPromises);
549
+ }
550
+
551
+ private async fetchAndUpdateAddress(addrDTO: AddressDTO, hash: string): Promise<AddressHistory> {
552
+ addrDTO.balance = await this.rostrumService.getBalance(addrDTO.address);
553
+ addrDTO.tokensBalance = await this.rostrumService.getTokensBalance(addrDTO.address);
554
+
555
+ const history = await this.transactionService.fetchTransactionsHistory(addrDTO.address, addrDTO.height);
556
+ addrDTO.height = history.lastHeight;
557
+ if (!addrDTO.used) {
558
+ addrDTO.used = history.txs.length > 0;
559
+ }
560
+
561
+ addrDTO.statusHash = hash;
562
+ await this.walletDb.saveAddress(addrDTO);
563
+
564
+ return { address: addrDTO, txs: history.txs };
565
+ }
566
+
567
+ private async fetchAndUpdateAccount(account: AccountDTO, hash: string): Promise<AddressHistory> {
568
+ account.balance = await this.rostrumService.getBalance(account.address);
569
+ account.tokensBalance = await this.rostrumService.getTokensBalance(account.address);
570
+
571
+ const history = await this.transactionService.fetchTransactionsHistory(account.address, account.height);
572
+ account.height = history.lastHeight;
573
+
574
+ account.statusHash = hash;
575
+ await this.walletDb.saveAccount(account);
576
+
577
+ return { address: account, txs: history.txs };
578
+ }
579
+
580
+ private async fetchAndUpdateVault(vault: VaultDTO, hash: string): Promise<AddressHistory> {
581
+ vault.balance = await this.rostrumService.getBalance(vault.address);
582
+
583
+ const history = await this.transactionService.fetchTransactionsHistory(vault.address, vault.height);
584
+ vault.height = history.lastHeight;
585
+
586
+ vault.statusHash = hash;
587
+ await this.walletDb.saveVault(vault);
588
+ this.notify({ type: 'vault_balance_updated', address: vault.address, balance: vault.balance });
589
+
590
+ return { address: vault, txs: history.txs };
591
+ }
592
+
593
+ private async checkGapLimit(keySpace: KeySpace): Promise<void> {
594
+ const addresses = keySpace === KeySpace.RECEIVE
595
+ ? this.receiveAddresses
596
+ : this.changeAddresses;
597
+
598
+ const spaceName = keySpace === KeySpace.RECEIVE ? 'Receive' : 'Change';
599
+ const unused = addresses.filter(a => !a.used).length;
600
+
601
+ if (unused < KeyManager.GAP_LIMIT) {
602
+ const needed = KeyManager.GAP_LIMIT - unused;
603
+ const lastIndex = addresses[addresses.length - 1].idx;
604
+
605
+ console.log(`Deriving ${needed} more ${spaceName} addresses...`);
606
+
607
+ const newAddresses = this.deriveAddresses(keySpace, lastIndex + 1, needed);
608
+
609
+ if (keySpace === KeySpace.RECEIVE) {
610
+ this.receiveAddresses.push(...newAddresses);
611
+ } else {
612
+ this.changeAddresses.push(...newAddresses);
613
+ }
614
+
615
+ await this.saveAddresses(newAddresses);
616
+ await this.subscribeAddresses(newAddresses);
617
+ }
618
+ }
619
+
620
+ public async addNewAccount(id: number, name: string): Promise<void> {
621
+ const address = this.keyManager.deriveAddress(AccountType.DAPP, KeySpace.RECEIVE, id);
622
+
623
+ const account: AccountDTO = {
624
+ id: id,
625
+ name: name,
626
+ address: address,
627
+ height: 0,
628
+ hidden: 0,
629
+ statusHash: '',
630
+ balance: { confirmed: "0", unconfirmed: "0" },
631
+ tokensBalance: {},
632
+ type: AccountType.DAPP
633
+ };
634
+
635
+ this.accounts.set(id, account);
636
+ this.accountsAddressToId.set(address, id);
637
+ await this.walletDb.saveAccount(account);
638
+
639
+ this.notify({
640
+ type: 'new_account',
641
+ account: {
642
+ id: account.id,
643
+ name: account.name,
644
+ address: account.address,
645
+ balance: account.balance,
646
+ tokensBalance: account.tokensBalance,
647
+ sessions: {}
648
+ }
649
+ });
650
+ await this.subscribeAddresses([account]);
651
+ }
652
+
653
+ public async updateAccountName(id: number, name: string): Promise<void> {
654
+ if (!name) {
655
+ return;
656
+ }
657
+
658
+ const account = this.accounts.get(id)!;
659
+ account.name = name;
660
+
661
+ await this.walletDb.updateAccountName(id, name);
662
+ }
663
+
664
+ public rescanAccount(id: number): void {
665
+ if (id == HD_WALLET_ID) {
666
+ const addrs = this.getMainAddresses();
667
+ for (const addr of addrs) {
668
+ addr.height = 0;
669
+ this.registerUpdate({address: addr, result: addr.statusHash});
670
+ }
671
+ } else {
672
+ const account = this.accounts.get(id)!
673
+ account.height = 0;
674
+ this.registerUpdate({address: account, result: account.statusHash});
675
+ }
676
+ }
677
+
678
+ public rescanVaults(): Promise<AddressHistory[]> {
679
+ const vaultsPromises: Promise<AddressHistory>[] = [];
680
+ for (const vault of this.vaults.values()) {
681
+ const p = this.fetchAndUpdateVault(vault, vault.statusHash);
682
+ vaultsPromises.push(p);
683
+ }
684
+ return Promise.all(vaultsPromises);
685
+ }
686
+
687
+ public getVaultNextIndex(): number {
688
+ if (this.vaults.size == 0) {
689
+ return 0;
690
+ }
691
+ return Math.max(...Array.from(this.vaults.values(), v => v.idx)) + 1;
692
+ }
693
+
694
+ public async addNewVault(address: string, block: number, index: number): Promise<void> {
695
+ const vault: VaultDTO = {
696
+ address: address,
697
+ block: block,
698
+ idx: index,
699
+ height: 0,
700
+ statusHash: '',
701
+ balance: { confirmed: "0", unconfirmed: "0" },
702
+ tokensBalance: {},
703
+ type: AccountType.VAULT
704
+ };
705
+ await this.addVault(vault);
706
+ }
707
+
708
+ private async addVault(vault: VaultDTO): Promise<void> {
709
+ this.vaults.set(vault.address, vault);
710
+ await this.walletDb.saveVault(vault);
711
+
712
+ this.notify({
713
+ type: 'new_vault',
714
+ vault: {
715
+ address: vault.address,
716
+ balance: vault.balance,
717
+ block: vault.block,
718
+ index: vault.idx
719
+ }
720
+ });
721
+ await this.subscribeAddresses([vault]);
722
+ }
723
+
724
+ public async recoverVaults(): Promise<boolean> {
725
+ let found = false;
726
+ const vaults = await this.discoveryService.discoverVaults();
727
+ const promises: Promise<void>[] = [];
728
+ for (const [address, vault] of vaults) {
729
+ if (!this.vaults.has(address)) {
730
+ found = true;
731
+ promises.push(this.addVault(vault));
732
+ }
733
+ }
734
+ await Promise.all(promises);
735
+ return found;
736
+ }
737
+
738
+ private async recoverTokens(): Promise<void> {
739
+ const tokensLoadPromises: Promise<void>[] = [];
740
+ tokensLoadPromises.push(this.assetService.syncTokens(HD_WALLET_ID, sumTokensBalance(this.getMainAddresses().map(a => a.tokensBalance))));
741
+ for (const account of this.accounts.values()) {
742
+ tokensLoadPromises.push(this.assetService.syncTokens(account.id, account.tokensBalance));
743
+ }
744
+ await Promise.all(tokensLoadPromises);
745
+ }
746
+
747
+ private isVaultAddress(address: AccountDTO | AddressDTO | VaultDTO): address is VaultDTO {
748
+ return address.type == AccountType.VAULT;
749
+ }
750
+
751
+ private isAccountAddress(address: AccountDTO | AddressDTO | VaultDTO): address is AccountDTO {
752
+ return address.type == AccountType.DAPP;
753
+ }
754
+
755
+ private isMainAddress(address: AccountDTO | AddressDTO | VaultDTO): address is AddressDTO {
756
+ return address.type == AccountType.MAIN;
757
+ }
758
+ }