-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathTransactionsService.ts
More file actions
515 lines (449 loc) · 15.3 KB
/
Copy pathTransactionsService.ts
File metadata and controls
515 lines (449 loc) · 15.3 KB
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
import {
KeyringEvent,
type CaipAssetType,
type Transaction,
} from '@metamask/keyring-api';
import { emitSnapKeyringEvent } from '@metamask/keyring-snap-sdk';
import {
address as asAddress,
type Address,
type Signature,
} from '@solana/kit';
import type { SolanaKeyringAccount } from '../../../domain';
import { Network } from '../../constants/solana';
import type { ILogger } from '../../utils/logger';
import type { ConfigProvider } from '../config';
import type { SolanaConnection } from '../connection';
import type { IStateManager } from '../state/IStateManager';
import type { UnencryptedStateValue } from '../state/State';
import type { TokenMetadataService } from '../token-metadata/TokenMetadata';
import type { SignatureMapping } from './types';
import { mapRpcTransaction } from './utils/mapRpcTransaction';
export class TransactionsService {
readonly #connection: SolanaConnection;
readonly #logger: ILogger;
readonly #tokenMetadataService: TokenMetadataService;
readonly #state: IStateManager<UnencryptedStateValue>;
readonly #configProvider: ConfigProvider;
constructor({
logger,
connection,
tokenMetadataService,
state,
configProvider,
}: {
logger: ILogger;
connection: SolanaConnection;
tokenMetadataService: TokenMetadataService;
state: IStateManager<UnencryptedStateValue>;
configProvider: ConfigProvider;
}) {
this.#connection = connection;
this.#tokenMetadataService = tokenMetadataService;
this.#logger = logger;
this.#state = state;
this.#configProvider = configProvider;
}
async fetchLatestAddressTransactions(address: Address, limit: number) {
const scopes = this.#configProvider.get().activeNetworks;
const transactions = (
await Promise.all(
scopes.map(async (scope) =>
this.#fetchAddressTransactions(scope, address, {
limit,
}),
),
)
)
.flatMap(({ data }) => data)
.sort((a, b) => (b.timestamp ?? 0) - (a.timestamp ?? 0));
return transactions;
}
async #fetchAddressTransactions(
scope: Network,
address: Address,
pagination: { limit: number; next?: Signature | null },
): Promise<{
data: Transaction[];
next: Signature | null;
}> {
/**
* First get signatures
*/
const signatures = (
await this.#connection
.getRpc(scope)
.getSignaturesForAddress(
address,
pagination.next
? {
limit: pagination.limit,
before: pagination.next,
}
: { limit: pagination.limit },
)
.send()
).map(({ signature }) => signature);
const existingSinatures =
(await this.#state.getKey<Signature[]>(`signatures.${address}`)) ?? [];
await this.#state.setKey(`signatures.${address}`, [
...new Set([...existingSinatures, ...signatures]),
]);
/**
* Now fetch their transaction data
*/
const transactionsData = await this.getTransactionsDataFromSignatures({
scope,
signatures,
});
/**
* Map it to the expected format from the Keyring API
*/
const mappedTransactionsData = transactionsData.reduce<Transaction[]>(
(transactions, transactionData) => {
const mappedTransaction = mapRpcTransaction({
scope,
address,
transactionData,
});
/**
* Filter out unmapped transactions
*/
if (mappedTransaction) {
transactions.push(mappedTransaction);
}
return transactions;
},
[],
);
const transactionsByAccountWithTokenMetadata =
await this.#populateAccountTransactionAssetUnits({
[address]: mappedTransactionsData.map((tx) => ({
...tx,
account: address,
})),
});
const next =
signatures.length === pagination.limit
? (signatures[signatures.length - 1] ?? null) // eslint-disable-line prettier/prettier
: null;
return {
data: transactionsByAccountWithTokenMetadata[address] ?? [],
next,
};
}
async fetchLatestSignatures(
scope: Network,
address: Address,
limit: number,
): Promise<Signature[]> {
this.#logger.log(
`[TransactionsService.fetchAllSignatures] Fetching all signatures for ${address} on ${scope}`,
);
const signatureResponses = await this.#connection
.getRpc(scope)
.getSignaturesForAddress(address, {
limit,
})
.send();
const signatures = signatureResponses.map(({ signature }) => signature);
const existingSinatures =
(await this.#state.getKey<Signature[]>(`signatures.${address}`)) ?? [];
await this.#state.setKey(`signatures.${address}`, [
...new Set([...existingSinatures, ...signatures]),
]);
return signatures;
}
async getTransactionsDataFromSignatures({
scope,
signatures,
}: {
scope: Network;
signatures: Signature[];
}) {
const transactionsData = await Promise.all(
signatures.map(async (signature) =>
this.#connection
.getRpc(scope)
.getTransaction(signature, {
maxSupportedTransactionVersion: 0,
})
.send(),
),
);
return transactionsData;
}
/**
* Fetches transactions for all accounts in the keyring and updates the state accordingly. Also emits events for any changes.
* @param accounts - The accounts to refresh transactions for.
*/
async refreshTransactions(accounts: SolanaKeyringAccount[]) {
try {
this.#logger.log(
`[TransactionsService] Refreshing transactions for ${accounts.length} accounts`,
);
if (!accounts.length) {
this.#logger.log('[TransactionsService] No accounts found');
return;
}
const scopes = this.#configProvider.get().activeNetworks;
const transactionsByAccount =
(await this.#state.getKey<UnencryptedStateValue['transactions']>(
'transactions',
)) ?? {};
const existingSignatures = this.#mapExistingSignaturesSet(
transactionsByAccount,
);
const newSignaturesMapping = await this.#collectNewTransactionSignatures({
scopes,
accounts,
existingSignatures,
});
const newTransactionsByAccount =
await this.#fetchAndMapTransactionsPerAccount({
scopes,
accounts,
newSignaturesMapping,
});
const newTransactionsByAccountWithTokenMetadata =
await this.#populateAccountTransactionAssetUnits(
newTransactionsByAccount,
);
await emitSnapKeyringEvent(
snap,
KeyringEvent.AccountTransactionsUpdated,
{
transactions: newTransactionsByAccountWithTokenMetadata,
},
);
const updatedTransactionsByAccount = this.#mergeSortAndTrimTransactions({
accounts,
previousTransactionsByAccount: transactionsByAccount,
newTransactionsByAccount,
});
await this.#state.setKey('transactions', updatedTransactionsByAccount);
} catch (error) {
this.#logger.error(
'[TransactionsService] Error. Releasing lock...',
error,
);
}
}
/**
* Creates a Set of existing transaction signatures for quick lookup.
* @param transactions - The current state's transactions record, mapping account IDs to their transactions.
* @returns A Set containing all existing transaction signatures.
*/
#mapExistingSignaturesSet(
transactions: Record<string, Transaction[]>,
): Set<string> {
return new Set(
Object.values(transactions ?? {})
.flat()
.map((tx) => tx.id),
);
}
/**
* Fetches and collects new transaction signatures for all accounts across networks.
* @param params - Parameters for fetching signatures.
* @param params.accounts - List of accounts to fetch signatures for.
* @param params.scopes - List of networks to check.
* @param params.existingSignatures - Set of already known signatures.
* @returns Mapping of new signatures by network and account.
*/
async #collectNewTransactionSignatures({
scopes = [Network.Mainnet, Network.Devnet],
accounts,
existingSignatures,
}: {
scopes?: Network[];
accounts: SolanaKeyringAccount[];
existingSignatures: Set<string>;
}): Promise<SignatureMapping> {
const newSignaturesMapping: SignatureMapping = {
byNetwork: new Map(scopes.map((scope) => [scope, new Set<string>()])),
byAccountAndNetwork: new Map(
accounts.map((account) => [
account.id,
new Map(scopes.map((scope) => [scope, new Set<string>()])),
]),
),
};
/**
* For each account and network, fetch the latest signatures and take note of the
* ones we need to fetch data for.
*/
for (const account of accounts) {
for (const scope of scopes) {
this.#logger.log(
`[TransactionsService] Fetching signatures for ${account.address} on ${scope}...`,
);
const signatures = await this.fetchLatestSignatures(
scope,
asAddress(account.address),
this.#configProvider.get().transactions.storageLimit,
);
/**
* Filter out existing signatures and store new ones
*/
const newSignatures = signatures.filter(
(signature) => !existingSignatures.has(signature),
);
if (!newSignatures.length) {
this.#logger.log(
`[TransactionsService] Found 0 new signatures out of ${signatures.length} total for address ${account.address} on network ${scope}`,
);
continue;
}
const networkSet = newSignaturesMapping.byNetwork.get(
scope,
) as Set<string>;
const accountMap = newSignaturesMapping.byAccountAndNetwork.get(
account.id,
) as Map<Network, Set<string>>;
const accountNetworkSet = accountMap.get(scope) as Set<string>;
newSignatures.forEach((signature) => {
networkSet.add(signature);
accountNetworkSet.add(signature);
});
this.#logger.info(
`[TransactionsService] Found ${newSignatures.length} new signatures (${signatures.length} total) for ${account.address} on ${scope}`,
);
}
}
return newSignaturesMapping;
}
/**
* Fetches and maps transactions for all accounts on a per-network basis.
* @param params - Parameters for fetching and mapping transactions.
* @param params.scopes - List of networks to process.
* @param params.accounts - List of accounts to process.
* @param params.newSignaturesMapping - Mapping of signatures by network and account.
* @returns Updated transactions record.
*/
async #fetchAndMapTransactionsPerAccount({
scopes = [Network.Mainnet, Network.Devnet],
accounts,
newSignaturesMapping,
}: {
scopes?: Network[];
accounts: SolanaKeyringAccount[];
newSignaturesMapping: SignatureMapping;
}): Promise<Record<string, Transaction[]>> {
const newTransactions: Record<string, Transaction[]> = {};
for (const scope of scopes) {
const networkSet = newSignaturesMapping.byNetwork.get(
scope,
) as Set<string>;
if (!networkSet.size) {
continue;
}
const networkSignatures = Array.from(networkSet);
const transactionsData = await this.getTransactionsDataFromSignatures({
scope,
signatures: networkSignatures as Signature[],
});
// Map fetched transactions to their respective accounts
for (const account of accounts) {
if (!newTransactions[account.id]) {
newTransactions[account.id] = [];
}
const accountMap = newSignaturesMapping.byAccountAndNetwork.get(
account.id,
) as Map<Network, Set<string>>;
const accountNetworkSet = accountMap.get(scope) as Set<string>;
const accountTransactions = transactionsData
.filter((txData) => {
const signature = txData?.transaction?.signatures[0];
return signature && accountNetworkSet.has(signature);
})
.map((txData) => {
const mappedTx = mapRpcTransaction({
scope,
address: account.address as Address,
transactionData: txData,
});
if (!mappedTx) {
return null;
}
return {
...mappedTx,
account: account.id,
};
})
.filter((tx): tx is Transaction => tx !== null);
newTransactions[account.id]?.push(...accountTransactions);
}
}
return newTransactions;
}
/**
* Merges and sorts transactions for all accounts.
* @param options - Options for merging and sorting transactions.
* @param options.accounts - List of accounts to process.
* @param options.previousTransactionsByAccount - Previous transactions by account.
* @param options.newTransactionsByAccount - New transactions by account.
* @returns Updated transactions record.
*/
#mergeSortAndTrimTransactions({
accounts,
previousTransactionsByAccount,
newTransactionsByAccount,
}: {
accounts: SolanaKeyringAccount[];
previousTransactionsByAccount: Record<string, Transaction[]>;
newTransactionsByAccount: Record<string, Transaction[]>;
}): Record<string, Transaction[]> {
return Object.fromEntries(
accounts.map((account) => [
account.id,
[
...(previousTransactionsByAccount[account.id] ?? []),
...(newTransactionsByAccount[account.id] ?? []),
]
.sort((a, b) => (a.timestamp ?? 0) - (b.timestamp ?? 0))
.slice(0, this.#configProvider.get().transactions.storageLimit),
]),
);
}
/**
* Populate token metadata on the `from` and `to` arrays of each transaction.
* 1. Go through each `from` and `to` element and collect all CAIP 19 IDs for the assets that we need metadata for.
* 2. Fetch the metadata for this array of CAIP 19 IDs.
* 3. Map the metadata to the `from` and `to` arrays.
* @param transactionsByAccount - Array of mapped transactions to populate with token metadata.
* @returns Array of transactions with populated token metadata.
*/
async #populateAccountTransactionAssetUnits(
transactionsByAccount: Record<string, Transaction[]>,
) {
const caip19Ids = [
...new Set(
Object.values(transactionsByAccount).flatMap((transactions) =>
transactions.flatMap(({ from, to }) =>
[...from, ...to]
.filter((item) => item.asset?.fungible)
.map((item) => (item.asset as { type: CaipAssetType }).type),
),
),
),
];
const tokenMetadata =
await this.#tokenMetadataService.getTokensMetadata(caip19Ids);
Object.keys(transactionsByAccount).forEach((accountId) => {
transactionsByAccount[accountId]?.forEach((transaction) => {
transaction.from.forEach((from) => {
if (from.asset?.fungible && tokenMetadata[from.asset.type]) {
from.asset.unit = tokenMetadata[from.asset.type]?.symbol ?? '';
}
});
transaction.to.forEach((to) => {
if (to.asset?.fungible && tokenMetadata[to.asset.type]) {
to.asset.unit = tokenMetadata[to.asset.type]?.symbol ?? '';
}
});
});
});
return transactionsByAccount;
}
}