generated from MetaMask/metamask-module-template
-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathSnapKeyring.ts
More file actions
1695 lines (1544 loc) · 51.8 KB
/
SnapKeyring.ts
File metadata and controls
1695 lines (1544 loc) · 51.8 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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { TypedTransaction } from '@ethereumjs/tx';
import { TransactionFactory } from '@ethereumjs/tx';
import type { TypedDataV1, TypedMessage } from '@metamask/eth-sig-util';
import { SignTypedDataVersion } from '@metamask/eth-sig-util';
import type {
KeyringAccount,
KeyringExecutionContext,
BtcMethod,
EthBaseTransaction,
EthBaseUserOperation,
EthUserOperation,
EthUserOperationPatch,
ResolvedAccountAddress,
CaipChainId,
MetaMaskOptions,
KeyringResponse,
CreateAccountOptions,
} from '@metamask/keyring-api';
import {
EthBytesStruct,
EthMethod,
EthBaseUserOperationStruct,
EthUserOperationPatchStruct,
isEvmAccountType,
KeyringEvent,
AccountAssetListUpdatedEventStruct,
AccountBalancesUpdatedEventStruct,
AccountTransactionsUpdatedEventStruct,
AnyAccountType,
} from '@metamask/keyring-api';
import type { InternalAccount } from '@metamask/keyring-internal-api';
import { toKeyringRequestWithoutOrigin } from '@metamask/keyring-internal-api';
import { KeyringInternalSnapClient } from '@metamask/keyring-internal-snap-client';
import {
type GetSelectedAccountsResponse,
GetSelectedAccountsRequestStruct,
SnapManageAccountsMethod,
} from '@metamask/keyring-snap-sdk';
import type { AccountId, JsonRpcRequest } from '@metamask/keyring-utils';
import { strictMask } from '@metamask/keyring-utils';
import type { ExtractEventPayload } from '@metamask/messenger';
import type { SnapId } from '@metamask/snaps-sdk';
import { type Snap } from '@metamask/snaps-utils';
import { assert, mask, object, string } from '@metamask/superstruct';
import type { Hex, Json, SemVerVersion } from '@metamask/utils';
import {
bigIntToHex,
hasProperty,
KnownCaipNamespace,
toCaipChainId,
} from '@metamask/utils';
import { v4 as uuid } from 'uuid';
import { transformAccount } from './account';
import { DeferredPromise } from './DeferredPromise';
import {
AccountCreatedEventStruct,
AccountUpdatedEventStruct,
AccountDeletedEventStruct,
RequestApprovedEventStruct,
RequestRejectedEventStruct,
} from './events';
import { projectLogger as log } from './logger';
import { isAccountV1, migrateAccountV1 } from './migrations';
import {
getInternalOptionsOf,
type SnapKeyringInternalOptions,
} from './options';
import { PLATFORM_VERSION_FOR_KEYRING_REQUEST_WITH_ORIGIN } from './platform-versions';
import { SnapIdMap } from './SnapIdMap';
import type {
SnapKeyringEvents,
SnapKeyringMessenger,
} from './SnapKeyringMessenger';
import { SNAP_KEYRING_NAME } from './SnapKeyringMessenger';
import type { SnapMessage } from './types';
import { SnapMessageStruct } from './types';
import {
equalsIgnoreCase,
sanitizeUrl,
throwError,
toJson,
unique,
} from './util';
export const SNAP_KEYRING_TYPE = 'Snap Keyring';
// TODO: to be removed when this is added to the keyring-api
type AccountMethod = EthMethod | BtcMethod;
/**
* Snap keyring state.
*
* This state is persisted by the keyring controller and passed to the Snap
* keyring when it's created.
*/
export type KeyringState = {
accounts: Record<string, { account: KeyringAccount; snapId: SnapId }>;
};
/**
* Snap keyring callbacks.
*
* These callbacks are used to interact with other components.
*/
export type SnapKeyringCallbacks = {
saveState: () => Promise<void>;
addressExists(address: string): Promise<boolean>;
addAccount(
address: string,
snapId: SnapId,
handleUserInput: (accepted: boolean) => Promise<void>,
onceSaved: Promise<AccountId>,
accountNameSuggestion?: string,
internalOptions?: SnapKeyringInternalOptions,
): Promise<void>;
removeAccount(
address: string,
snapId: SnapId,
handleUserInput: (accepted: boolean) => Promise<void>,
): Promise<void>;
redirectUser(snapId: SnapId, url: string, message: string): Promise<void>;
};
/**
* Callback type to filter unknown account ID from a mapping account ID mapping.
*/
type FilterAccountIdFunction = <Entry>(
accountMapping: Record<AccountId, Entry>,
) => Record<AccountId, Entry>;
/**
* Normalize account's address.
*
* @param account - The account.
* @returns The normalized account address.
*/
function normalizeAccountAddress(account: KeyringAccount): string {
// FIXME: Is it required to lowercase the address here? For now we'll keep this behavior
// only for Ethereum addresses and use the original address for other non-EVM accounts.
// For example, Solana addresses are case-sensitives.
return isEvmAccountType(account.type)
? account.address.toLowerCase()
: account.address;
}
/**
* Keyring bridge implementation to support Snaps.
*/
export class SnapKeyring {
static type: string = SNAP_KEYRING_TYPE;
type: string;
// Name and state are required for modular initialisation.
name: typeof SNAP_KEYRING_NAME = SNAP_KEYRING_NAME;
state = null;
/**
* Messenger to dispatch requests to the Snaps controller.
*/
readonly #messenger: SnapKeyringMessenger;
/**
* Client used to call the Snap keyring.
*/
readonly #snapClient: KeyringInternalSnapClient;
/**
* Mapping between account IDs and an object that contains the associated
* account object and Snap ID.
*/
#accounts: SnapIdMap<{
account: KeyringAccount;
snapId: SnapId;
}>;
/**
* Mapping between Snap IDs and the selected accounts.
*/
readonly #selectedAccounts: Map<SnapId, AccountId[]>;
/**
* Mapping between request IDs and their deferred promises.
*/
readonly #requests: SnapIdMap<{
promise: DeferredPromise<any>;
snapId: SnapId;
}>;
/**
* Mapping between internal options, a correlation ID and a Snap ID.
*/
readonly #options: SnapIdMap<{
options: SnapKeyringInternalOptions;
snapId: SnapId;
// TODO: Add TTL to avoid having too many "leaking" internal options.
}>;
/**
* Callbacks used to interact with other components.
*/
readonly #callbacks: SnapKeyringCallbacks;
/**
* Whether to allow the creation and update of generic accounts.
*
* Account deletion is not affected by this flag and is always allowed.
*/
readonly #isAnyAccountTypeAllowed: boolean;
/**
* Create a new Snap keyring.
*
* @param options - Constructor options.
* @param options.messenger - Snap keyring messenger.
* @param options.callbacks - Callbacks used to interact with other components.
* @param options.isAnyAccountTypeAllowed - Whether to allow the `AnyAccountType` generic account type.
* @returns A new Snap keyring.
*/
constructor({
messenger,
callbacks,
isAnyAccountTypeAllowed = false,
}: {
messenger: SnapKeyringMessenger;
callbacks: SnapKeyringCallbacks;
isAnyAccountTypeAllowed?: boolean;
}) {
this.type = SnapKeyring.type;
this.#messenger = messenger;
this.#snapClient = new KeyringInternalSnapClient({ messenger });
this.#requests = new SnapIdMap();
this.#accounts = new SnapIdMap();
this.#options = new SnapIdMap();
this.#callbacks = callbacks;
this.#isAnyAccountTypeAllowed = isAnyAccountTypeAllowed;
this.#selectedAccounts = new Map();
}
/**
* Checks whether a Snap meets a minimum platform version.
*
* @param snapId - The Snap ID.
* @param platformVersion - Platform version to check.
* @returns True if the Snap meets the minimum version, false otherwise.
*/
#isMinimumPlatformVersion(
snapId: SnapId,
platformVersion: SemVerVersion,
): boolean {
return this.#messenger.call(
'SnapController:isMinimumPlatformVersion',
snapId,
platformVersion,
);
}
/**
* Get internal options given a correlation ID.
*
* NOTE: The associated options will be deleted automatically.
*
* @param snapId - Snap ID
* @param correlationId - Correlation ID associated with the internal options.
* @returns Internal options if found, `undefined` otherwise.
*/
#getInternalOptions(
snapId: SnapId,
correlationId: string | undefined,
): SnapKeyringInternalOptions | undefined {
if (correlationId) {
// We still need to check if the correlation ID is valid and associated to
// some internal options.
//
// NOTE: `found` will be `undefined` if a Snap tried to use a correlation ID that
// belongs to another Snap ID. However, if a Snap starts 2 parallel flow (which
// will results in 2 different correlation IDs), we won't be able to prevent
// the Snap from swapping/mixing up those correlation IDs he owns.
const found = this.#options.pop(snapId, correlationId);
if (found) {
return found.options;
}
console.warn(
`SnapKeyring - Received unmapped correlation ID: "${correlationId}"`,
);
}
return undefined;
}
/**
* Handle an Account Created event from a Snap.
*
* @param snapId - Snap ID.
* @param message - Event message.
* @returns `null`.
*/
async #handleAccountCreated(
snapId: SnapId,
message: SnapMessage,
): Promise<null> {
assert(message, AccountCreatedEventStruct);
const {
metamask, // Used for internal options.
account: newAccountFromEvent,
accountNameSuggestion,
displayAccountNameSuggestion,
displayConfirmation,
} = message.params;
// READ THIS CAREFULLY:
// ------------------------------------------------------------------------
// The account creation flow is now asynchronous. We expect the Snap to
// first create the account data and then fire the "AccountCreated" event.
// Potentially migrate the account.
const account = transformAccount(newAccountFromEvent);
const address = normalizeAccountAddress(account);
// The `AnyAccountType.Account` generic account type is allowed only during
// development, so we check whether it's allowed before continuing.
if (
!this.#isAnyAccountTypeAllowed &&
account.type === AnyAccountType.Account
) {
throw new Error(`Cannot create generic account '${account.id}'`);
}
// This is idempotent, so we need to check whether the account already exists
// and that the right Snap is trying to "create" it again.
const accountEntry = this.#accounts.get(snapId, account.id);
if (
accountEntry &&
normalizeAccountAddress(accountEntry.account) === address
) {
// NOTE: We are not checking account object equality here. If a Snap
// re-send this event with different account data, we will ignore it.
return null;
}
// The UI still uses the account address to identify accounts, so we need
// to block the creation of duplicate accounts for now to prevent accounts
// from being overwritten.
if (await this.#callbacks.addressExists(address)) {
throw new Error(`Account address '${address}' already exists`);
}
// A Snap could try to create an account with a different address but with
// an existing ID, so the above test only is not enough.
if (this.#accounts.has(snapId, account.id)) {
throw new Error(`Account '${account.id}' already exists`);
}
// A deferred promise that will be resolved once the Snap keyring has saved
// its internal state.
// This part of the flow is run asynchronously, so we have no other way of
// letting the MetaMask client that this "save" has been run.
// NOTE: Another way of fixing that could be to rely on events through the
// messenger maybe?
const onceSaved = new DeferredPromise<AccountId>();
// Add the account to the keyring, but wait for the MetaMask client to
// approve the account creation first.
await this.#callbacks.addAccount(
address,
snapId,
// This callback is passed to the MetaMask client, it will be called whenever
// the end user will accept or not the account creation.
async (accepted: boolean) => {
if (accepted) {
// We consider the account to be created on the Snap keyring only if
// the user accepted it. Meaning that the Snap MIGHT HAVE created the
// account on its own state, but the Snap keyring MIGHT NOT HAVE it yet.
//
// e.g The account creation dialog crashed on MetaMask, this callback
// will never be called, but the Snap still has the account.
this.#accounts.set(account.id, { account, snapId });
// This is the "true async part". We do not `await` for this call, mainly
// because this callback will persist the account on the client side
// (through the `AccountsController`).
//
// Since this will happen after the Snap account creation and Snap
// event, if anything goes wrong, we will delete the account by
// calling `deleteAccount` on the Snap.
// eslint-disable-next-line no-void
void this.#callbacks
.saveState()
.then(() => {
// This allows the MetaMask client to be "notified" when then
// Snap keyring has truly persisted its state. From there, we should
// be able to use the account (e.g. to display account creation
// confirmation dialogs).
onceSaved.resolve(account.id);
})
.catch(async (error) => {
// FIXME: There's a potential race condition here, if the Snap did
// not persist the account yet (this should mostly be for older Snaps).
await this.#deleteAccount(snapId, account);
// This allows the MetaMask client to be "notified" that something went
// wrong with the Snap keyring. (e.g. useful to display account creation
// error dialogs).
onceSaved.reject(error);
});
}
},
onceSaved.promise,
accountNameSuggestion,
getInternalOptionsOf([
// 1. We use the internal options from the Snap keyring.
this.#getInternalOptions(snapId, metamask?.correlationId) ?? {},
// 2. We use the ones coming from the Snap.
{
displayConfirmation,
displayAccountNameSuggestion,
},
]),
);
return null;
}
/**
* Handle an Account Updated event from a Snap.
*
* @param snapId - Snap ID.
* @param message - Event message.
* @returns `null`.
*/
async #handleAccountUpdated(
snapId: SnapId,
message: SnapMessage,
): Promise<null> {
assert(message, AccountUpdatedEventStruct);
const { account: newAccountFromEvent } = message.params;
const { account: oldAccount } =
this.#accounts.get(snapId, newAccountFromEvent.id) ??
throwError(`Account '${newAccountFromEvent.id}' not found`);
// Potentially migrate the account.
const newAccount = transformAccount(newAccountFromEvent);
// The `AnyAccountType.Account` generic account type is allowed only during
// development, so we check whether it's allowed before continuing.
//
// An account cannot be updated if the `isAnyAccountTypeAllowed` flag is
// set to `false` and the new or old account is a generic account.
const isGenericAccountInvolved =
newAccount.type === AnyAccountType.Account ||
oldAccount.type === AnyAccountType.Account;
if (!this.#isAnyAccountTypeAllowed && isGenericAccountInvolved) {
throw new Error(`Cannot update generic account '${newAccount.id}'`);
}
// The address of the account cannot be changed. In the future, we will
// support changing the address of an account since it will be required to
// support UTXO-based chains.
if (!equalsIgnoreCase(oldAccount.address, newAccount.address)) {
throw new Error(`Cannot change address of account '${newAccount.id}'`);
}
this.#accounts.set(newAccount.id, { account: newAccount, snapId });
await this.#callbacks.saveState();
return null;
}
/**
* Handle an Account Deleted event from a Snap.
*
* @param snapId - Snap ID.
* @param message - Event message.
* @returns `null`.
*/
async #handleAccountDeleted(
snapId: SnapId,
message: SnapMessage,
): Promise<null> {
assert(message, AccountDeletedEventStruct);
const { id } = message.params;
const entry = this.#accounts.get(snapId, id);
// We can ignore the case where the account was already removed from the
// keyring, making the deletion idempotent.
//
// This happens when the keyring calls the Snap to delete an account, and
// the Snap calls the keyring back with an `AccountDeleted` event.
if (entry === undefined) {
return null;
}
// At this point we know that the account exists, so we can safely
// destructure it.
const { account } = entry;
await this.#callbacks.removeAccount(
normalizeAccountAddress(account),
snapId,
async (accepted) => {
if (accepted) {
await this.#callbacks.saveState();
}
},
);
return null;
}
/**
* Handle a Get Selected Accounts method call from a Snap.
*
* @param snapId - Snap ID.
* @param message - Method call message.
* @returns The selected accounts.
*/
async #handleGetSelectedAccounts(
snapId: SnapId,
message: SnapMessage,
): Promise<GetSelectedAccountsResponse> {
assert(message, GetSelectedAccountsRequestStruct);
return this.#selectedAccounts.get(snapId) ?? [];
}
/**
* Handle an Request Approved event from a Snap.
*
* @param snapId - Snap ID.
* @param message - Event message.
* @returns `null`.
*/
async #handleRequestApproved(
snapId: SnapId,
message: SnapMessage,
): Promise<null> {
assert(message, RequestApprovedEventStruct);
const { id, result } = message.params;
const { promise } =
this.#requests.get(snapId, id) ?? throwError(`Request '${id}' not found`);
this.#requests.delete(snapId, id);
promise.resolve(result);
return null;
}
/**
* Handle an Request Rejected event from a Snap.
*
* @param snapId - Snap ID.
* @param message - Event message.
* @returns `null`.
*/
async #handleRequestRejected(
snapId: SnapId,
message: SnapMessage,
): Promise<null> {
assert(message, RequestRejectedEventStruct);
const { id } = message.params;
const { promise } =
this.#requests.get(snapId, id) ?? throwError(`Request '${id}' not found`);
this.#requests.delete(snapId, id);
promise.reject(new Error(`Request rejected by user or snap.`));
return null;
}
/**
* Re-publish an account event.
*
* @param snapId - Snap ID.
* @param event - The event type. This is a unique identifier for this event.
* @param filteredEventCallback - A callback that returns the event to re-publish. This callback takes a filtering
* function as parameter that can be used to filter out account ID that do not belong to this Snap ID.
* @template EventType - A Snap keyring event type.
* @returns `null`.
*/
async #rePublishAccountEvent<EventType extends SnapKeyringEvents['type']>(
snapId: SnapId,
event: EventType,
filteredEventCallback: (
filter: FilterAccountIdFunction,
) => ExtractEventPayload<SnapKeyringEvents, EventType>,
): Promise<null> {
// This callback can be used to filter out the accounts that no longer exists on the Snap (fail-safe) or to
// prevent other Snaps from updating accounts they do not own.
const filter: FilterAccountIdFunction = <Entry>(
accountMapping: Record<AccountId, Entry>,
): Record<AccountId, Entry> => {
return Object.entries(accountMapping).reduce<Record<AccountId, Entry>>(
(filtered, [accountId, entry]) => {
if (this.#accounts.has(snapId, accountId)) {
// If the Snap owns this account, we can use it.
filtered[accountId] = entry;
} else {
// Otherwise, we just filter it out and log it (for debugging/tracking purposes).
console.warn(
`SnapKeyring - ${event} - Found an unknown account ID "${accountId}" for Snap ID "${snapId}". Skipping.`,
);
}
return filtered;
},
{},
);
};
this.#messenger.publish(event, ...filteredEventCallback(filter));
return null;
}
/**
* Handle a balances updated event from a Snap.
*
* @param snapId - ID of the Snap.
* @param message - Event message.
* @returns `null`.
*/
async #handleAccountBalancesUpdated(
snapId: SnapId,
message: SnapMessage,
): Promise<null> {
assert(message, AccountBalancesUpdatedEventStruct);
const event = message.params;
return this.#rePublishAccountEvent(
snapId,
'SnapKeyring:accountBalancesUpdated',
(filter) => {
event.balances = filter(event.balances);
return [event];
},
);
}
/**
* Handle a asset list updated event from a Snap.
*
* @param snapId - ID of the Snap.
* @param message - Event message.
* @returns `null`.
*/
async #handleAccountAssetListUpdated(
snapId: SnapId,
message: SnapMessage,
): Promise<null> {
assert(message, AccountAssetListUpdatedEventStruct);
const event = message.params;
return this.#rePublishAccountEvent(
snapId,
'SnapKeyring:accountAssetListUpdated',
(filter) => {
event.assets = filter(event.assets);
return [event];
},
);
}
/**
* Handle a transactions updated event from a Snap.
*
* @param snapId - ID of the Snap.
* @param message - Event message.
* @returns `null`.
*/
async #handleAccountTransactionsUpdated(
snapId: SnapId,
message: SnapMessage,
): Promise<null> {
assert(message, AccountTransactionsUpdatedEventStruct);
const event = message.params;
return this.#rePublishAccountEvent(
snapId,
'SnapKeyring:accountTransactionsUpdated',
(filter) => {
event.transactions = filter(event.transactions);
return [event];
},
);
}
/**
* Handle a message from a Snap.
*
* @param snapId - ID of the Snap.
* @param message - Message sent by the Snap.
* @returns The execution result.
*/
async handleKeyringSnapMessage(
snapId: SnapId,
message: SnapMessage,
): Promise<Json> {
assert(message, SnapMessageStruct);
switch (message.method) {
case `${KeyringEvent.AccountCreated}`: {
return this.#handleAccountCreated(snapId, message);
}
case `${KeyringEvent.AccountUpdated}`: {
return this.#handleAccountUpdated(snapId, message);
}
case `${KeyringEvent.AccountDeleted}`: {
return this.#handleAccountDeleted(snapId, message);
}
case `${KeyringEvent.RequestApproved}`: {
return this.#handleRequestApproved(snapId, message);
}
case `${KeyringEvent.RequestRejected}`: {
return this.#handleRequestRejected(snapId, message);
}
// Assets related events:
case `${KeyringEvent.AccountBalancesUpdated}`: {
return this.#handleAccountBalancesUpdated(snapId, message);
}
case `${KeyringEvent.AccountAssetListUpdated}`: {
return this.#handleAccountAssetListUpdated(snapId, message);
}
case `${KeyringEvent.AccountTransactionsUpdated}`: {
return this.#handleAccountTransactionsUpdated(snapId, message);
}
case `${SnapManageAccountsMethod.GetSelectedAccounts}`: {
return this.#handleGetSelectedAccounts(snapId, message);
}
default:
throw new Error(`Method not supported: ${message.method}`);
}
}
/**
* Serialize the keyring state.
*
* @returns Serialized keyring state.
*/
async serialize(): Promise<KeyringState> {
return {
accounts: this.#accounts.toObject(),
};
}
/**
* Deserialize the keyring state into this keyring.
*
* @param state - Serialized keyring state.
*/
async deserialize(state: KeyringState | undefined): Promise<void> {
// If the state is undefined, it means that this is a new keyring, so we
// don't need to do anything.
if (state === undefined) {
return;
}
// Running Snap keyring migrations. We might have some accounts that have a
// different "version" than the one we expect.
//
// In this case, we "transform" then directly when deserializing to convert
// them in the final account version.
const accounts: KeyringState['accounts'] = {};
for (const [snapId, entry] of Object.entries(state.accounts)) {
// V1 accounts are missing the scopes.
if (isAccountV1(entry.account)) {
console.info(
`SnapKeyring - Found a KeyringAccountV1, migrating to V2: ${entry.account.id}`,
);
accounts[snapId] = {
...entry,
account: migrateAccountV1(entry.account),
};
} else {
accounts[snapId] = entry;
}
}
this.#accounts = SnapIdMap.fromObject(accounts);
}
/**
* Get an account and its associated Snap ID from its ID.
*
* @param id - Account ID.
* @throws An error if the account could not be found.
* @returns The account associated with the given account ID in this keyring.
*/
#getAccount(id: string): { account: KeyringAccount; snapId: SnapId } {
const found = [...this.#accounts.values()].find(
(entry) => entry.account.id === id,
);
if (!found) {
throw new Error(`Unable to get account: unknown account ID: '${id}'`);
}
return found;
}
/**
* Get the addresses of the accounts in this keyring.
*
* @returns The addresses of the accounts in this keyring.
*/
async getAccounts(): Promise<string[]> {
return unique(
[...this.#accounts.values()].map(({ account }) =>
normalizeAccountAddress(account),
),
);
}
/**
* Get the addresses of the accounts associated with a given Snap.
*
* @param snapId - Snap ID to filter by.
* @returns The addresses of the accounts associated with the given Snap.
*/
async getAccountsBySnapId(snapId: SnapId): Promise<string[]> {
return unique(
[...this.#accounts.values()]
.filter(({ snapId: accountSnapId }) => accountSnapId === snapId)
.map(({ account }) => normalizeAccountAddress(account)),
);
}
/**
* Create an account.
*
* @param snapId - Snap ID to create the account for.
* @param options - Account creation options. Differs between keyrings.
* @param internalOptions - Internal Snap keyring options.
* @returns The account object.
*/
async createAccount(
snapId: SnapId,
options: Record<string, Json>,
internalOptions?: SnapKeyringInternalOptions,
): Promise<KeyringAccount> {
const client = new KeyringInternalSnapClient({
messenger: this.#messenger,
snapId,
});
// The 'metamask' field is reserved, so we have to prevent use of it on
// the "normal options".
const reserved = 'metamask';
if (hasProperty(options, reserved)) {
throw new Error(
`The '${reserved}' property is reserved for internal use`,
);
}
// Those internal options are optional. If not set, we avoid registering anything
// to internal map (to avoid holding resources for nothing). In this case, it's
// just a normal `keyring_createAccount`.
if (!internalOptions) {
return await client.createAccount(options);
}
// A unique ID to identify this execution flow which allows to associate the
// internal options and the current `keyring_createAccount` flow for that Snap.
const correlationId = uuid();
// Register those internal options to use them during the `keyring_createAccount`
// flow.
this.#options.set(correlationId, {
snapId,
options: internalOptions,
});
return await client.createAccount({
...options,
// Create internal options context.
// NOTE: Those options HAVE TO be re-emitted during the `notify:accountCreated` event.
...({
metamask: {
correlationId,
},
} as MetaMaskOptions),
});
}
/**
* Create one or more accounts according to the provided options.
*
* This method supports batch account creation for BIP-44 derivation paths,
* allowing the creation of multiple accounts up to a specified maximum index.
*
* @param snapId - Snap ID to create the accounts for.
* @param options - Account creation options.
* @returns A promise that resolves to an array of the created account objects.
*/
async createAccounts(
snapId: SnapId,
options: CreateAccountOptions,
): Promise<KeyringAccount[]> {
const client = new KeyringInternalSnapClient({
messenger: this.#messenger,
snapId,
});
// Add each returned account to the internal accounts map.
// NOTE: This method DOES NOT rely on the `AccountCreated` event to add
// accounts to the keyring, since those accounts are created in batch.
const accounts = await client.createAccounts(options);
for (const account of accounts) {
this.#accounts.set(account.id, { account, snapId });
}
// Save the state after adding all accounts.
await this.#callbacks.saveState();
return accounts;
}
/**
* Checks if a Snap ID is known from the keyring.
*
* @param snapId - Snap ID.
* @returns `true` if the Snap ID is known, `false` otherwise.
*/
hasSnapId(snapId: SnapId): boolean {
return this.#accounts.hasSnapId(snapId);
}
/**
* Resolve the Snap account's address associated from a signing request.
*
* @param snapId - Snap ID.
* @param scope - CAIP-2 chain ID.
* @param request - Signing request object.
* @throws An error if the Snap ID is not known from the keyring.
* @returns The resolved address if found, `null` otherwise.
*/
async resolveAccountAddress(
snapId: SnapId,
scope: CaipChainId,
request: JsonRpcRequest,
): Promise<ResolvedAccountAddress | null> {
// We do check that the incoming Snap ID is known by the keyring.
if (!this.hasSnapId(snapId)) {
throw new Error(
`Unable to resolve account address: unknown Snap ID: ${snapId}`,
);
}
return await this.#snapClient
.withSnapId(snapId)
.resolveAccountAddress(scope, request);
}
/**
* Submit a request to a Snap from an account ID.
*
* This request cannot be an asynchronous keyring request.
*
* @param opts - Request options.
* @param opts.origin - Send origin.
* @param opts.account - Account ID.
* @param opts.method - Method to call.
* @param opts.params - Method parameters.
* @param opts.scope - Selected chain ID (CAIP-2).
* @returns Promise that resolves to the result of the method call.
*/
async submitRequest({
origin,
account: accountId,
method,
params,
scope,
}: {
origin: string;
// NOTE: We use `account` here rather than `id` to avoid ambiguity with a "request ID".
// We already use this same field name for `KeyringAccount`s.
account: string;
method: string;
params?: Json[] | Record<string, Json>;
scope: string;
}): Promise<Json> {
const { account, snapId } = this.#getAccount(accountId);
return await this.#submitSnapRequest({
origin,
snapId,
account,
method: method as AccountMethod,
params,
scope,