@otoplo/wallet-common 0.8.1 → 0.9.0

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.
@@ -1,162 +1,190 @@
1
- import type { NftEntity, TokenEntity } from "../types/db.types";
2
- import { getAssetFileUrl, getAssetMetadataUrl } from "../utils/asset";
3
- import { balanceTotal, currentTimestamp, tokenIdToHex } from "../utils/common";
4
- import type { WalletDB } from "../persistence/wallet-db";
5
- import type { WalletCache } from "./cache";
6
- import type { AssetInfo, Balance } from "../types/wallet.types";
7
-
8
- export class AssetService {
9
-
10
- private readonly walletDb: WalletDB;
11
- private readonly walletCache: WalletCache;
12
-
13
- constructor(walletDb: WalletDB, walletCache: WalletCache) {
14
- this.walletDb = walletDb;
15
- this.walletCache = walletCache;
16
- }
17
-
18
- public async getAssetInfo(assetId: string): Promise<AssetInfo | undefined> {
19
- try {
20
- const token = await this.walletCache.getToken(assetId);
21
- if (token) {
22
- return {
23
- type: "token",
24
- parent: token.parent,
25
- token: token.token,
26
- tokenIdHex: token.tokenIdHex,
27
- data: {
28
- name: token.name,
29
- ticker: token.ticker,
30
- decimals: token.decimals,
31
- iconUrl: token.iconUrl
32
- }
33
- }
34
- }
35
-
36
- const nft = await this.walletCache.getNft(assetId);
37
- if (nft) {
38
- return {
39
- type: "nft",
40
- parent: nft.parent,
41
- token: nft.token,
42
- tokenIdHex: nft.tokenIdHex,
43
- data: {
44
- name: nft.name,
45
- series: nft.series,
46
- collection: nft.collection,
47
- author: nft.author,
48
- public: nft.public,
49
- front: nft.front,
50
- back: nft.back,
51
- thumb: nft.thumb
52
- }
53
- }
54
- }
55
-
56
- return await this.getAssetMetadata(assetId);
57
- } catch (e) {
58
- console.error(e);
59
- return undefined;
60
- }
61
- }
62
-
63
- public async handleNftReceive(accountId: number, tokenIdHex: string, time: number): Promise<void> {
64
- const nft = await this.getAssetInfo(tokenIdHex);
65
- if (nft && nft.type == 'nft') {
66
- const nftEntity: NftEntity = {
67
- token: nft.token,
68
- tokenIdHex: nft.tokenIdHex,
69
- parent: nft.parent,
70
- ...nft.data
71
- }
72
- await this.saveNft(accountId, nftEntity, time);
73
- }
74
- }
75
-
76
- public async syncTokens(accountId: number, tokenBalances: Record<string, Balance>): Promise<void> {
77
- for (const tokenId in tokenBalances) {
78
- const balance = tokenBalances[tokenId];
79
- if (balance && balanceTotal(balance) > 0n) {
80
- const token = await this.getAssetInfo(tokenId);
81
- if (token && token.type == 'token') {
82
- const tokenEntity: TokenEntity = {
83
- token: token.token,
84
- tokenIdHex: token.tokenIdHex,
85
- parent: token.parent,
86
- ...token.data
87
- };
88
- await this.saveToken(accountId, tokenEntity);
89
- }
90
- }
91
- }
92
- }
93
-
94
- public async syncNfts(accountId: number, tokensBalance: Record<string, Balance>): Promise<void> {
95
- const currentAssets = Object.keys(tokensBalance);
96
- const internalAssets = await this.walletDb.getAssets(accountId, "nft");
97
-
98
- const staleAssets = internalAssets?.filter(a => !currentAssets.includes(a.tokenIdHex)) ?? [];
99
- for (const asset of staleAssets) {
100
- await this.deleteNft(accountId, asset.tokenIdHex);
101
- }
102
-
103
- for (const [token, balance] of Object.entries(tokensBalance)) {
104
- const tokenId = tokenIdToHex(token);
105
- const hasBalance = balance && balanceTotal(balance) > 0n;
106
- const isAssetExist = internalAssets?.some(a => a.tokenIdHex == tokenId);
107
- if ((!hasBalance && !isAssetExist) || (hasBalance && isAssetExist)) {
108
- continue;
109
- }
110
-
111
- if (!hasBalance && isAssetExist) {
112
- await this.deleteNft(accountId, tokenId);
113
- } else {
114
- await this.handleNftReceive(accountId, tokenId, currentTimestamp());
115
- }
116
- }
117
- }
118
-
119
- public async saveToken(accountId: number, token: TokenEntity): Promise<void> {
120
- await this.walletDb.saveToken(accountId, token);
121
- }
122
-
123
- public async deleteToken(accountId: number, tokenId: string): Promise<void> {
124
- await this.walletDb.deleteToken(accountId, tokenId);
125
- this.walletCache.removeToken(tokenId);
126
- }
127
-
128
- public async saveNft(accountId: number, nft: NftEntity, time: number): Promise<void> {
129
- await this.walletDb.saveNft(accountId, nft, time);
130
- }
131
-
132
- public async deleteNft(accountId: number, tokenId: string): Promise<void> {
133
- await this.walletDb.deleteNft(accountId, tokenId);
134
- this.walletCache.removeNft(tokenId);
135
- }
136
-
137
- public getAssetFile(token: string, asset: string): Promise<Uint8Array> {
138
- return this.performGet(getAssetFileUrl(token, asset), 'raw');
139
- }
140
-
141
- private getAssetMetadata(token: string): Promise<AssetInfo> {
142
- return this.performGet(getAssetMetadataUrl(token), 'json');
143
- }
144
-
145
- private async performGet(url: string, responseType?: 'json' | 'raw'): Promise<any> {
146
- try {
147
- const response = await fetch(url);
148
- if (!response.ok) {
149
- throw new Error(`Failed to perform GET. status: ${response.status}`);
150
- }
151
-
152
- if (responseType === 'raw') {
153
- const arrayBuffer = await response.arrayBuffer();
154
- return new Uint8Array(arrayBuffer);
155
- } else {
156
- return await response.json();
157
- }
158
- } catch (e) {
159
- throw new Error(`Unexpected Error: ${e}`);
160
- }
161
- }
162
- }
1
+ import type { AssetMetadataEntity } from "../types/db.types";
2
+ import { getAssetFileUrl, getAssetMetadataUrl } from "../utils/asset";
3
+ import { balanceTotal, currentTimestamp, tokenIdToHex } from "../utils/common";
4
+ import type { WalletDB } from "../persistence/wallet-db";
5
+ import type { CachedAsset, WalletCache } from "./cache";
6
+ import type { AccountAsset, AssetInfo, AssetType, Balance } from "../types/wallet.types";
7
+
8
+ /**
9
+ * Bump when stored metadata must be fetched again, e.g. the assets API response changed.
10
+ * Rows of an older version are refetched when next used, with no DB migration.
11
+ */
12
+ export const ASSET_METADATA_VERSION = 1;
13
+
14
+ export class AssetService {
15
+
16
+ private readonly walletDb: WalletDB;
17
+ private readonly walletCache: WalletCache;
18
+
19
+ constructor(walletDb: WalletDB, walletCache: WalletCache) {
20
+ this.walletDb = walletDb;
21
+ this.walletCache = walletCache;
22
+ }
23
+
24
+ /**
25
+ * Metadata of any asset, held or not: memory, then DB, then API.
26
+ * Metadata of an older version is refetched, and kept if the fetch fails.
27
+ */
28
+ public async getAssetInfo(assetId: string): Promise<AssetInfo | undefined> {
29
+ const id = tokenIdToHex(assetId);
30
+ try {
31
+ const cached = this.walletCache.getAsset(id) ?? await this.loadFromDb(id);
32
+ if (cached?.version === ASSET_METADATA_VERSION) {
33
+ return cached.info;
34
+ }
35
+ return await this.fetchMetadata(id) ?? cached?.info;
36
+ } catch (e) {
37
+ console.error(e);
38
+ return undefined;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * One page of the account's assets, straight from the DB.
44
+ * Rows of an older version are returned as they are and refetched in the background,
45
+ * so the next load shows the new metadata.
46
+ */
47
+ public async getAssets(accountId: number, type: AssetType, pageNum: number, pageSize: number): Promise<AccountAsset[]> {
48
+ const rows = await this.walletDb.getPageAssets(accountId, type, pageNum, pageSize);
49
+ return rows.map(row => {
50
+ const id = row.tokenIdHex;
51
+ const info = parseAssetInfo(row.data);
52
+ if (info && !this.walletCache.getAsset(id)) {
53
+ this.walletCache.setAsset(id, { info, version: row.version });
54
+ }
55
+ if (!info || row.version !== ASSET_METADATA_VERSION) {
56
+ void this.fetchMetadata(id);
57
+ }
58
+ return { tokenIdHex: id, type: row.type, addedTime: row.addedTime, info };
59
+ });
60
+ }
61
+
62
+ public countAssets(accountId: number, type: AssetType): Promise<number> {
63
+ return this.walletDb.countAssets(accountId, type);
64
+ }
65
+
66
+ public async handleNftReceive(accountId: number, tokenIdHex: string, time: number): Promise<void> {
67
+ const nft = await this.getAssetInfo(tokenIdHex);
68
+ if (nft && nft.type == 'nft') {
69
+ await this.saveAsset(accountId, nft, time);
70
+ }
71
+ }
72
+
73
+ public async syncTokens(accountId: number, tokenBalances: Record<string, Balance>): Promise<void> {
74
+ for (const tokenId in tokenBalances) {
75
+ const balance = tokenBalances[tokenId];
76
+ if (balance && balanceTotal(balance) > 0n) {
77
+ const token = await this.getAssetInfo(tokenId);
78
+ if (token && token.type == 'token') {
79
+ await this.saveAsset(accountId, token);
80
+ }
81
+ }
82
+ }
83
+ }
84
+
85
+ public async syncNfts(accountId: number, tokensBalance: Record<string, Balance>): Promise<void> {
86
+ const currentAssets = Object.keys(tokensBalance);
87
+ const internalAssets = await this.walletDb.getAssets(accountId, "nft");
88
+
89
+ const staleAssets = internalAssets?.filter(a => !currentAssets.includes(a.tokenIdHex)) ?? [];
90
+ for (const asset of staleAssets) {
91
+ await this.deleteAsset(accountId, asset.tokenIdHex);
92
+ }
93
+
94
+ for (const [tokenId, balance] of Object.entries(tokensBalance)) {
95
+ const hasBalance = balance && balanceTotal(balance) > 0n;
96
+ const isAssetExist = internalAssets?.some(a => a.tokenIdHex == tokenId);
97
+ if ((!hasBalance && !isAssetExist) || (hasBalance && isAssetExist)) {
98
+ continue;
99
+ }
100
+
101
+ if (!hasBalance && isAssetExist) {
102
+ await this.deleteAsset(accountId, tokenId);
103
+ } else {
104
+ await this.handleNftReceive(accountId, tokenId, currentTimestamp());
105
+ }
106
+ }
107
+ }
108
+
109
+ /** Adds the asset to the account and stores its metadata. */
110
+ public async saveAsset(accountId: number, info: AssetInfo, addedTime = currentTimestamp()): Promise<void> {
111
+ const id = tokenIdToHex(info.tokenIdHex);
112
+ // the version info was fetched under, so an outdated fallback is still refetched later
113
+ const version = this.walletCache.getAsset(id)?.version ?? ASSET_METADATA_VERSION;
114
+
115
+ await this.walletDb.saveAssetMetadata(toMetadataEntity(id, { info, version }));
116
+ await this.walletDb.saveAsset({ accountId, tokenIdHex: id, type: info.type, addedTime });
117
+ }
118
+
119
+ /** Removes the asset from the account; its metadata too once no account holds it. */
120
+ public deleteAsset(accountId: number, tokenId: string): Promise<void> {
121
+ return this.walletDb.deleteAsset(accountId, tokenIdToHex(tokenId));
122
+ }
123
+
124
+ public getAssetFile(token: string, asset: string): Promise<Uint8Array> {
125
+ return this.performGet(getAssetFileUrl(token, asset), 'raw');
126
+ }
127
+
128
+ private async loadFromDb(id: string): Promise<CachedAsset | undefined> {
129
+ const row = await this.walletDb.getAssetMetadata(id);
130
+ const info = row ? parseAssetInfo(row.data) : undefined;
131
+ if (!row || !info) {
132
+ return undefined;
133
+ }
134
+
135
+ const cached: CachedAsset = { info, version: row.version };
136
+ this.walletCache.setAsset(id, cached);
137
+ return cached;
138
+ }
139
+
140
+ /** Fetches from the API into memory, and into the DB if the asset is held. Never throws. */
141
+ private async fetchMetadata(id: string): Promise<AssetInfo | undefined> {
142
+ try {
143
+ const info: AssetInfo = await this.performGet(getAssetMetadataUrl(id), 'json');
144
+ const cached: CachedAsset = { info, version: ASSET_METADATA_VERSION };
145
+ this.walletCache.setAsset(id, cached);
146
+ if (await this.walletDb.isAssetHeld(id)) {
147
+ await this.walletDb.saveAssetMetadata(toMetadataEntity(id, cached));
148
+ }
149
+ return info;
150
+ } catch (e) {
151
+ console.error(e);
152
+ return undefined;
153
+ }
154
+ }
155
+
156
+ private async performGet(url: string, responseType?: 'json' | 'raw'): Promise<any> {
157
+ try {
158
+ const response = await fetch(url);
159
+ if (!response.ok) {
160
+ throw new Error(`Failed to perform GET. status: ${response.status}`);
161
+ }
162
+
163
+ if (responseType === 'raw') {
164
+ const arrayBuffer = await response.arrayBuffer();
165
+ return new Uint8Array(arrayBuffer);
166
+ } else {
167
+ return await response.json();
168
+ }
169
+ } catch (e) {
170
+ throw new Error(`Unexpected Error: ${e}`);
171
+ }
172
+ }
173
+ }
174
+
175
+ function parseAssetInfo(data: string): AssetInfo | undefined {
176
+ try {
177
+ return JSON.parse(data);
178
+ } catch {
179
+ return undefined;
180
+ }
181
+ }
182
+
183
+ function toMetadataEntity(id: string, cached: CachedAsset): AssetMetadataEntity {
184
+ return {
185
+ tokenIdHex: id,
186
+ name: cached.info.data.name,
187
+ data: JSON.stringify(cached.info),
188
+ version: cached.version,
189
+ };
190
+ }
@@ -1,54 +1,26 @@
1
- import type { NftEntity, TokenEntity } from "../types/db.types";
2
- import { tokenIdToHex } from "../utils/common";
3
- import type { WalletDB } from "../persistence/wallet-db";
4
-
5
- export class WalletCache {
6
-
7
- private readonly walletDb: WalletDB;
8
-
9
- private readonly tokens = new Map<string, TokenEntity>();
10
- private readonly nfts = new Map<string, NftEntity>();
11
-
12
- public constructor(walletDb: WalletDB) {
13
- this.walletDb = walletDb;
14
- }
15
-
16
- public clear(): void {
17
- this.tokens.clear();
18
- this.nfts.clear();
19
- }
20
-
21
- public async getToken(id: string): Promise<TokenEntity | null | undefined> {
22
- id = tokenIdToHex(id);
23
- if (this.tokens.has(id)) {
24
- return this.tokens.get(id);
25
- }
26
-
27
- const token = await this.walletDb.getToken(id);
28
- if (token) {
29
- this.tokens.set(id, token);
30
- }
31
- return token;
32
- }
33
-
34
- public async getNft(id: string): Promise<NftEntity | null | undefined> {
35
- id = tokenIdToHex(id);
36
- if (this.nfts.has(id)) {
37
- return this.nfts.get(id);
38
- }
39
-
40
- const nft = await this.walletDb.getNft(id);
41
- if (nft) {
42
- this.nfts.set(id, nft);
43
- }
44
- return nft;
45
- }
46
-
47
- public removeToken(id: string): void {
48
- this.tokens.delete(tokenIdToHex(id));
49
- }
50
-
51
- public removeNft(id: string): void {
52
- this.nfts.delete(tokenIdToHex(id));
53
- }
54
- }
1
+ import type { AssetInfo } from "../types/wallet.types";
2
+ import { tokenIdToHex } from "../utils/common";
3
+
4
+ export interface CachedAsset {
5
+ info: AssetInfo;
6
+ /** The metadata version `info` was fetched under. */
7
+ version: number;
8
+ }
9
+
10
+ /** Asset metadata in memory, for every asset looked up while the wallet is unlocked. */
11
+ export class WalletCache {
12
+
13
+ private readonly assets = new Map<string, CachedAsset>();
14
+
15
+ public clear(): void {
16
+ this.assets.clear();
17
+ }
18
+
19
+ public getAsset(id: string): CachedAsset | undefined {
20
+ return this.assets.get(tokenIdToHex(id));
21
+ }
22
+
23
+ public setAsset(id: string, asset: CachedAsset): void {
24
+ this.assets.set(tokenIdToHex(id), asset);
25
+ }
26
+ }
@@ -26,7 +26,7 @@ export type WalletEvent =
26
26
  | { type: 'new_vault'; vault: VaultInfo; }
27
27
  | { type: 'sync_wallet'; loading: boolean; }
28
28
  | { type: 'clear_wallet'; }
29
- | { type: 'account_balance_updated'; accountId: number; balance: Balance, tokensBalance: Record<string, Balance>; }
29
+ | { type: 'account_balance_updated'; accountId: number; balance: Balance, tokensBalance: Record<string, Balance>; hasActivity: boolean; }
30
30
  | { type: 'vault_balance_updated'; address: string, balance: Balance; }
31
31
 
32
32
  export type WalletUpdateCallback = (event: WalletEvent) => void;
@@ -144,6 +144,13 @@ export class WalletManager {
144
144
  }));
145
145
  }
146
146
 
147
+ private hasActivity(accountId = HD_WALLET_ID): boolean {
148
+ if (accountId === HD_WALLET_ID) {
149
+ return this.receiveAddresses.some(a => a.used);
150
+ }
151
+ return Boolean(this.accounts.get(accountId)?.statusHash);
152
+ }
153
+
147
154
  /**
148
155
  * Switches to another server (or reconnects to the current one without `params`): saves it, disconnects, then
149
156
  * connects with `connect()`, retrying until it does. Check the server first with `RostrumService.checkInstance()`.
@@ -309,6 +316,7 @@ export class WalletManager {
309
316
  address: this.getReceiveAddress(),
310
317
  balance: sumBalance(walletAddresses.map(a => a.balance)),
311
318
  tokensBalance: sumTokensBalance(walletAddresses.map(a => a.tokensBalance)),
319
+ hasActivity: this.hasActivity(HD_WALLET_ID),
312
320
  sessions: {}
313
321
  }
314
322
  });
@@ -322,6 +330,7 @@ export class WalletManager {
322
330
  address: account.address,
323
331
  balance: account.balance,
324
332
  tokensBalance: account.tokensBalance,
333
+ hasActivity: this.hasActivity(account.id),
325
334
  sessions: {}
326
335
  }
327
336
  });
@@ -519,7 +528,13 @@ export class WalletManager {
519
528
  const walletBalance = sumBalance(walletAddresses.map(a => a.balance));
520
529
  const walletTokenBalances = sumTokensBalance(walletAddresses.map(a => a.tokensBalance));
521
530
 
522
- this.notify({ type: 'account_balance_updated', accountId: HD_WALLET_ID, balance: walletBalance, tokensBalance: walletTokenBalances });
531
+ this.notify({
532
+ type: 'account_balance_updated',
533
+ accountId: HD_WALLET_ID,
534
+ balance: walletBalance,
535
+ tokensBalance: walletTokenBalances,
536
+ hasActivity: this.hasActivity(HD_WALLET_ID),
537
+ });
523
538
 
524
539
  await this.postProcessActivity(HD_WALLET_ID, txHistory, walletAddresses.map(a => a.address), walletTokenBalances);
525
540
  }
@@ -533,7 +548,13 @@ export class WalletManager {
533
548
  for (const { address, txs } of history) {
534
549
  const account = address as AccountDTO;
535
550
 
536
- this.notify({ type: 'account_balance_updated', accountId: account.id, balance: account.balance, tokensBalance: account.tokensBalance });
551
+ this.notify({
552
+ type: 'account_balance_updated',
553
+ accountId: account.id,
554
+ balance: account.balance,
555
+ tokensBalance: account.tokensBalance,
556
+ hasActivity: this.hasActivity(account.id),
557
+ });
537
558
 
538
559
  const p = this.postProcessActivity(account.id, txs, [account.address], account.tokensBalance);
539
560
  activityPromises.push(p);
@@ -648,6 +669,7 @@ export class WalletManager {
648
669
  address: account.address,
649
670
  balance: account.balance,
650
671
  tokensBalance: account.tokensBalance,
672
+ hasActivity: this.hasActivity(account.id),
651
673
  sessions: {}
652
674
  }
653
675
  });
@@ -50,28 +50,21 @@ export interface AssetEntity {
50
50
  addedTime: number;
51
51
  }
52
52
 
53
- export interface TokenEntity {
54
- token: string;
53
+ /** Asset metadata as fetched from the assets API, shared by every account that holds the asset. */
54
+ export interface AssetMetadataEntity {
55
55
  tokenIdHex: string;
56
+ /** Copied out of `data`, only to sort lists by it. */
56
57
  name: string;
57
- ticker: string;
58
- iconUrl: string;
59
- decimals: number;
60
- parent: string;
58
+ /** The API response (an `AssetInfo`) as JSON. */
59
+ data: string;
60
+ /** The metadata version that wrote this row; older rows get refetched. */
61
+ version: number;
61
62
  }
62
63
 
63
- export interface NftEntity {
64
- token: string;
65
- tokenIdHex: string;
66
- name: string;
67
- parent: string;
68
- collection: string;
69
- series: string;
70
- author: string;
71
- public: string;
72
- front: string;
73
- back: string;
74
- thumb: string;
64
+ /** An account's asset joined with its metadata. A query result, not a stored table. */
65
+ export interface AssetDTO extends AssetEntity {
66
+ data: string;
67
+ version: number;
75
68
  }
76
69
 
77
70
  export interface SessionEntity {
@@ -25,6 +25,7 @@ export interface Account {
25
25
  address: string;
26
26
  balance: Balance;
27
27
  tokensBalance: Record<string, Balance>;
28
+ hasActivity: boolean;
28
29
  sessions: Record<string, SessionInfo>
29
30
  }
30
31
 
@@ -50,6 +51,7 @@ export interface TokenAsset {
50
51
  name: string;
51
52
  ticker: string;
52
53
  iconUrl: string;
54
+ icon: string;
53
55
  decimals: number;
54
56
  }
55
57
 
@@ -70,6 +72,15 @@ export type AssetInfo =
70
72
  | (AssetBase & { type: 'token'; data: TokenAsset })
71
73
  | (AssetBase & { type: 'nft'; data: NFTAsset });
72
74
 
75
+ /** An asset of an account, as listed in the wallet. */
76
+ export interface AccountAsset {
77
+ tokenIdHex: string;
78
+ type: AssetType;
79
+ addedTime: number;
80
+ /** Undefined only if the stored metadata is unreadable; it is refetched in the background. */
81
+ info?: AssetInfo;
82
+ }
83
+
73
84
  export interface MarketData {
74
85
  id: string;
75
86
  name: string;