@metamask-previews/eth-snap-keyring 22.3.0-e51c895 → 23.0.1-1fa477f

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.
@@ -10,17 +10,27 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _SnapKeyring_instances, _SnapKeyring_callbacks, _SnapKeyring_lock, _SnapKeyring_withLock;
13
+ var _SnapKeyring_instances, _SnapKeyring_registry, _SnapKeyring_messenger, _SnapKeyring_callbacks, _SnapKeyring_isAnyAccountTypeAllowed, _SnapKeyring_lock, _SnapKeyring_context, _SnapKeyring_v1, _SnapKeyring_client_get, _SnapKeyring_withLock, _SnapKeyring_assertInitialized, _SnapKeyring_resolveKeyringCapabilities, _SnapKeyring_getExistingAccount;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.SnapKeyring = exports.isSnapKeyring = exports.SnapKeyringStateStruct = void 0;
15
+ exports.SnapKeyring = exports.isSnapKeyring = exports.SnapKeyringStateStruct = exports.EMPTY_CAPABILITIES = void 0;
16
16
  const keyring_api_1 = require("@metamask/keyring-api");
17
17
  const v2_1 = require("@metamask/keyring-api/v2");
18
+ const v2_2 = require("@metamask/keyring-internal-snap-client/v2");
19
+ const keyring_sdk_1 = require("@metamask/keyring-sdk");
18
20
  const superstruct_1 = require("@metamask/superstruct");
19
21
  const async_mutex_1 = require("async-mutex");
20
22
  const account_1 = require("../account.cjs");
21
23
  const migrations_1 = require("../migrations/index.cjs");
22
24
  const SnapKeyringV1_1 = require("../SnapKeyringV1.cjs");
23
25
  const util_1 = require("../util.cjs");
26
+ /**
27
+ * Default, empty capabilities used until the snap manifest is read on
28
+ * `deserialize`. Typed (no cast) so that adding a new required
29
+ * `KeyringCapabilities` field surfaces here as a compile error.
30
+ */
31
+ exports.EMPTY_CAPABILITIES = Object.freeze({
32
+ scopes: [],
33
+ });
24
34
  /**
25
35
  * Superstruct schema for {@link SnapKeyringState}.
26
36
  *
@@ -42,50 +52,103 @@ function isSnapKeyring(keyring) {
42
52
  }
43
53
  exports.isSnapKeyring = isSnapKeyring;
44
54
  /**
45
- * Per-snap keyring wrapper that implements `Keyring`.
55
+ * Per-snap keyring that implements `Keyring` (v2).
46
56
  *
47
- * Extends `SnapKeyringV1` — the v1 event-driven flow (account lifecycle,
48
- * request handling, asset events) is inherited. This class adds the
49
- * `KeyringV2` batch interface (`createAccounts`, `deleteAccount`, etc.) and
50
- * owns the `capabilities` property.
51
- *
52
- * The `KeyringAccountRegistry`, snap client, and messenger are all inherited
53
- * from `SnapKeyringV1` so there is no duplicated state.
57
+ * Owns the account registry and messenger. For v1 snaps (those that do not
58
+ * declare `endowment:keyring` capabilities in their manifest), a
59
+ * {@link SnapKeyringV1} instance is created on `deserialize` and held under
60
+ * {@link SnapKeyring.v1}. V2 snaps have `v1 === undefined` and communicate
61
+ * directly through the v2 client without the `{ pending, result }` envelope.
54
62
  */
55
- class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
56
- constructor(options) {
57
- super(options);
63
+ class SnapKeyring {
64
+ constructor({ messenger, callbacks, isAnyAccountTypeAllowed = false, }) {
58
65
  _SnapKeyring_instances.add(this);
59
- /**
60
- * V2-typed view of the callbacks. Stored separately from the V1 private
61
- * field so that V2-specific callbacks are accessible without casting.
62
- * Both fields hold the same object reference.
63
- */
66
+ /** Account registry — shared by reference with the v1 instance when present. */
67
+ _SnapKeyring_registry.set(this, void 0);
68
+ /** Messenger for snap controller calls and event publishing. */
69
+ _SnapKeyring_messenger.set(this, void 0);
64
70
  _SnapKeyring_callbacks.set(this, void 0);
71
+ _SnapKeyring_isAnyAccountTypeAllowed.set(this, void 0);
65
72
  /**
66
73
  * Mutex that serializes `createAccounts` calls on this snap instance.
67
74
  * Owned here so that each `SnapKeyring` is fully self-contained.
68
75
  */
69
76
  _SnapKeyring_lock.set(this, void 0);
77
+ /** V2 snap client. Set via {@link bindSnapId}. */
78
+ _SnapKeyring_context.set(this, void 0);
79
+ /**
80
+ * V1 instance, present only when the snap does not declare v2 capabilities.
81
+ * Created on `deserialize()` after reading the snap manifest.
82
+ */
83
+ _SnapKeyring_v1.set(this, void 0);
70
84
  // ──────────────────────────────────────────────
71
85
  // Keyring properties
72
86
  // ──────────────────────────────────────────────
73
87
  this.type = `${v2_1.KeyringType.Snap}`;
74
- __classPrivateFieldSet(this, _SnapKeyring_callbacks, options.callbacks, "f");
88
+ __classPrivateFieldSet(this, _SnapKeyring_registry, new keyring_sdk_1.KeyringAccountRegistry(), "f");
89
+ __classPrivateFieldSet(this, _SnapKeyring_messenger, messenger, "f");
90
+ __classPrivateFieldSet(this, _SnapKeyring_callbacks, callbacks, "f");
91
+ __classPrivateFieldSet(this, _SnapKeyring_isAnyAccountTypeAllowed, isAnyAccountTypeAllowed, "f");
75
92
  __classPrivateFieldSet(this, _SnapKeyring_lock, new async_mutex_1.Mutex(), "f");
76
- // Default capabilities — parent updates this when snap metadata is available.
77
- // We cast here because KeyringCapabilities requires a non-empty scopes array,
78
- // but we don't have the snap metadata at construction time (e.g. during deserialization).
79
- this.capabilities = { scopes: [] };
93
+ // Default capabilities; replaced from the snap manifest on `deserialize`.
94
+ this.capabilities = exports.EMPTY_CAPABILITIES;
95
+ }
96
+ /**
97
+ * Gets the v1 instance for this snap, or `undefined` if the snap is v2-only.
98
+ *
99
+ * @returns The v1 instance, or `undefined` if the snap is v2-only.
100
+ *
101
+ * Use this to make v1 calls explicit:
102
+ * ```ts
103
+ * keyring.v1?.signTransaction(account, tx);
104
+ * ```
105
+ */
106
+ get v1() {
107
+ return __classPrivateFieldGet(this, _SnapKeyring_v1, "f");
80
108
  }
81
109
  /**
82
- * Destroy this keyring.
110
+ * The snap ID this instance is scoped to.
83
111
  *
84
- * Delegates to the parent `SnapKeyringV1.destroy()` to reject any pending
85
- * requests inherited from the v1 flow.
112
+ * @returns The snap ID.
113
+ * @throws If the keyring has not been initialized yet.
114
+ */
115
+ get snapId() {
116
+ /* istanbul ignore next */
117
+ if (__classPrivateFieldGet(this, _SnapKeyring_context, "f") === undefined) {
118
+ throw new Error('SnapKeyring has not been initialized: call deserialize() first');
119
+ }
120
+ return __classPrivateFieldGet(this, _SnapKeyring_context, "f").snapId;
121
+ }
122
+ /**
123
+ * Bind this keyring to a snap ID and initialize the v2 client.
124
+ *
125
+ * Idempotent for the same `snapId`; throws if called again with a different
126
+ * one to prevent accidentally swapping a keyring's identity.
127
+ *
128
+ * @param snapId - The snap ID to bind to.
129
+ */
130
+ bindSnapId(snapId) {
131
+ if (__classPrivateFieldGet(this, _SnapKeyring_context, "f") !== undefined && __classPrivateFieldGet(this, _SnapKeyring_context, "f").snapId !== snapId) {
132
+ throw new Error(`SnapKeyring bound to '${__classPrivateFieldGet(this, _SnapKeyring_context, "f").snapId}' cannot be rebound to '${snapId}'`);
133
+ }
134
+ if (__classPrivateFieldGet(this, _SnapKeyring_context, "f") === undefined) {
135
+ __classPrivateFieldSet(this, _SnapKeyring_context, {
136
+ snapId,
137
+ client: new v2_2.KeyringInternalSnapClient({
138
+ messenger: __classPrivateFieldGet(this, _SnapKeyring_messenger, "f"),
139
+ snapId,
140
+ }),
141
+ }, "f");
142
+ }
143
+ }
144
+ /**
145
+ * Destroy this keyring, rejecting any pending v1 requests.
146
+ *
147
+ * @returns A promise that resolves when the keyring is destroyed.
86
148
  */
87
149
  async destroy() {
88
- await super.destroy();
150
+ await __classPrivateFieldGet(this, _SnapKeyring_v1, "f")?.destroy();
151
+ __classPrivateFieldSet(this, _SnapKeyring_v1, undefined, "f");
89
152
  }
90
153
  // ──────────────────────────────────────────────
91
154
  // Keyring methods
@@ -96,6 +159,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
96
159
  * @returns A promise that resolves to an array of all accounts.
97
160
  */
98
161
  async getAccounts() {
162
+ __classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_assertInitialized).call(this);
99
163
  return this.accounts();
100
164
  }
101
165
  /**
@@ -105,6 +169,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
105
169
  * @returns A promise that resolves to the account.
106
170
  */
107
171
  async getAccount(accountId) {
172
+ __classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_assertInitialized).call(this);
108
173
  const account = this.lookupAccount(accountId);
109
174
  if (!account) {
110
175
  throw new Error(`Account '${accountId}' not found in snap '${this.snapId}'`);
@@ -127,19 +192,30 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
127
192
  * @returns A promise that resolves to an array of the created account objects.
128
193
  */
129
194
  async createAccounts(options) {
195
+ __classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_assertInitialized).call(this);
130
196
  return __classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_withLock).call(this, async () => {
131
197
  // Keep track of address/account ID part of this batch, to avoid having duplicates.
132
198
  const batchAddresses = new Set();
133
199
  const batchIds = new Set();
134
200
  const accounts = [];
135
201
  const newAccounts = [];
136
- const snapAccounts = await this.client.createAccounts(options);
202
+ let snapAccounts;
203
+ if (__classPrivateFieldGet(this, _SnapKeyring_v1, "f")) {
204
+ // v1 snap: the v1 client wraps options in `{ options }` before sending
205
+ // `keyring_createAccounts`, while the v2 client sends flat options.
206
+ // Route through v1 so v1 snaps receive the format they expect.
207
+ snapAccounts = await __classPrivateFieldGet(this, _SnapKeyring_v1, "f").createAccounts(options);
208
+ }
209
+ else {
210
+ // v2 snap: call snap directly with flat options.
211
+ snapAccounts = await __classPrivateFieldGet(this, _SnapKeyring_instances, "a", _SnapKeyring_client_get).createAccounts(options);
212
+ }
137
213
  try {
138
214
  for (const snapAccount of snapAccounts) {
139
215
  let account = (0, account_1.normalizeAccount)((0, account_1.transformAccount)(snapAccount));
140
216
  const { address } = account;
141
217
  // Check for idempotency.
142
- const existingAccount = this.getExistingAccount(account);
218
+ const existingAccount = __classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_getExistingAccount).call(this, account);
143
219
  if (existingAccount) {
144
220
  // NOTE: We re-use the account from the internal state to avoid having the Snap
145
221
  // mutating the account object without updating the map.
@@ -166,9 +242,6 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
166
242
  for (const account of newAccounts) {
167
243
  this.setAccount(account);
168
244
  }
169
- // NOTE: We assume this will never fail, thus, we don't need to rollback the
170
- // keyring state if anything goes wrong here.
171
- await __classPrivateFieldGet(this, _SnapKeyring_callbacks, "f").saveState();
172
245
  }
173
246
  return accounts;
174
247
  }
@@ -176,9 +249,9 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
176
249
  // Rollback Snap state.
177
250
  for (const snapAccount of snapAccounts) {
178
251
  // Make sure to only delete accounts that were not part of the keyring state.
179
- if (!this.getExistingAccount(snapAccount)) {
252
+ if (!__classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_getExistingAccount).call(this, snapAccount)) {
180
253
  try {
181
- await this.client.deleteAccount(snapAccount.id);
254
+ await __classPrivateFieldGet(this, _SnapKeyring_instances, "a", _SnapKeyring_client_get).deleteAccount(snapAccount.id);
182
255
  }
183
256
  catch (rollbackError) {
184
257
  // Best-effort rollback; log snap-side failures for observability.
@@ -199,11 +272,12 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
199
272
  * @param accountId - ID of the account to delete.
200
273
  */
201
274
  async deleteAccount(accountId) {
275
+ __classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_assertInitialized).call(this);
202
276
  // Always remove the account from the registry, even if the Snap is going to
203
277
  // fail to delete it. removeAccount fires onUnregister to clean #accountIndex.
204
278
  this.removeAccount(accountId);
205
279
  try {
206
- await this.client.deleteAccount(accountId);
280
+ await __classPrivateFieldGet(this, _SnapKeyring_instances, "a", _SnapKeyring_client_get).deleteAccount(accountId);
207
281
  }
208
282
  catch (error) {
209
283
  // If the Snap failed to delete the account, log the error and continue
@@ -215,12 +289,13 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
215
289
  /**
216
290
  * Submits a request to the keyring.
217
291
  *
218
- * Validates that the account belongs to this wrapper, then delegates
219
- * to the inherited `submitSnapRequest` for the full request lifecycle
220
- * (sync / async / redirect).
292
+ * For v1 snaps (those without declared capabilities), delegates to the v1
293
+ * event-driven flow that handles the `{ pending, result }` envelope.
294
+ * For v2 snaps, calls the snap directly via the v2 client which returns
295
+ * `Json` with no envelope.
221
296
  *
222
297
  * @param request - The keyring request to submit.
223
- * @param request.id - The request ID (unused — a fresh ID is generated internally).
298
+ * @param request.id - The request ID.
224
299
  * @param request.origin - The sender origin.
225
300
  * @param request.scope - The CAIP-2 chain ID.
226
301
  * @param request.account - The account ID.
@@ -230,17 +305,29 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
230
305
  * @returns A promise that resolves to the response.
231
306
  */
232
307
  async submitRequest(request) {
308
+ __classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_assertInitialized).call(this);
233
309
  const account = this.lookupAccount(request.account);
234
310
  if (!account) {
235
311
  throw new Error(`Account '${request.account}' not found in snap '${this.snapId}'`);
236
312
  }
237
- return this.submitSnapRequest({
313
+ if (__classPrivateFieldGet(this, _SnapKeyring_v1, "f")) {
314
+ // v1 snap: use event-driven flow with { pending, result } envelope handling.
315
+ return __classPrivateFieldGet(this, _SnapKeyring_v1, "f").submitSnapRequest({
316
+ origin: request.origin,
317
+ account,
318
+ method: request.request.method,
319
+ params: request.request.params,
320
+ scope: request.scope,
321
+ noPending: false,
322
+ });
323
+ }
324
+ // v2 snap: call snap directly, returns Json (no envelope).
325
+ return __classPrivateFieldGet(this, _SnapKeyring_instances, "a", _SnapKeyring_client_get).submitRequest({
326
+ id: request.id,
238
327
  origin: request.origin,
239
- account,
240
- method: request.request.method,
241
- params: request.request.params,
242
328
  scope: request.scope,
243
- noPending: false,
329
+ account: request.account,
330
+ request: request.request,
244
331
  });
245
332
  }
246
333
  // ──────────────────────────────────────────────
@@ -256,8 +343,8 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
256
343
  * @param account - The account to add or update.
257
344
  */
258
345
  setAccount(account) {
259
- const isNew = !this.registry.has(account.id);
260
- this.registry.set(account);
346
+ const isNew = !__classPrivateFieldGet(this, _SnapKeyring_registry, "f").has(account.id);
347
+ __classPrivateFieldGet(this, _SnapKeyring_registry, "f").set(account);
261
348
  if (isNew) {
262
349
  __classPrivateFieldGet(this, _SnapKeyring_callbacks, "f").onRegister?.(account.id);
263
350
  }
@@ -271,10 +358,10 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
271
358
  * @returns `true` if the account was removed, `false` if it was not found.
272
359
  */
273
360
  removeAccount(id) {
274
- if (!this.registry.has(id)) {
361
+ if (!__classPrivateFieldGet(this, _SnapKeyring_registry, "f").has(id)) {
275
362
  return false;
276
363
  }
277
- this.registry.delete(id);
364
+ __classPrivateFieldGet(this, _SnapKeyring_registry, "f").delete(id);
278
365
  __classPrivateFieldGet(this, _SnapKeyring_callbacks, "f").onUnregister?.(id);
279
366
  return true;
280
367
  }
@@ -285,7 +372,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
285
372
  * @returns `true` if the account exists.
286
373
  */
287
374
  hasAccount(id) {
288
- return this.registry.has(id);
375
+ return __classPrivateFieldGet(this, _SnapKeyring_registry, "f").has(id);
289
376
  }
290
377
  /**
291
378
  * Get an account by its ID.
@@ -294,7 +381,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
294
381
  * @returns The account, or `undefined` if not found.
295
382
  */
296
383
  lookupAccount(id) {
297
- return this.registry.get(id);
384
+ return __classPrivateFieldGet(this, _SnapKeyring_registry, "f").get(id);
298
385
  }
299
386
  /**
300
387
  * Get an account by address (case-insensitive).
@@ -306,15 +393,15 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
306
393
  * @returns The account, or `undefined` if not found.
307
394
  */
308
395
  lookupByAddress(address) {
309
- const id = this.registry.getAccountId(address);
396
+ const id = __classPrivateFieldGet(this, _SnapKeyring_registry, "f").getAccountId(address);
310
397
  if (id !== undefined) {
311
- return this.registry.get(id);
398
+ return __classPrivateFieldGet(this, _SnapKeyring_registry, "f").get(id);
312
399
  }
313
400
  // The fallback only runs when the exact-match branch above misses,
314
401
  // which in practice only happens for EVM addresses with casing
315
402
  // differences (checksummed vs lowercase). Non-EVM addresses are
316
403
  // case-sensitive and always resolve on the exact branch.
317
- return this.registry
404
+ return __classPrivateFieldGet(this, _SnapKeyring_registry, "f")
318
405
  .values()
319
406
  .find((account) => (0, util_1.equalsIgnoreCase)(account.address, address));
320
407
  }
@@ -328,7 +415,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
328
415
  * @returns An array of all accounts.
329
416
  */
330
417
  accounts() {
331
- return this.registry.values();
418
+ return __classPrivateFieldGet(this, _SnapKeyring_registry, "f").values();
332
419
  }
333
420
  /**
334
421
  * Serialize this keyring's state.
@@ -341,7 +428,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
341
428
  */
342
429
  async serialize() {
343
430
  const accounts = {};
344
- for (const account of this.registry.values()) {
431
+ for (const account of __classPrivateFieldGet(this, _SnapKeyring_registry, "f").values()) {
345
432
  accounts[account.id] = account;
346
433
  }
347
434
  const state = {
@@ -353,9 +440,11 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
353
440
  /**
354
441
  * Restore this keyring from a serialized state.
355
442
  *
356
- * Validates the payload (accepting both v1 and v2 accounts), migrates any
357
- * v1 accounts to v2, then replaces the registry. If validation fails, the
358
- * existing registry is left untouched.
443
+ * Validates the payload (accepting both v1 and v2 account shapes), migrates
444
+ * any v1 accounts to v2, then replaces the registry. Also determines whether
445
+ * the snap is v1 or v2 by reading its manifest capabilities: if no
446
+ * capabilities are declared, a {@link SnapKeyringV1} instance is created and
447
+ * held under {@link SnapKeyring.v1}.
359
448
  *
360
449
  * @param state - The state to deserialize.
361
450
  * @returns A promise that resolves when deserialization is complete.
@@ -366,6 +455,31 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
366
455
  // Bind the keyring to its snap ID (idempotent for the same ID, throws on
367
456
  // mismatch to prevent swapping a keyring's identity via deserialize).
368
457
  this.bindSnapId(state.snapId);
458
+ // Refresh capabilities from the snap manifest on every deserialize, falling
459
+ // back to the empty default so a re-hydrate clears any previously-loaded
460
+ // capabilities when the snap no longer declares them.
461
+ const capabilities = __classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_resolveKeyringCapabilities).call(this);
462
+ this.capabilities = capabilities ?? exports.EMPTY_CAPABILITIES;
463
+ // Determine snap version and create a v1 instance if needed.
464
+ const v1 = capabilities === undefined;
465
+ if (v1) {
466
+ // v1 snap: no declared capabilities. Create a SnapKeyringV1 instance
467
+ // that shares the registry and messenger owned by this class.
468
+ if (__classPrivateFieldGet(this, _SnapKeyring_v1, "f") === undefined) {
469
+ __classPrivateFieldSet(this, _SnapKeyring_v1, new SnapKeyringV1_1.SnapKeyringV1({
470
+ messenger: __classPrivateFieldGet(this, _SnapKeyring_messenger, "f"),
471
+ callbacks: __classPrivateFieldGet(this, _SnapKeyring_callbacks, "f"),
472
+ registry: __classPrivateFieldGet(this, _SnapKeyring_registry, "f"),
473
+ isAnyAccountTypeAllowed: __classPrivateFieldGet(this, _SnapKeyring_isAnyAccountTypeAllowed, "f"),
474
+ }), "f");
475
+ __classPrivateFieldGet(this, _SnapKeyring_v1, "f").bindSnapId(state.snapId);
476
+ }
477
+ }
478
+ else {
479
+ // v2 snap: tear down any stale v1 instance (e.g. after a manifest update).
480
+ await __classPrivateFieldGet(this, _SnapKeyring_v1, "f")?.destroy();
481
+ __classPrivateFieldSet(this, _SnapKeyring_v1, undefined, "f");
482
+ }
369
483
  // Migrate v1 accounts to v2.
370
484
  const migratedAccounts = {};
371
485
  for (const [id, rawAccount] of Object.entries(state.accounts)) {
@@ -378,7 +492,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
378
492
  }
379
493
  }
380
494
  // Apply the migrated state to the registry.
381
- for (const id of [...this.registry.keys()]) {
495
+ for (const id of [...__classPrivateFieldGet(this, _SnapKeyring_registry, "f").keys()]) {
382
496
  this.removeAccount(id);
383
497
  }
384
498
  for (const account of Object.values(migratedAccounts)) {
@@ -387,14 +501,20 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
387
501
  }
388
502
  }
389
503
  exports.SnapKeyring = SnapKeyring;
390
- _SnapKeyring_callbacks = new WeakMap(), _SnapKeyring_lock = new WeakMap(), _SnapKeyring_instances = new WeakSet(), _SnapKeyring_withLock =
504
+ _SnapKeyring_registry = new WeakMap(), _SnapKeyring_messenger = new WeakMap(), _SnapKeyring_callbacks = new WeakMap(), _SnapKeyring_isAnyAccountTypeAllowed = new WeakMap(), _SnapKeyring_lock = new WeakMap(), _SnapKeyring_context = new WeakMap(), _SnapKeyring_v1 = new WeakMap(), _SnapKeyring_instances = new WeakSet(), _SnapKeyring_client_get = function _SnapKeyring_client_get() {
505
+ /* istanbul ignore next */
506
+ if (__classPrivateFieldGet(this, _SnapKeyring_context, "f") === undefined) {
507
+ throw new Error('SnapKeyring is not bound to a snap ID');
508
+ }
509
+ return __classPrivateFieldGet(this, _SnapKeyring_context, "f").client;
510
+ }, _SnapKeyring_withLock =
391
511
  /**
392
512
  * Run a callback under the appropriate lock.
393
513
  *
394
514
  * Prefers the injected `withLock` callback (global lock provided by
395
515
  * `SnapKeyring`) so that `createAccounts` calls across different snaps
396
516
  * are serialized. Falls back to the per-instance `#lock` when no global
397
- * lock is provided.g. standalone use in tests).
517
+ * lock is provided (e.g. standalone use in tests).
398
518
  *
399
519
  * @param callback - Operation to run under the lock.
400
520
  * @returns The result of the callback.
@@ -402,6 +522,27 @@ _SnapKeyring_callbacks = new WeakMap(), _SnapKeyring_lock = new WeakMap(), _Snap
402
522
  async function _SnapKeyring_withLock(callback) {
403
523
  return (__classPrivateFieldGet(this, _SnapKeyring_callbacks, "f").withLock ??
404
524
  (async (operation) => __classPrivateFieldGet(this, _SnapKeyring_lock, "f").runExclusive(operation)))(callback);
525
+ }, _SnapKeyring_assertInitialized = function _SnapKeyring_assertInitialized() {
526
+ if (__classPrivateFieldGet(this, _SnapKeyring_context, "f") === undefined) {
527
+ throw new Error('SnapKeyring has not been initialized: call deserialize() first');
528
+ }
529
+ }, _SnapKeyring_resolveKeyringCapabilities = function _SnapKeyring_resolveKeyringCapabilities() {
530
+ const snap = __classPrivateFieldGet(this, _SnapKeyring_messenger, "f").call('SnapController:getSnap', this.snapId);
531
+ // READ THIS CAREFULLY:
532
+ // We are not validating the shape of the capabilities here, because there is
533
+ // manifest validation done already on the snaps side, the snaps repo maintains
534
+ // a copy of the `KeyringCapabilitiesStruct`.
535
+ // We must ensure that both structs are always in-sync, otherwise the type-cast
536
+ // could cause runtime issues!
537
+ return snap?.manifest.initialPermissions['endowment:keyring']
538
+ ?.capabilities;
539
+ }, _SnapKeyring_getExistingAccount = function _SnapKeyring_getExistingAccount(account) {
540
+ const address = (0, account_1.normalizeAccountAddress)(account);
541
+ const existing = __classPrivateFieldGet(this, _SnapKeyring_registry, "f").get(account.id);
542
+ if (existing && (0, account_1.normalizeAccountAddress)(existing) === address) {
543
+ return existing;
544
+ }
545
+ return undefined;
405
546
  };
406
547
  SnapKeyring.type = `${v2_1.KeyringType.Snap}`;
407
548
  //# sourceMappingURL=SnapKeyring.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"SnapKeyring.cjs","sourceRoot":"","sources":["../../src/v2/SnapKeyring.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,uDAA6D;AAM7D,iDAAuD;AAIvD,uDAA8E;AAE9E,6CAAoC;AAEpC,4C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AAQ,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;YAC3C,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC;QACzB,CAAC;QAED,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,EAAE,CAAC;YACtD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QAC3B,CAAC;IACH,CAAC;;AA9ZH,kCAmaC;;AAlXC;;;;;;;;;;GAUG;AACH,KAAK,gCAAmB,QAA+B;IACrD,OAAO,CACL,uBAAA,IAAI,8BAAW,CAAC,QAAQ;QACxB,CAAC,KAAK,EAAE,SAAgC,EAAmB,EAAE,CAC3D,uBAAA,IAAI,yBAAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,CACtC,CAAC,QAAQ,CAAC,CAAC;AACd,CAAC;AA9Ce,gBAAI,GAAG,GAAG,gBAAW,CAAC,IAAI,EAAW,AAAjC,CAAkC","sourcesContent":["import type { KeyringAccount } from '@metamask/keyring-api';\nimport { KeyringAccountStruct } from '@metamask/keyring-api';\nimport type {\n CreateAccountOptions,\n Keyring,\n KeyringCapabilities,\n} from '@metamask/keyring-api/v2';\nimport { KeyringType } from '@metamask/keyring-api/v2';\nimport type { AccountId } from '@metamask/keyring-utils';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type { Infer } from '@metamask/superstruct';\nimport { assert, object, record, string, union } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport {\n KeyringAccountV1Struct,\n normalizeAccount,\n transformAccount,\n} from '../account';\nimport { isAccountV1, migrateAccountV1 } from '../migrations';\nimport { SnapKeyringV1 } from '../SnapKeyringV1';\nimport type {\n AccountMethod,\n SnapKeyringV1Callbacks,\n SnapKeyringV1Options,\n} from '../SnapKeyringV1';\nimport { equalsIgnoreCase } from '../util';\n\n/**\n * Superstruct schema for {@link SnapKeyringState}.\n *\n * Accepts both v1 accounts (missing `scopes`) and v2 accounts so that\n * persisted state can be validated before migration.\n */\nexport const SnapKeyringStateStruct = object({\n snapId: string(),\n accounts: record(\n string(),\n union([KeyringAccountStruct, KeyringAccountV1Struct]),\n ),\n});\n\n/**\n * Serialized state of a single SnapKeyring instance.\n *\n * Note: this is an internal format only used between SnapKeyring and its\n * parent SnapKeyring. The external KeyringState format (flat `{ account,\n * snapId }` map) is preserved by SnapKeyring.serialize / deserialize.\n *\n * Inferred from {@link SnapKeyringStateStruct}: `snapId` is `string`\n * (not the branded `SnapId`) so the shape stays JSON-compatible without\n * unsafe casts.\n */\nexport type SnapKeyringState = Infer<typeof SnapKeyringStateStruct>;\n\n/**\n * Callbacks injected by the parent `SnapKeyring` for global coordination.\n */\nexport type SnapKeyringCallbacks = SnapKeyringV1Callbacks & {\n /**\n * Run a callback under a global lock to prevent TOCTOU races in\n * `createAccounts` when multiple snaps call `assertAccountCanBeUsed`\n * concurrently.\n *\n * Optional: if omitted, `SnapKeyringV2` falls back to its own per-instance\n * `Mutex`, which is sufficient when the keyring is used standalone.\n */\n withLock?: <Result>(callback: () => Promise<Result>) => Promise<Result>;\n};\n\ntype SnapKeyringOptions = Omit<SnapKeyringV1Options, 'callbacks'> & {\n callbacks: SnapKeyringCallbacks;\n};\n\n/**\n * Checks if a given keyring is a Snap keyring (v2).\n *\n * @param keyring - The keyring to check.\n * @returns `true` if the keyring is a Snap keyring (v2), `false` otherwise.\n */\nexport function isSnapKeyring(keyring: Keyring): keyring is SnapKeyring {\n return keyring.type === KeyringType.Snap;\n}\n\n/**\n * Per-snap keyring wrapper that implements `Keyring`.\n *\n * Extends `SnapKeyringV1` — the v1 event-driven flow (account lifecycle,\n * request handling, asset events) is inherited. This class adds the\n * `KeyringV2` batch interface (`createAccounts`, `deleteAccount`, etc.) and\n * owns the `capabilities` property.\n *\n * The `KeyringAccountRegistry`, snap client, and messenger are all inherited\n * from `SnapKeyringV1` so there is no duplicated state.\n */\nexport class SnapKeyring extends SnapKeyringV1 implements Keyring {\n /**\n * V2-typed view of the callbacks. Stored separately from the V1 private\n * field so that V2-specific callbacks are accessible without casting.\n * Both fields hold the same object reference.\n */\n readonly #callbacks: SnapKeyringCallbacks;\n\n /**\n * Mutex that serializes `createAccounts` calls on this snap instance.\n * Owned here so that each `SnapKeyring` is fully self-contained.\n */\n readonly #lock: Mutex;\n\n // ──────────────────────────────────────────────\n // Keyring properties\n // ──────────────────────────────────────────────\n\n readonly type = `${KeyringType.Snap}` as const;\n\n static readonly type = `${KeyringType.Snap}` as const;\n\n /**\n * Capabilities are snap-specific. Initialized empty and can be updated\n * by the parent when snap metadata becomes available.\n */\n capabilities: KeyringCapabilities;\n\n constructor(options: SnapKeyringOptions) {\n super(options);\n this.#callbacks = options.callbacks;\n this.#lock = new Mutex();\n\n // Default capabilities — parent updates this when snap metadata is available.\n // We cast here because KeyringCapabilities requires a non-empty scopes array,\n // but we don't have the snap metadata at construction time (e.g. during deserialization).\n this.capabilities = { scopes: [] } as unknown as KeyringCapabilities;\n }\n\n /**\n * Destroy this keyring.\n *\n * Delegates to the parent `SnapKeyringV1.destroy()` to reject any pending\n * requests inherited from the v1 flow.\n */\n override async destroy(): Promise<void> {\n await super.destroy();\n }\n\n /**\n * Run a callback under the appropriate lock.\n *\n * Prefers the injected `withLock` callback (global lock provided by\n * `SnapKeyring`) so that `createAccounts` calls across different snaps\n * are serialized. Falls back to the per-instance `#lock` when no global\n * lock is provided.g. standalone use in tests).\n *\n * @param callback - Operation to run under the lock.\n * @returns The result of the callback.\n */\n async #withLock<Result>(callback: () => Promise<Result>): Promise<Result> {\n return (\n this.#callbacks.withLock ??\n (async (operation: () => Promise<Result>): Promise<Result> =>\n this.#lock.runExclusive(operation))\n )(callback);\n }\n\n // ──────────────────────────────────────────────\n // Keyring methods\n // ──────────────────────────────────────────────\n\n /**\n * Returns all accounts managed by this keyring.\n *\n * @returns A promise that resolves to an array of all accounts.\n */\n async getAccounts(): Promise<KeyringAccount[]> {\n return this.accounts();\n }\n\n /**\n * Returns the account with the specified ID.\n *\n * @param accountId - ID of the account to retrieve.\n * @returns A promise that resolves to the account.\n */\n async getAccount(accountId: AccountId): Promise<KeyringAccount> {\n const account = this.lookupAccount(accountId);\n if (!account) {\n throw new Error(\n `Account '${accountId}' not found in snap '${this.snapId}'`,\n );\n }\n return account;\n }\n\n /**\n * Creates one or more new accounts according to the provided options.\n *\n * Deterministic account creation MUST be idempotent, meaning that for\n * deterministic algorithms, like BIP-44, calling this method with the same\n * options should always return the same accounts, even if the accounts\n * already exist in the keyring.\n *\n * NOTE: If some accounts are not allowed (non-unique address, unsupported\n * generic account), this method will skip their creation and ask the Snap\n * to remove them from its state.\n *\n * @param options - Options describing how to create the account(s).\n * @returns A promise that resolves to an array of the created account objects.\n */\n async createAccounts(\n options: CreateAccountOptions,\n ): Promise<KeyringAccount[]> {\n return this.#withLock(async () => {\n // Keep track of address/account ID part of this batch, to avoid having duplicates.\n const batchAddresses = new Set<string>();\n const batchIds = new Set<string>();\n\n const accounts: KeyringAccount[] = [];\n const newAccounts: KeyringAccount[] = [];\n const snapAccounts = await this.client.createAccounts(options);\n\n try {\n for (const snapAccount of snapAccounts) {\n let account = normalizeAccount(transformAccount(snapAccount));\n const { address } = account;\n\n // Check for idempotency.\n const existingAccount = this.getExistingAccount(account);\n if (existingAccount) {\n // NOTE: We re-use the account from the internal state to avoid having the Snap\n // mutating the account object without updating the map.\n account = existingAccount;\n } else {\n await this.#callbacks.assertAccountCanBeUsed(account);\n\n // Also check for transient accounts that are not yet part of the keyring\n // state.\n if (batchAddresses.has(address) || batchIds.has(account.id)) {\n throw new Error(\n `Account '${account.id}' is already part of this batch (same address or account ID)`,\n );\n }\n batchAddresses.add(address);\n batchIds.add(account.id);\n\n // NOTE: This method does not rely on the `AccountCreated` event to add\n // accounts to the keyring, so we have to add them to the state manually.\n newAccounts.push(account);\n }\n\n // New AND existing accounts are returned to the caller no matter what.\n accounts.push(account);\n }\n\n // We update the keyring state only if needed.\n if (newAccounts.length > 0) {\n for (const account of newAccounts) {\n this.setAccount(account);\n }\n\n // NOTE: We assume this will never fail, thus, we don't need to rollback the\n // keyring state if anything goes wrong here.\n await this.#callbacks.saveState();\n }\n\n return accounts;\n } catch (error) {\n // Rollback Snap state.\n for (const snapAccount of snapAccounts) {\n // Make sure to only delete accounts that were not part of the keyring state.\n if (!this.getExistingAccount(snapAccount)) {\n try {\n await this.client.deleteAccount(snapAccount.id);\n } catch (rollbackError) {\n // Best-effort rollback; log snap-side failures for observability.\n console.error(\n `Account '${snapAccount.id}' may not have been removed from snap '${this.snapId}' during createAccounts rollback:`,\n rollbackError,\n );\n }\n }\n }\n\n throw error;\n }\n });\n }\n\n /**\n * Deletes the account with the specified ID.\n *\n * Removes the account from the local registry (firing `onUnregister` so the\n * parent can update its index), then asks the snap to delete it.\n *\n * @param accountId - ID of the account to delete.\n */\n async deleteAccount(accountId: AccountId): Promise<void> {\n // Always remove the account from the registry, even if the Snap is going to\n // fail to delete it. removeAccount fires onUnregister to clean #accountIndex.\n this.removeAccount(accountId);\n\n try {\n await this.client.deleteAccount(accountId);\n } catch (error) {\n // If the Snap failed to delete the account, log the error and continue\n // with the account deletion, otherwise the account will be stuck in the\n // keyring.\n console.error(\n `Account '${accountId}' may not have been removed from snap '${this.snapId}':`,\n error,\n );\n }\n }\n\n /**\n * Submits a request to the keyring.\n *\n * Validates that the account belongs to this wrapper, then delegates\n * to the inherited `submitSnapRequest` for the full request lifecycle\n * (sync / async / redirect).\n *\n * @param request - The keyring request to submit.\n * @param request.id - The request ID (unused — a fresh ID is generated internally).\n * @param request.origin - The sender origin.\n * @param request.scope - The CAIP-2 chain ID.\n * @param request.account - The account ID.\n * @param request.request - The inner JSON-RPC request.\n * @param request.request.method - The method to call.\n * @param request.request.params - The method parameters.\n * @returns A promise that resolves to the response.\n */\n async submitRequest(request: {\n id: string;\n origin: string;\n scope: string;\n account: AccountId;\n request: {\n method: string;\n params?: Json[] | Record<string, Json>;\n };\n }): Promise<Json> {\n const account = this.lookupAccount(request.account);\n if (!account) {\n throw new Error(\n `Account '${request.account}' not found in snap '${this.snapId}'`,\n );\n }\n return this.submitSnapRequest({\n origin: request.origin,\n account,\n method: request.request.method as AccountMethod,\n params: request.request.params,\n scope: request.scope,\n noPending: false,\n });\n }\n\n // ──────────────────────────────────────────────\n // Internal API (used by parent SnapKeyring for event handling, routing, etc.)\n // ──────────────────────────────────────────────\n\n /**\n * Upsert an account into the registry.\n *\n * Fires `onRegister` only when the account is new (not already present).\n * Safe to call for updates -- the parent index is already populated in that\n * case and the no-op path avoids a redundant write.\n *\n * @param account - The account to add or update.\n */\n setAccount(account: KeyringAccount): void {\n const isNew = !this.registry.has(account.id);\n this.registry.set(account);\n if (isNew) {\n this.#callbacks.onRegister?.(account.id);\n }\n }\n\n /**\n * Remove an account from the registry.\n *\n * Fires `onUnregister` so the parent can drop the account from its index.\n *\n * @param id - The account ID to remove.\n * @returns `true` if the account was removed, `false` if it was not found.\n */\n removeAccount(id: AccountId): boolean {\n if (!this.registry.has(id)) {\n return false;\n }\n this.registry.delete(id);\n this.#callbacks.onUnregister?.(id);\n return true;\n }\n\n /**\n * Check whether an account exists in this keyring.\n *\n * @param id - The account ID to check.\n * @returns `true` if the account exists.\n */\n hasAccount(id: AccountId): boolean {\n return this.registry.has(id);\n }\n\n /**\n * Get an account by its ID.\n *\n * @param id - The account ID to look up.\n * @returns The account, or `undefined` if not found.\n */\n lookupAccount(id: AccountId): KeyringAccount | undefined {\n return this.registry.get(id);\n }\n\n /**\n * Get an account by address (case-insensitive).\n *\n * Performs an O(1) exact lookup first; falls back to a linear scan to\n * handle addresses stored with different casing.\n *\n * @param address - The address to look up.\n * @returns The account, or `undefined` if not found.\n */\n lookupByAddress(address: string): KeyringAccount | undefined {\n const id = this.registry.getAccountId(address);\n if (id !== undefined) {\n return this.registry.get(id);\n }\n // The fallback only runs when the exact-match branch above misses,\n // which in practice only happens for EVM addresses with casing\n // differences (checksummed vs lowercase). Non-EVM addresses are\n // case-sensitive and always resolve on the exact branch.\n return this.registry\n .values()\n .find((account) => equalsIgnoreCase(account.address, address));\n }\n\n /**\n * Get all accounts in this keyring (synchronous).\n *\n * This exists alongside the async `getAccounts()` (from `Keyring`) because\n * `SnapKeyring` needs synchronous access for iteration in `serialize`,\n * `listAccounts`, `hasSnapId`, etc. without awaiting.\n *\n * @returns An array of all accounts.\n */\n accounts(): KeyringAccount[] {\n return this.registry.values();\n }\n\n /**\n * Serialize this keyring's state.\n *\n * The returned object uses the internal per-snap format; the parent\n * `SnapKeyring` reconstructs the flat external format in its own\n * `serialize()`.\n *\n * @returns The serialized state.\n */\n async serialize(): Promise<SnapKeyringState> {\n const accounts: SnapKeyringState['accounts'] = {};\n for (const account of this.registry.values()) {\n accounts[account.id] = account;\n }\n const state: SnapKeyringState = {\n snapId: this.snapId,\n accounts,\n };\n return state;\n }\n\n /**\n * Restore this keyring from a serialized state.\n *\n * Validates the payload (accepting both v1 and v2 accounts), migrates any\n * v1 accounts to v2, then replaces the registry. If validation fails, the\n * existing registry is left untouched.\n *\n * @param state - The state to deserialize.\n * @returns A promise that resolves when deserialization is complete.\n */\n async deserialize(state: Json): Promise<void> {\n // Validate the raw payload — accepts both v1 and v2 account shapes.\n assert(state, SnapKeyringStateStruct);\n\n // Bind the keyring to its snap ID (idempotent for the same ID, throws on\n // mismatch to prevent swapping a keyring's identity via deserialize).\n this.bindSnapId(state.snapId as SnapId);\n\n // Migrate v1 accounts to v2.\n const migratedAccounts: Record<string, KeyringAccount> = {};\n for (const [id, rawAccount] of Object.entries(state.accounts)) {\n if (isAccountV1(rawAccount)) {\n console.info(\n `SnapKeyring - Found a KeyringAccountV1, migrating to V2: ${rawAccount.id}`,\n );\n migratedAccounts[id] = migrateAccountV1(rawAccount);\n } else {\n migratedAccounts[id] = rawAccount as KeyringAccount;\n }\n }\n\n // Apply the migrated state to the registry.\n for (const id of [...this.registry.keys()]) {\n this.removeAccount(id);\n }\n\n for (const account of Object.values(migratedAccounts)) {\n this.setAccount(account);\n }\n }\n\n // ──────────────────────────────────────────────\n // Private helpers\n // ──────────────────────────────────────────────\n}\n"]}
1
+ {"version":3,"file":"SnapKeyring.cjs","sourceRoot":"","sources":["../../src/v2/SnapKeyring.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,uDAA6D;AAM7D,iDAAuD;AACvD,kEAAsF;AACtF,uDAA+D;AAI/D,uDAA8E;AAE9E,6CAAoC;AAEpC,4CAKoB;AACpB,wDAA8D;AAE9D,wDAAiD;AAEjD,sCAA2C;AAE3C;;;;GAIG;AACU,QAAA,kBAAkB,GAAwB,MAAM,CAAC,MAAM,CAAC;IACnE,MAAM,EAAE,EAAE;CACX,CAAC,CAAC;AAEH;;;;;GAKG;AACU,QAAA,sBAAsB,GAAG,IAAA,oBAAM,EAAC;IAC3C,MAAM,EAAE,IAAA,oBAAM,GAAE;IAChB,QAAQ,EAAE,IAAA,oBAAM,EACd,IAAA,oBAAM,GAAE,EACR,IAAA,mBAAK,EAAC,CAAC,kCAAoB,EAAE,gCAAsB,CAAC,CAAC,CACtD;CACF,CAAC,CAAC;AA6CH;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,OAAgB;IAC5C,OAAO,OAAO,CAAC,IAAI,KAAK,gBAAW,CAAC,IAAI,CAAC;AAC3C,CAAC;AAFD,sCAEC;AAED;;;;;;;;GAQG;AACH,MAAa,WAAW;IAwCtB,YAAY,EACV,SAAS,EACT,SAAS,EACT,uBAAuB,GAAG,KAAK,GACZ;;QA3CrB,gFAAgF;QACvE,wCAAkC;QAE3C,gEAAgE;QACvD,yCAAiC;QAEjC,yCAAiC;QAEjC,uDAAkC;QAE3C;;;WAGG;QACM,oCAAa;QAEtB,kDAAkD;QAClD,uCAAyC;QAEzC;;;WAGG;QACH,kCAA+B;QAE/B,iDAAiD;QACjD,qBAAqB;QACrB,iDAAiD;QAExC,SAAI,GAAG,GAAG,gBAAW,CAAC,IAAI,EAAW,CAAC;QAe7C,uBAAA,IAAI,yBAAa,IAAI,oCAAsB,EAA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B,CAAC,KAAK,EAAE,SAAgC,EAAmB,EAAE,CAC3D,uBAAA,IAAI,yBAAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,CACtC,CAAC,QAAQ,CAAC,CAAC;AACd,CAAC;IA0ZC,IAAI,uBAAA,IAAI,4BAAS,KAAK,SAAS,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;IACJ,CAAC;AACH,CAAC;IAQC,MAAM,IAAI,GAAG,uBAAA,IAAI,8BAAW,CAAC,IAAI,CAAC,wBAAwB,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IACzE,uBAAuB;IACvB,6EAA6E;IAC7E,+EAA+E;IAC/E,6CAA6C;IAC7C,+EAA+E;IAC/E,8BAA8B;IAC9B,OAAO,IAAI,EAAE,QAAQ,CAAC,kBAAkB,CAAC,mBAAmB,CAAC;QAC3D,EAAE,YAA+C,CAAC;AACtD,CAAC,6EASmB,OAAuB;IACzC,MAAM,OAAO,GAAG,IAAA,iCAAuB,EAAC,OAAO,CAAC,CAAC;IACjD,MAAM,QAAQ,GAAG,uBAAA,IAAI,6BAAU,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAChD,IAAI,QAAQ,IAAI,IAAA,iCAAuB,EAAC,QAAQ,CAAC,KAAK,OAAO,EAAE,CAAC;QAC9D,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAvjBe,gBAAI,GAAG,GAAG,gBAAW,CAAC,IAAI,EAAW,AAAjC,CAAkC","sourcesContent":["import type { KeyringAccount } from '@metamask/keyring-api';\nimport { KeyringAccountStruct } from '@metamask/keyring-api';\nimport type {\n CreateAccountOptions,\n Keyring,\n KeyringCapabilities,\n} from '@metamask/keyring-api/v2';\nimport { KeyringType } from '@metamask/keyring-api/v2';\nimport { KeyringInternalSnapClient } from '@metamask/keyring-internal-snap-client/v2';\nimport { KeyringAccountRegistry } from '@metamask/keyring-sdk';\nimport type { AccountId } from '@metamask/keyring-utils';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type { Infer } from '@metamask/superstruct';\nimport { assert, object, record, string, union } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport {\n KeyringAccountV1Struct,\n normalizeAccount,\n normalizeAccountAddress,\n transformAccount,\n} from '../account';\nimport { isAccountV1, migrateAccountV1 } from '../migrations';\nimport type { SnapKeyringMessenger } from '../SnapKeyringMessenger';\nimport { SnapKeyringV1 } from '../SnapKeyringV1';\nimport type { AccountMethod, SnapKeyringV1Callbacks } from '../SnapKeyringV1';\nimport { equalsIgnoreCase } from '../util';\n\n/**\n * Default, empty capabilities used until the snap manifest is read on\n * `deserialize`. Typed (no cast) so that adding a new required\n * `KeyringCapabilities` field surfaces here as a compile error.\n */\nexport const EMPTY_CAPABILITIES: KeyringCapabilities = Object.freeze({\n scopes: [],\n});\n\n/**\n * Superstruct schema for {@link SnapKeyringState}.\n *\n * Accepts both v1 accounts (missing `scopes`) and v2 accounts so that\n * persisted state can be validated before migration.\n */\nexport const SnapKeyringStateStruct = object({\n snapId: string(),\n accounts: record(\n string(),\n union([KeyringAccountStruct, KeyringAccountV1Struct]),\n ),\n});\n\n/**\n * Serialized state of a single SnapKeyring instance.\n *\n * Note: this is an internal format only used between SnapKeyring and its\n * parent SnapKeyring. The external KeyringState format (flat `{ account,\n * snapId }` map) is preserved by SnapKeyring.serialize / deserialize.\n *\n * Inferred from {@link SnapKeyringStateStruct}: `snapId` is `string`\n * (not the branded `SnapId`) so the shape stays JSON-compatible without\n * unsafe casts.\n */\nexport type SnapKeyringState = Infer<typeof SnapKeyringStateStruct>;\n\n/**\n * Callbacks injected by the parent `SnapKeyring` for global coordination.\n */\nexport type SnapKeyringCallbacks = SnapKeyringV1Callbacks & {\n /**\n * Run a callback under a global lock to prevent TOCTOU races in\n * `createAccounts` when multiple snaps call `assertAccountCanBeUsed`\n * concurrently.\n *\n * Optional: if omitted, `SnapKeyringV2` falls back to its own per-instance\n * `Mutex`, which is sufficient when the keyring is used standalone.\n */\n withLock?: <Result>(callback: () => Promise<Result>) => Promise<Result>;\n};\n\ntype SnapKeyringOptions = {\n messenger: SnapKeyringMessenger;\n callbacks: SnapKeyringCallbacks;\n isAnyAccountTypeAllowed?: boolean;\n};\n\n/**\n * Holds the v2 snap client once a {@link SnapKeyring} instance has been bound\n * via {@link SnapKeyring.bindSnapId}.\n */\ntype SnapKeyringContext = {\n snapId: SnapId;\n client: KeyringInternalSnapClient;\n};\n\n/**\n * Checks if a given keyring is a Snap keyring (v2).\n *\n * @param keyring - The keyring to check.\n * @returns `true` if the keyring is a Snap keyring (v2), `false` otherwise.\n */\nexport function isSnapKeyring(keyring: Keyring): keyring is SnapKeyring {\n return keyring.type === KeyringType.Snap;\n}\n\n/**\n * Per-snap keyring that implements `Keyring` (v2).\n *\n * Owns the account registry and messenger. For v1 snaps (those that do not\n * declare `endowment:keyring` capabilities in their manifest), a\n * {@link SnapKeyringV1} instance is created on `deserialize` and held under\n * {@link SnapKeyring.v1}. V2 snaps have `v1 === undefined` and communicate\n * directly through the v2 client without the `{ pending, result }` envelope.\n */\nexport class SnapKeyring implements Keyring {\n /** Account registry — shared by reference with the v1 instance when present. */\n readonly #registry: KeyringAccountRegistry;\n\n /** Messenger for snap controller calls and event publishing. */\n readonly #messenger: SnapKeyringMessenger;\n\n readonly #callbacks: SnapKeyringCallbacks;\n\n readonly #isAnyAccountTypeAllowed: boolean;\n\n /**\n * Mutex that serializes `createAccounts` calls on this snap instance.\n * Owned here so that each `SnapKeyring` is fully self-contained.\n */\n readonly #lock: Mutex;\n\n /** V2 snap client. Set via {@link bindSnapId}. */\n #context: SnapKeyringContext | undefined;\n\n /**\n * V1 instance, present only when the snap does not declare v2 capabilities.\n * Created on `deserialize()` after reading the snap manifest.\n */\n #v1: SnapKeyringV1 | undefined;\n\n // ──────────────────────────────────────────────\n // Keyring properties\n // ──────────────────────────────────────────────\n\n readonly type = `${KeyringType.Snap}` as const;\n\n static readonly type = `${KeyringType.Snap}` as const;\n\n /**\n * Capabilities are snap-specific. Initialized empty and can be updated\n * by the parent when snap metadata becomes available.\n */\n capabilities: KeyringCapabilities;\n\n constructor({\n messenger,\n callbacks,\n isAnyAccountTypeAllowed = false,\n }: SnapKeyringOptions) {\n this.#registry = new KeyringAccountRegistry();\n this.#messenger = messenger;\n this.#callbacks = callbacks;\n this.#isAnyAccountTypeAllowed = isAnyAccountTypeAllowed;\n this.#lock = new Mutex();\n\n // Default capabilities; replaced from the snap manifest on `deserialize`.\n this.capabilities = EMPTY_CAPABILITIES;\n }\n\n /**\n * Gets the v1 instance for this snap, or `undefined` if the snap is v2-only.\n *\n * @returns The v1 instance, or `undefined` if the snap is v2-only.\n *\n * Use this to make v1 calls explicit:\n * ```ts\n * keyring.v1?.signTransaction(account, tx);\n * ```\n */\n get v1(): SnapKeyringV1 | undefined {\n return this.#v1;\n }\n\n /**\n * The snap ID this instance is scoped to.\n *\n * @returns The snap ID.\n * @throws If the keyring has not been initialized yet.\n */\n get snapId(): SnapId {\n /* istanbul ignore next */\n if (this.#context === undefined) {\n throw new Error(\n 'SnapKeyring has not been initialized: call deserialize() first',\n );\n }\n return this.#context.snapId;\n }\n\n /**\n * Bind this keyring to a snap ID and initialize the v2 client.\n *\n * Idempotent for the same `snapId`; throws if called again with a different\n * one to prevent accidentally swapping a keyring's identity.\n *\n * @param snapId - The snap ID to bind to.\n */\n protected bindSnapId(snapId: SnapId): void {\n if (this.#context !== undefined && this.#context.snapId !== snapId) {\n throw new Error(\n `SnapKeyring bound to '${this.#context.snapId}' cannot be rebound to '${snapId}'`,\n );\n }\n if (this.#context === undefined) {\n this.#context = {\n snapId,\n client: new KeyringInternalSnapClient({\n messenger: this.#messenger,\n snapId,\n }),\n };\n }\n }\n\n /**\n * Returns the v2 snap client.\n *\n * @returns The v2 snap client.\n * @throws If the keyring is not yet initialized.\n */\n get #client(): KeyringInternalSnapClient {\n /* istanbul ignore next */\n if (this.#context === undefined) {\n throw new Error('SnapKeyring is not bound to a snap ID');\n }\n return this.#context.client;\n }\n\n /**\n * Destroy this keyring, rejecting any pending v1 requests.\n *\n * @returns A promise that resolves when the keyring is destroyed.\n */\n async destroy(): Promise<void> {\n await this.#v1?.destroy();\n this.#v1 = undefined;\n }\n\n /**\n * Run a callback under the appropriate lock.\n *\n * Prefers the injected `withLock` callback (global lock provided by\n * `SnapKeyring`) so that `createAccounts` calls across different snaps\n * are serialized. Falls back to the per-instance `#lock` when no global\n * lock is provided (e.g. standalone use in tests).\n *\n * @param callback - Operation to run under the lock.\n * @returns The result of the callback.\n */\n async #withLock<Result>(callback: () => Promise<Result>): Promise<Result> {\n return (\n this.#callbacks.withLock ??\n (async (operation: () => Promise<Result>): Promise<Result> =>\n this.#lock.runExclusive(operation))\n )(callback);\n }\n\n // ──────────────────────────────────────────────\n // Keyring methods\n // ──────────────────────────────────────────────\n\n /**\n * Returns all accounts managed by this keyring.\n *\n * @returns A promise that resolves to an array of all accounts.\n */\n async getAccounts(): Promise<KeyringAccount[]> {\n this.#assertInitialized();\n return this.accounts();\n }\n\n /**\n * Returns the account with the specified ID.\n *\n * @param accountId - ID of the account to retrieve.\n * @returns A promise that resolves to the account.\n */\n async getAccount(accountId: AccountId): Promise<KeyringAccount> {\n this.#assertInitialized();\n const account = this.lookupAccount(accountId);\n if (!account) {\n throw new Error(\n `Account '${accountId}' not found in snap '${this.snapId}'`,\n );\n }\n return account;\n }\n\n /**\n * Creates one or more new accounts according to the provided options.\n *\n * Deterministic account creation MUST be idempotent, meaning that for\n * deterministic algorithms, like BIP-44, calling this method with the same\n * options should always return the same accounts, even if the accounts\n * already exist in the keyring.\n *\n * NOTE: If some accounts are not allowed (non-unique address, unsupported\n * generic account), this method will skip their creation and ask the Snap\n * to remove them from its state.\n *\n * @param options - Options describing how to create the account(s).\n * @returns A promise that resolves to an array of the created account objects.\n */\n async createAccounts(\n options: CreateAccountOptions,\n ): Promise<KeyringAccount[]> {\n this.#assertInitialized();\n return this.#withLock(async () => {\n // Keep track of address/account ID part of this batch, to avoid having duplicates.\n const batchAddresses = new Set<string>();\n const batchIds = new Set<string>();\n\n const accounts: KeyringAccount[] = [];\n const newAccounts: KeyringAccount[] = [];\n let snapAccounts: KeyringAccount[];\n if (this.#v1) {\n // v1 snap: the v1 client wraps options in `{ options }` before sending\n // `keyring_createAccounts`, while the v2 client sends flat options.\n // Route through v1 so v1 snaps receive the format they expect.\n snapAccounts = await this.#v1.createAccounts(options);\n } else {\n // v2 snap: call snap directly with flat options.\n snapAccounts = await this.#client.createAccounts(options);\n }\n\n try {\n for (const snapAccount of snapAccounts) {\n let account = normalizeAccount(transformAccount(snapAccount));\n const { address } = account;\n\n // Check for idempotency.\n const existingAccount = this.#getExistingAccount(account);\n if (existingAccount) {\n // NOTE: We re-use the account from the internal state to avoid having the Snap\n // mutating the account object without updating the map.\n account = existingAccount;\n } else {\n await this.#callbacks.assertAccountCanBeUsed(account);\n\n // Also check for transient accounts that are not yet part of the keyring\n // state.\n if (batchAddresses.has(address) || batchIds.has(account.id)) {\n throw new Error(\n `Account '${account.id}' is already part of this batch (same address or account ID)`,\n );\n }\n batchAddresses.add(address);\n batchIds.add(account.id);\n\n // NOTE: This method does not rely on the `AccountCreated` event to add\n // accounts to the keyring, so we have to add them to the state manually.\n newAccounts.push(account);\n }\n\n // New AND existing accounts are returned to the caller no matter what.\n accounts.push(account);\n }\n\n // We update the keyring state only if needed.\n if (newAccounts.length > 0) {\n for (const account of newAccounts) {\n this.setAccount(account);\n }\n }\n\n return accounts;\n } catch (error) {\n // Rollback Snap state.\n for (const snapAccount of snapAccounts) {\n // Make sure to only delete accounts that were not part of the keyring state.\n if (!this.#getExistingAccount(snapAccount)) {\n try {\n await this.#client.deleteAccount(snapAccount.id);\n } catch (rollbackError) {\n // Best-effort rollback; log snap-side failures for observability.\n console.error(\n `Account '${snapAccount.id}' may not have been removed from snap '${this.snapId}' during createAccounts rollback:`,\n rollbackError,\n );\n }\n }\n }\n\n throw error;\n }\n });\n }\n\n /**\n * Deletes the account with the specified ID.\n *\n * Removes the account from the local registry (firing `onUnregister` so the\n * parent can update its index), then asks the snap to delete it.\n *\n * @param accountId - ID of the account to delete.\n */\n async deleteAccount(accountId: AccountId): Promise<void> {\n this.#assertInitialized();\n // Always remove the account from the registry, even if the Snap is going to\n // fail to delete it. removeAccount fires onUnregister to clean #accountIndex.\n this.removeAccount(accountId);\n\n try {\n await this.#client.deleteAccount(accountId);\n } catch (error) {\n // If the Snap failed to delete the account, log the error and continue\n // with the account deletion, otherwise the account will be stuck in the\n // keyring.\n console.error(\n `Account '${accountId}' may not have been removed from snap '${this.snapId}':`,\n error,\n );\n }\n }\n\n /**\n * Submits a request to the keyring.\n *\n * For v1 snaps (those without declared capabilities), delegates to the v1\n * event-driven flow that handles the `{ pending, result }` envelope.\n * For v2 snaps, calls the snap directly via the v2 client which returns\n * `Json` with no envelope.\n *\n * @param request - The keyring request to submit.\n * @param request.id - The request ID.\n * @param request.origin - The sender origin.\n * @param request.scope - The CAIP-2 chain ID.\n * @param request.account - The account ID.\n * @param request.request - The inner JSON-RPC request.\n * @param request.request.method - The method to call.\n * @param request.request.params - The method parameters.\n * @returns A promise that resolves to the response.\n */\n async submitRequest(request: {\n id: string;\n origin: string;\n scope: string;\n account: AccountId;\n request: {\n method: string;\n params?: Json[] | Record<string, Json>;\n };\n }): Promise<Json> {\n this.#assertInitialized();\n const account = this.lookupAccount(request.account);\n if (!account) {\n throw new Error(\n `Account '${request.account}' not found in snap '${this.snapId}'`,\n );\n }\n if (this.#v1) {\n // v1 snap: use event-driven flow with { pending, result } envelope handling.\n return this.#v1.submitSnapRequest({\n origin: request.origin,\n account,\n method: request.request.method as AccountMethod,\n params: request.request.params,\n scope: request.scope,\n noPending: false,\n });\n }\n // v2 snap: call snap directly, returns Json (no envelope).\n return this.#client.submitRequest({\n id: request.id,\n origin: request.origin,\n scope: request.scope,\n account: request.account,\n request: request.request,\n });\n }\n\n // ──────────────────────────────────────────────\n // Internal API (used by parent SnapKeyring for event handling, routing, etc.)\n // ──────────────────────────────────────────────\n\n /**\n * Upsert an account into the registry.\n *\n * Fires `onRegister` only when the account is new (not already present).\n * Safe to call for updates -- the parent index is already populated in that\n * case and the no-op path avoids a redundant write.\n *\n * @param account - The account to add or update.\n */\n setAccount(account: KeyringAccount): void {\n const isNew = !this.#registry.has(account.id);\n this.#registry.set(account);\n if (isNew) {\n this.#callbacks.onRegister?.(account.id);\n }\n }\n\n /**\n * Remove an account from the registry.\n *\n * Fires `onUnregister` so the parent can drop the account from its index.\n *\n * @param id - The account ID to remove.\n * @returns `true` if the account was removed, `false` if it was not found.\n */\n removeAccount(id: AccountId): boolean {\n if (!this.#registry.has(id)) {\n return false;\n }\n this.#registry.delete(id);\n this.#callbacks.onUnregister?.(id);\n return true;\n }\n\n /**\n * Check whether an account exists in this keyring.\n *\n * @param id - The account ID to check.\n * @returns `true` if the account exists.\n */\n hasAccount(id: AccountId): boolean {\n return this.#registry.has(id);\n }\n\n /**\n * Get an account by its ID.\n *\n * @param id - The account ID to look up.\n * @returns The account, or `undefined` if not found.\n */\n lookupAccount(id: AccountId): KeyringAccount | undefined {\n return this.#registry.get(id);\n }\n\n /**\n * Get an account by address (case-insensitive).\n *\n * Performs an O(1) exact lookup first; falls back to a linear scan to\n * handle addresses stored with different casing.\n *\n * @param address - The address to look up.\n * @returns The account, or `undefined` if not found.\n */\n lookupByAddress(address: string): KeyringAccount | undefined {\n const id = this.#registry.getAccountId(address);\n if (id !== undefined) {\n return this.#registry.get(id);\n }\n // The fallback only runs when the exact-match branch above misses,\n // which in practice only happens for EVM addresses with casing\n // differences (checksummed vs lowercase). Non-EVM addresses are\n // case-sensitive and always resolve on the exact branch.\n return this.#registry\n .values()\n .find((account) => equalsIgnoreCase(account.address, address));\n }\n\n /**\n * Get all accounts in this keyring (synchronous).\n *\n * This exists alongside the async `getAccounts()` (from `Keyring`) because\n * `SnapKeyring` needs synchronous access for iteration in `serialize`,\n * `listAccounts`, `hasSnapId`, etc. without awaiting.\n *\n * @returns An array of all accounts.\n */\n accounts(): KeyringAccount[] {\n return this.#registry.values();\n }\n\n /**\n * Serialize this keyring's state.\n *\n * The returned object uses the internal per-snap format; the parent\n * `SnapKeyring` reconstructs the flat external format in its own\n * `serialize()`.\n *\n * @returns The serialized state.\n */\n async serialize(): Promise<SnapKeyringState> {\n const accounts: SnapKeyringState['accounts'] = {};\n for (const account of this.#registry.values()) {\n accounts[account.id] = account;\n }\n const state: SnapKeyringState = {\n snapId: this.snapId,\n accounts,\n };\n return state;\n }\n\n /**\n * Restore this keyring from a serialized state.\n *\n * Validates the payload (accepting both v1 and v2 account shapes), migrates\n * any v1 accounts to v2, then replaces the registry. Also determines whether\n * the snap is v1 or v2 by reading its manifest capabilities: if no\n * capabilities are declared, a {@link SnapKeyringV1} instance is created and\n * held under {@link SnapKeyring.v1}.\n *\n * @param state - The state to deserialize.\n * @returns A promise that resolves when deserialization is complete.\n */\n async deserialize(state: Json): Promise<void> {\n // Validate the raw payload — accepts both v1 and v2 account shapes.\n assert(state, SnapKeyringStateStruct);\n\n // Bind the keyring to its snap ID (idempotent for the same ID, throws on\n // mismatch to prevent swapping a keyring's identity via deserialize).\n this.bindSnapId(state.snapId as SnapId);\n\n // Refresh capabilities from the snap manifest on every deserialize, falling\n // back to the empty default so a re-hydrate clears any previously-loaded\n // capabilities when the snap no longer declares them.\n const capabilities = this.#resolveKeyringCapabilities();\n this.capabilities = capabilities ?? EMPTY_CAPABILITIES;\n\n // Determine snap version and create a v1 instance if needed.\n const v1 = capabilities === undefined;\n if (v1) {\n // v1 snap: no declared capabilities. Create a SnapKeyringV1 instance\n // that shares the registry and messenger owned by this class.\n if (this.#v1 === undefined) {\n this.#v1 = new SnapKeyringV1({\n messenger: this.#messenger,\n callbacks: this.#callbacks,\n registry: this.#registry,\n isAnyAccountTypeAllowed: this.#isAnyAccountTypeAllowed,\n });\n this.#v1.bindSnapId(state.snapId as SnapId);\n }\n } else {\n // v2 snap: tear down any stale v1 instance (e.g. after a manifest update).\n await this.#v1?.destroy();\n this.#v1 = undefined;\n }\n\n // Migrate v1 accounts to v2.\n const migratedAccounts: Record<string, KeyringAccount> = {};\n for (const [id, rawAccount] of Object.entries(state.accounts)) {\n if (isAccountV1(rawAccount)) {\n console.info(\n `SnapKeyring - Found a KeyringAccountV1, migrating to V2: ${rawAccount.id}`,\n );\n migratedAccounts[id] = migrateAccountV1(rawAccount);\n } else {\n migratedAccounts[id] = rawAccount as KeyringAccount;\n }\n }\n\n // Apply the migrated state to the registry.\n for (const id of [...this.#registry.keys()]) {\n this.removeAccount(id);\n }\n\n for (const account of Object.values(migratedAccounts)) {\n this.setAccount(account);\n }\n }\n\n // ──────────────────────────────────────────────\n // Private helpers\n // ──────────────────────────────────────────────\n\n /**\n * Assert that the keyring has been initialized.\n *\n * @throws An error if the keyring has not been initialized.\n */\n #assertInitialized(): void {\n if (this.#context === undefined) {\n throw new Error(\n 'SnapKeyring has not been initialized: call deserialize() first',\n );\n }\n }\n\n /**\n * Resolve the keyring capabilities from the snap manifest.\n *\n * @returns The keyring capabilities, or `undefined` if the snap manifest does not declare any capabilities.\n */\n #resolveKeyringCapabilities(): KeyringCapabilities | undefined {\n const snap = this.#messenger.call('SnapController:getSnap', this.snapId);\n // READ THIS CAREFULLY:\n // We are not validating the shape of the capabilities here, because there is\n // manifest validation done already on the snaps side, the snaps repo maintains\n // a copy of the `KeyringCapabilitiesStruct`.\n // We must ensure that both structs are always in-sync, otherwise the type-cast\n // could cause runtime issues!\n return snap?.manifest.initialPermissions['endowment:keyring']\n ?.capabilities as KeyringCapabilities | undefined;\n }\n\n /**\n * Check whether an account with the same ID and address already exists in\n * the registry. Used for idempotent account creation.\n *\n * @param account - The account to check against the registry.\n * @returns The existing account if found, `undefined` otherwise.\n */\n #getExistingAccount(account: KeyringAccount): KeyringAccount | undefined {\n const address = normalizeAccountAddress(account);\n const existing = this.#registry.get(account.id);\n if (existing && normalizeAccountAddress(existing) === address) {\n return existing;\n }\n return undefined;\n }\n}\n"]}