-
-
Notifications
You must be signed in to change notification settings - Fork 288
Expand file tree
/
Copy pathMultichainTransactionsController.ts
More file actions
575 lines (513 loc) · 17.4 KB
/
Copy pathMultichainTransactionsController.ts
File metadata and controls
575 lines (513 loc) · 17.4 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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
import type {
AccountsControllerAccountAddedEvent,
AccountsControllerAccountRemovedEvent,
AccountsControllerListMultichainAccountsAction,
AccountsControllerAccountTransactionsUpdatedEvent,
} from '@metamask/accounts-controller';
import { BaseController } from '@metamask/base-controller';
import type {
ControllerGetStateAction,
ControllerStateChangeEvent,
} from '@metamask/base-controller';
import {
AccountActivityServiceTransactionUpdatedEvent,
Transaction as BackendTransactionUpdate,
} from '@metamask/core-backend';
import { isEvmAccountType, TransactionStatus } from '@metamask/keyring-api';
import type {
Transaction,
AccountTransactionsUpdatedEventPayload,
} from '@metamask/keyring-api';
import type { KeyringControllerGetStateAction } from '@metamask/keyring-controller';
import type { InternalAccount } from '@metamask/keyring-internal-api';
import { KeyringClient } from '@metamask/keyring-snap-client';
import type { Messenger } from '@metamask/messenger';
import type { SnapControllerHandleRequestAction } from '@metamask/snaps-controllers';
import type { SnapId } from '@metamask/snaps-sdk';
import { HandlerType } from '@metamask/snaps-utils';
import type { CaipChainId, Json, JsonRpcRequest } from '@metamask/utils';
import type { Draft } from 'immer';
import type { MultichainTransactionsControllerMethodActions } from './MultichainTransactionsController-method-action-types';
const controllerName = 'MultichainTransactionsController';
const MESSENGER_EXPOSED_METHODS = ['updateTransactionsForAccount'] as const;
/**
* Maps a backend WebSocket status string to a terminal keyring status, or
* `undefined` for non-terminal / unknown statuses (which are ignored).
*
* @param status - The status reported by the account-activity WebSocket.
* @returns The terminal {@link TransactionStatus}, or `undefined`.
*/
function toTerminalStatus(status: string): TransactionStatus | undefined {
const normalized = status.toLowerCase();
if (normalized === TransactionStatus.Confirmed) {
return TransactionStatus.Confirmed;
}
if (normalized === TransactionStatus.Failed) {
return TransactionStatus.Failed;
}
return undefined;
}
/**
* PaginationOptions
*
* Represents options for paginating transaction results
* limit - The maximum number of transactions to return
* next - The cursor for the next page of transactions, or null if there is no next page
*/
export type PaginationOptions = {
limit: number;
next?: string | null;
};
/**
* State used by the {@link MultichainTransactionsController} to cache account transactions.
*/
export type MultichainTransactionsControllerState = {
nonEvmTransactions: {
[accountId: string]: {
[chain: CaipChainId]: TransactionStateEntry;
};
};
};
/**
* Constructs the default {@link MultichainTransactionsController} state.
*
* @returns The default {@link MultichainTransactionsController} state.
*/
export function getDefaultMultichainTransactionsControllerState(): MultichainTransactionsControllerState {
return {
nonEvmTransactions: {},
};
}
/**
* Event emitted when a transaction is finalized.
*/
export type MultichainTransactionsControllerTransactionConfirmedEvent = {
type: `${typeof controllerName}:transactionConfirmed`;
payload: [Transaction];
};
/**
* Event emitted when a transaction is submitted.
*/
export type MultichainTransactionsControllerTransactionSubmittedEvent = {
type: `${typeof controllerName}:transactionSubmitted`;
payload: [Transaction];
};
/**
* Returns the state of the {@link MultichainTransactionsController}.
*/
export type MultichainTransactionsControllerGetStateAction =
ControllerGetStateAction<
typeof controllerName,
MultichainTransactionsControllerState
>;
/**
* Event emitted when the state of the {@link MultichainTransactionsController} changes.
*/
export type MultichainTransactionsControllerStateChange =
ControllerStateChangeEvent<
typeof controllerName,
MultichainTransactionsControllerState
>;
/**
* Actions exposed by the {@link MultichainTransactionsController}.
*/
export type MultichainTransactionsControllerActions =
| MultichainTransactionsControllerGetStateAction
| MultichainTransactionsControllerMethodActions;
/**
* Events emitted by {@link MultichainTransactionsController}.
*/
export type MultichainTransactionsControllerEvents =
| MultichainTransactionsControllerStateChange
| MultichainTransactionsControllerTransactionConfirmedEvent
| MultichainTransactionsControllerTransactionSubmittedEvent;
/**
* Messenger type for the MultichainTransactionsController.
*/
export type MultichainTransactionsControllerMessenger = Messenger<
typeof controllerName,
MultichainTransactionsControllerActions | AllowedActions,
MultichainTransactionsControllerEvents | AllowedEvents
>;
/**
* Actions that this controller is allowed to call.
*/
type AllowedActions =
| AccountsControllerListMultichainAccountsAction
| KeyringControllerGetStateAction
| SnapControllerHandleRequestAction;
/**
* Events that this controller is allowed to subscribe.
*/
type AllowedEvents =
| AccountsControllerAccountAddedEvent
| AccountsControllerAccountRemovedEvent
| AccountsControllerAccountTransactionsUpdatedEvent
| AccountActivityServiceTransactionUpdatedEvent;
/**
* {@link MultichainTransactionsController}'s metadata.
*
* This allows us to choose if fields of the state should be persisted or not
* using the `persist` flag; and if they can be sent to Sentry or not, using
* the `anonymous` flag.
*/
const multichainTransactionsControllerMetadata = {
nonEvmTransactions: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
};
/**
* The state of transactions for a specific chain.
*/
export type TransactionStateEntry = {
transactions: Transaction[];
next: string | null;
lastUpdated: number;
};
/**
* The MultichainTransactionsController is responsible for fetching and caching account
* transactions for non-EVM accounts.
*/
export class MultichainTransactionsController extends BaseController<
typeof controllerName,
MultichainTransactionsControllerState,
MultichainTransactionsControllerMessenger
> {
constructor({
messenger,
state,
}: {
messenger: MultichainTransactionsControllerMessenger;
state?: Partial<MultichainTransactionsControllerState>;
}) {
super({
messenger,
name: controllerName,
metadata: multichainTransactionsControllerMetadata,
state: {
...getDefaultMultichainTransactionsControllerState(),
...state,
},
});
this.messenger.registerMethodActionHandlers(
this,
MESSENGER_EXPOSED_METHODS,
);
// Fetch initial transactions for all non-EVM accounts
for (const account of this.#listAccounts()) {
this.updateTransactionsForAccount(account.id).catch((error) => {
console.error(
`Failed to fetch initial transactions for account ${account.id}:`,
error,
);
});
}
this.messenger.subscribe(
'AccountsController:accountAdded',
(account: InternalAccount) => this.#handleOnAccountAdded(account),
);
this.messenger.subscribe(
'AccountsController:accountRemoved',
(accountId: string) => this.#handleOnAccountRemoved(accountId),
);
this.messenger.subscribe(
'AccountsController:accountTransactionsUpdated',
(transactionsUpdate: AccountTransactionsUpdatedEventPayload) =>
this.#handleOnAccountTransactionsUpdated(transactionsUpdate),
);
// Client-owned terminal tracking: flip pending (Submitted) non-EVM entries to
// Confirmed/Failed from the account-activity WebSocket, replacing the snap's
// former confirmation tracking (see snap-transactions offload, ticket 5).
this.messenger.subscribe(
'AccountActivityService:transactionUpdated',
(update) => this.#handleOnBackendTransactionUpdated(update),
);
}
/**
* Lists the multichain accounts coming from the `AccountsController`.
*
* @returns A list of multichain accounts.
*/
#listMultichainAccounts(): InternalAccount[] {
return this.messenger.call('AccountsController:listMultichainAccounts');
}
/**
* Lists the accounts that we should get transactions for.
*
* @returns A list of accounts that we should get transactions for.
*/
#listAccounts(): InternalAccount[] {
const accounts = this.#listMultichainAccounts();
return accounts.filter((account) => this.#isNonEvmAccount(account));
}
/**
* Gets transactions for an account.
*
* @param accountId - The ID of the account to get transactions for.
* @param snapId - The ID of the snap that manages the account.
* @param pagination - Options for paginating transaction results.
* @returns A promise that resolves to the transaction data and pagination info.
*/
async #getTransactions(
accountId: string,
snapId: string,
pagination: PaginationOptions,
): Promise<{
data: Transaction[];
next: string | null;
}> {
return await this.#getClient(snapId).listAccountTransactions(
accountId,
pagination,
);
}
/**
* Updates transactions for a specific account. This is used for the initial fetch
* when an account is first added.
*
* @param accountId - The ID of the account to get transactions for.
*/
async updateTransactionsForAccount(accountId: string) {
const { isUnlocked } = this.messenger.call('KeyringController:getState');
if (!isUnlocked) {
return;
}
try {
const account = this.#listAccounts().find(
(accountItem) => accountItem.id === accountId,
);
if (account?.metadata.snap) {
const response = await this.#getTransactions(
account.id,
account.metadata.snap.id,
{ limit: 10 },
);
const transactionsByChain: Record<CaipChainId, Transaction[]> = {};
response.data.forEach((transaction) => {
const { chain } = transaction;
if (!transactionsByChain[chain]) {
transactionsByChain[chain] = [];
}
transactionsByChain[chain].push(transaction);
});
const chainUpdates = Object.entries(transactionsByChain).map(
([chain, transactions]) => ({
chain,
entry: {
transactions,
next: response.next,
lastUpdated: Date.now(),
},
}),
);
this.update((state: Draft<MultichainTransactionsControllerState>) => {
if (!state.nonEvmTransactions[account.id]) {
state.nonEvmTransactions[account.id] = {};
}
chainUpdates.forEach(({ chain, entry }) => {
state.nonEvmTransactions[account.id][chain as CaipChainId] = entry;
});
});
}
} catch (error) {
console.error(
`Failed to fetch transactions for account ${accountId}:`,
error,
);
}
}
/**
* Checks for non-EVM accounts.
*
* @param account - The new account to be checked.
* @returns True if the account is a non-EVM account, false otherwise.
*/
#isNonEvmAccount(account: InternalAccount): boolean {
return (
!isEvmAccountType(account.type) &&
// Non-EVM accounts are backed by a Snap for now
account.metadata.snap !== undefined
);
}
/**
* Handles changes when a new account has been added.
*
* @param account - The new account being added.
*/
async #handleOnAccountAdded(account: InternalAccount) {
if (!this.#isNonEvmAccount(account)) {
return;
}
await this.updateTransactionsForAccount(account.id);
}
/**
* Handles changes when a new account has been removed.
*
* @param accountId - The account ID being removed.
*/
async #handleOnAccountRemoved(accountId: string) {
if (accountId in this.state.nonEvmTransactions) {
this.update((state: Draft<MultichainTransactionsControllerState>) => {
delete state.nonEvmTransactions[accountId];
});
}
}
/**
* Publishes transaction update events.
*
* @param updatedTransaction - The updated transaction.
*/
#publishTransactionUpdateEvent(updatedTransaction: Transaction) {
if (updatedTransaction.status === TransactionStatus.Confirmed) {
this.messenger.publish(
'MultichainTransactionsController:transactionConfirmed',
updatedTransaction,
);
}
if (updatedTransaction.status === TransactionStatus.Submitted) {
this.messenger.publish(
'MultichainTransactionsController:transactionSubmitted',
updatedTransaction,
);
}
}
/**
* Handles transaction updates received from the AccountsController.
*
* @param transactionsUpdate - The transaction update event containing new transactions.
*/
#handleOnAccountTransactionsUpdated(
transactionsUpdate: AccountTransactionsUpdatedEventPayload,
): void {
const updatedTransactions: Record<
string,
Record<CaipChainId, Transaction[]>
> = {};
const transactionsToPublish: Transaction[] = [];
if (!transactionsUpdate?.transactions) {
return;
}
Object.entries(transactionsUpdate.transactions).forEach(
([accountId, newTransactions]) => {
updatedTransactions[accountId] = {};
newTransactions.forEach((tx) => {
const { chain } = tx;
if (!updatedTransactions[accountId][chain]) {
updatedTransactions[accountId][chain] = [];
}
updatedTransactions[accountId][chain].push(tx);
transactionsToPublish.push(tx);
});
Object.entries(updatedTransactions[accountId]).forEach(
([chain, chainTransactions]) => {
// Account might not have any transactions yet, so use `[]` in that case.
const oldTransactions =
this.state.nonEvmTransactions[accountId]?.[chain as CaipChainId]
?.transactions ?? [];
// Uses a `Map` to deduplicate transactions by ID, ensuring we keep the latest version
// of each transaction while preserving older transactions and transactions from other accounts.
// Transactions are sorted by timestamp (newest first).
const transactions = new Map();
oldTransactions.forEach((tx) => {
transactions.set(tx.id, tx);
});
chainTransactions.forEach((tx) => {
transactions.set(tx.id, tx);
});
// Sorted by timestamp (newest first). If the timestamp is not provided, those
// transactions will be put in the end of this list.
updatedTransactions[accountId][chain as CaipChainId] = Array.from(
transactions.values(),
).sort((a, b) => (b.timestamp ?? 0) - (a.timestamp ?? 0));
},
);
},
);
this.update((state) => {
Object.entries(updatedTransactions).forEach(([accountId, chainsData]) => {
if (!state.nonEvmTransactions[accountId]) {
state.nonEvmTransactions[accountId] = {};
}
Object.entries(chainsData).forEach(([chain, transactions]) => {
state.nonEvmTransactions[accountId][chain as CaipChainId] = {
transactions,
next: null,
lastUpdated: Date.now(),
};
});
});
});
// After we update the state, publish the events for new/updated transactions
transactionsToPublish.forEach((tx) => {
this.#publishTransactionUpdateEvent(tx);
});
}
/**
* Handles a transaction status update from the account-activity WebSocket.
*
* Finds the matching pending entry (by chain-specific id) and flips it to the
* reported terminal status. Non-terminal updates and unknown transactions are
* ignored.
*
* @param update - The backend transaction update.
*/
#handleOnBackendTransactionUpdated(update: BackendTransactionUpdate): void {
const terminalStatus = toTerminalStatus(update.status);
if (!terminalStatus) {
return;
}
let location:
| { accountId: string; chain: CaipChainId; existing: Transaction }
| undefined;
for (const [accountId, chains] of Object.entries(
this.state.nonEvmTransactions,
)) {
for (const [chain, entry] of Object.entries(chains)) {
const existing = entry.transactions.find((tx) => tx.id === update.id);
if (existing) {
location = { accountId, chain: chain as CaipChainId, existing };
break;
}
}
if (location) {
break;
}
}
if (!location || location.existing.status === terminalStatus) {
return;
}
const { accountId, chain } = location;
const updatedTransaction: Transaction = {
...location.existing,
status: terminalStatus,
};
this.update((state) => {
const entry = state.nonEvmTransactions[accountId][chain];
entry.transactions = entry.transactions.map((tx) =>
tx.id === update.id ? updatedTransaction : tx,
);
entry.lastUpdated = Date.now();
});
this.#publishTransactionUpdateEvent(updatedTransaction);
}
/**
* Gets a `KeyringClient` for a Snap.
*
* @param snapId - ID of the Snap to get the client for.
* @returns A `KeyringClient` for the Snap.
*/
#getClient(snapId: string): KeyringClient {
return new KeyringClient({
send: async (request: JsonRpcRequest) =>
(await this.messenger.call('SnapController:handleRequest', {
snapId: snapId as SnapId,
origin: 'metamask',
handler: HandlerType.OnKeyringRequest,
request,
})) as Promise<Json>,
});
}
}