@metamask-previews/eth-snap-keyring 22.3.0-e51c895 → 22.4.0-5951828
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.
- package/CHANGELOG.md +21 -1
- package/dist/SnapKeyring.cjs +31 -16
- package/dist/SnapKeyring.cjs.map +1 -1
- package/dist/SnapKeyring.d.cts +1 -1
- package/dist/SnapKeyring.d.cts.map +1 -1
- package/dist/SnapKeyring.d.mts +1 -1
- package/dist/SnapKeyring.d.mts.map +1 -1
- package/dist/SnapKeyring.mjs +31 -16
- package/dist/SnapKeyring.mjs.map +1 -1
- package/dist/SnapKeyringV1.cjs +16 -2
- package/dist/SnapKeyringV1.cjs.map +1 -1
- package/dist/SnapKeyringV1.d.cts +21 -2
- package/dist/SnapKeyringV1.d.cts.map +1 -1
- package/dist/SnapKeyringV1.d.mts +21 -2
- package/dist/SnapKeyringV1.d.mts.map +1 -1
- package/dist/SnapKeyringV1.mjs +16 -2
- package/dist/SnapKeyringV1.mjs.map +1 -1
- package/dist/events.cjs +4 -5
- package/dist/events.cjs.map +1 -1
- package/dist/events.d.cts +4 -4
- package/dist/events.d.cts.map +1 -1
- package/dist/events.d.mts +4 -4
- package/dist/events.d.mts.map +1 -1
- package/dist/events.mjs +1 -2
- package/dist/events.mjs.map +1 -1
- package/dist/v2/SnapKeyring.cjs +202 -58
- package/dist/v2/SnapKeyring.cjs.map +1 -1
- package/dist/v2/SnapKeyring.d.cts +67 -24
- package/dist/v2/SnapKeyring.d.cts.map +1 -1
- package/dist/v2/SnapKeyring.d.mts +67 -24
- package/dist/v2/SnapKeyring.d.mts.map +1 -1
- package/dist/v2/SnapKeyring.mjs +202 -58
- package/dist/v2/SnapKeyring.mjs.map +1 -1
- package/package.json +7 -7
package/dist/v2/SnapKeyring.cjs
CHANGED
|
@@ -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
|
|
55
|
+
* Per-snap keyring that implements `Keyring` (v2).
|
|
46
56
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
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
|
|
56
|
-
constructor(
|
|
57
|
-
super(options);
|
|
63
|
+
class SnapKeyring {
|
|
64
|
+
constructor({ messenger, callbacks, isAnyAccountTypeAllowed = false, }) {
|
|
58
65
|
_SnapKeyring_instances.add(this);
|
|
59
|
-
/**
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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,
|
|
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
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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
|
-
*
|
|
110
|
+
* The snap ID this instance is scoped to.
|
|
83
111
|
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
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
|
|
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
|
-
|
|
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.
|
|
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.
|
|
@@ -176,9 +252,9 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
176
252
|
// Rollback Snap state.
|
|
177
253
|
for (const snapAccount of snapAccounts) {
|
|
178
254
|
// Make sure to only delete accounts that were not part of the keyring state.
|
|
179
|
-
if (!this.
|
|
255
|
+
if (!__classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_getExistingAccount).call(this, snapAccount)) {
|
|
180
256
|
try {
|
|
181
|
-
await this.
|
|
257
|
+
await __classPrivateFieldGet(this, _SnapKeyring_instances, "a", _SnapKeyring_client_get).deleteAccount(snapAccount.id);
|
|
182
258
|
}
|
|
183
259
|
catch (rollbackError) {
|
|
184
260
|
// Best-effort rollback; log snap-side failures for observability.
|
|
@@ -199,11 +275,12 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
199
275
|
* @param accountId - ID of the account to delete.
|
|
200
276
|
*/
|
|
201
277
|
async deleteAccount(accountId) {
|
|
278
|
+
__classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_assertInitialized).call(this);
|
|
202
279
|
// Always remove the account from the registry, even if the Snap is going to
|
|
203
280
|
// fail to delete it. removeAccount fires onUnregister to clean #accountIndex.
|
|
204
281
|
this.removeAccount(accountId);
|
|
205
282
|
try {
|
|
206
|
-
await this.
|
|
283
|
+
await __classPrivateFieldGet(this, _SnapKeyring_instances, "a", _SnapKeyring_client_get).deleteAccount(accountId);
|
|
207
284
|
}
|
|
208
285
|
catch (error) {
|
|
209
286
|
// If the Snap failed to delete the account, log the error and continue
|
|
@@ -215,12 +292,13 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
215
292
|
/**
|
|
216
293
|
* Submits a request to the keyring.
|
|
217
294
|
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
295
|
+
* For v1 snaps (those without declared capabilities), delegates to the v1
|
|
296
|
+
* event-driven flow that handles the `{ pending, result }` envelope.
|
|
297
|
+
* For v2 snaps, calls the snap directly via the v2 client which returns
|
|
298
|
+
* `Json` with no envelope.
|
|
221
299
|
*
|
|
222
300
|
* @param request - The keyring request to submit.
|
|
223
|
-
* @param request.id - The request ID
|
|
301
|
+
* @param request.id - The request ID.
|
|
224
302
|
* @param request.origin - The sender origin.
|
|
225
303
|
* @param request.scope - The CAIP-2 chain ID.
|
|
226
304
|
* @param request.account - The account ID.
|
|
@@ -230,17 +308,29 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
230
308
|
* @returns A promise that resolves to the response.
|
|
231
309
|
*/
|
|
232
310
|
async submitRequest(request) {
|
|
311
|
+
__classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_assertInitialized).call(this);
|
|
233
312
|
const account = this.lookupAccount(request.account);
|
|
234
313
|
if (!account) {
|
|
235
314
|
throw new Error(`Account '${request.account}' not found in snap '${this.snapId}'`);
|
|
236
315
|
}
|
|
237
|
-
|
|
316
|
+
if (__classPrivateFieldGet(this, _SnapKeyring_v1, "f")) {
|
|
317
|
+
// v1 snap: use event-driven flow with { pending, result } envelope handling.
|
|
318
|
+
return __classPrivateFieldGet(this, _SnapKeyring_v1, "f").submitSnapRequest({
|
|
319
|
+
origin: request.origin,
|
|
320
|
+
account,
|
|
321
|
+
method: request.request.method,
|
|
322
|
+
params: request.request.params,
|
|
323
|
+
scope: request.scope,
|
|
324
|
+
noPending: false,
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
// v2 snap: call snap directly, returns Json (no envelope).
|
|
328
|
+
return __classPrivateFieldGet(this, _SnapKeyring_instances, "a", _SnapKeyring_client_get).submitRequest({
|
|
329
|
+
id: request.id,
|
|
238
330
|
origin: request.origin,
|
|
239
|
-
account,
|
|
240
|
-
method: request.request.method,
|
|
241
|
-
params: request.request.params,
|
|
242
331
|
scope: request.scope,
|
|
243
|
-
|
|
332
|
+
account: request.account,
|
|
333
|
+
request: request.request,
|
|
244
334
|
});
|
|
245
335
|
}
|
|
246
336
|
// ──────────────────────────────────────────────
|
|
@@ -256,8 +346,8 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
256
346
|
* @param account - The account to add or update.
|
|
257
347
|
*/
|
|
258
348
|
setAccount(account) {
|
|
259
|
-
const isNew = !this.
|
|
260
|
-
this.
|
|
349
|
+
const isNew = !__classPrivateFieldGet(this, _SnapKeyring_registry, "f").has(account.id);
|
|
350
|
+
__classPrivateFieldGet(this, _SnapKeyring_registry, "f").set(account);
|
|
261
351
|
if (isNew) {
|
|
262
352
|
__classPrivateFieldGet(this, _SnapKeyring_callbacks, "f").onRegister?.(account.id);
|
|
263
353
|
}
|
|
@@ -271,10 +361,10 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
271
361
|
* @returns `true` if the account was removed, `false` if it was not found.
|
|
272
362
|
*/
|
|
273
363
|
removeAccount(id) {
|
|
274
|
-
if (!this.
|
|
364
|
+
if (!__classPrivateFieldGet(this, _SnapKeyring_registry, "f").has(id)) {
|
|
275
365
|
return false;
|
|
276
366
|
}
|
|
277
|
-
this.
|
|
367
|
+
__classPrivateFieldGet(this, _SnapKeyring_registry, "f").delete(id);
|
|
278
368
|
__classPrivateFieldGet(this, _SnapKeyring_callbacks, "f").onUnregister?.(id);
|
|
279
369
|
return true;
|
|
280
370
|
}
|
|
@@ -285,7 +375,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
285
375
|
* @returns `true` if the account exists.
|
|
286
376
|
*/
|
|
287
377
|
hasAccount(id) {
|
|
288
|
-
return this.
|
|
378
|
+
return __classPrivateFieldGet(this, _SnapKeyring_registry, "f").has(id);
|
|
289
379
|
}
|
|
290
380
|
/**
|
|
291
381
|
* Get an account by its ID.
|
|
@@ -294,7 +384,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
294
384
|
* @returns The account, or `undefined` if not found.
|
|
295
385
|
*/
|
|
296
386
|
lookupAccount(id) {
|
|
297
|
-
return this.
|
|
387
|
+
return __classPrivateFieldGet(this, _SnapKeyring_registry, "f").get(id);
|
|
298
388
|
}
|
|
299
389
|
/**
|
|
300
390
|
* Get an account by address (case-insensitive).
|
|
@@ -306,15 +396,15 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
306
396
|
* @returns The account, or `undefined` if not found.
|
|
307
397
|
*/
|
|
308
398
|
lookupByAddress(address) {
|
|
309
|
-
const id = this.
|
|
399
|
+
const id = __classPrivateFieldGet(this, _SnapKeyring_registry, "f").getAccountId(address);
|
|
310
400
|
if (id !== undefined) {
|
|
311
|
-
return this.
|
|
401
|
+
return __classPrivateFieldGet(this, _SnapKeyring_registry, "f").get(id);
|
|
312
402
|
}
|
|
313
403
|
// The fallback only runs when the exact-match branch above misses,
|
|
314
404
|
// which in practice only happens for EVM addresses with casing
|
|
315
405
|
// differences (checksummed vs lowercase). Non-EVM addresses are
|
|
316
406
|
// case-sensitive and always resolve on the exact branch.
|
|
317
|
-
return this
|
|
407
|
+
return __classPrivateFieldGet(this, _SnapKeyring_registry, "f")
|
|
318
408
|
.values()
|
|
319
409
|
.find((account) => (0, util_1.equalsIgnoreCase)(account.address, address));
|
|
320
410
|
}
|
|
@@ -328,7 +418,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
328
418
|
* @returns An array of all accounts.
|
|
329
419
|
*/
|
|
330
420
|
accounts() {
|
|
331
|
-
return this.
|
|
421
|
+
return __classPrivateFieldGet(this, _SnapKeyring_registry, "f").values();
|
|
332
422
|
}
|
|
333
423
|
/**
|
|
334
424
|
* Serialize this keyring's state.
|
|
@@ -341,7 +431,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
341
431
|
*/
|
|
342
432
|
async serialize() {
|
|
343
433
|
const accounts = {};
|
|
344
|
-
for (const account of this.
|
|
434
|
+
for (const account of __classPrivateFieldGet(this, _SnapKeyring_registry, "f").values()) {
|
|
345
435
|
accounts[account.id] = account;
|
|
346
436
|
}
|
|
347
437
|
const state = {
|
|
@@ -353,9 +443,11 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
353
443
|
/**
|
|
354
444
|
* Restore this keyring from a serialized state.
|
|
355
445
|
*
|
|
356
|
-
* Validates the payload (accepting both v1 and v2
|
|
357
|
-
* v1 accounts to v2, then replaces the registry.
|
|
358
|
-
*
|
|
446
|
+
* Validates the payload (accepting both v1 and v2 account shapes), migrates
|
|
447
|
+
* any v1 accounts to v2, then replaces the registry. Also determines whether
|
|
448
|
+
* the snap is v1 or v2 by reading its manifest capabilities: if no
|
|
449
|
+
* capabilities are declared, a {@link SnapKeyringV1} instance is created and
|
|
450
|
+
* held under {@link SnapKeyring.v1}.
|
|
359
451
|
*
|
|
360
452
|
* @param state - The state to deserialize.
|
|
361
453
|
* @returns A promise that resolves when deserialization is complete.
|
|
@@ -366,6 +458,31 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
366
458
|
// Bind the keyring to its snap ID (idempotent for the same ID, throws on
|
|
367
459
|
// mismatch to prevent swapping a keyring's identity via deserialize).
|
|
368
460
|
this.bindSnapId(state.snapId);
|
|
461
|
+
// Refresh capabilities from the snap manifest on every deserialize, falling
|
|
462
|
+
// back to the empty default so a re-hydrate clears any previously-loaded
|
|
463
|
+
// capabilities when the snap no longer declares them.
|
|
464
|
+
const capabilities = __classPrivateFieldGet(this, _SnapKeyring_instances, "m", _SnapKeyring_resolveKeyringCapabilities).call(this);
|
|
465
|
+
this.capabilities = capabilities ?? exports.EMPTY_CAPABILITIES;
|
|
466
|
+
// Determine snap version and create a v1 instance if needed.
|
|
467
|
+
const v1 = capabilities === undefined;
|
|
468
|
+
if (v1) {
|
|
469
|
+
// v1 snap: no declared capabilities. Create a SnapKeyringV1 instance
|
|
470
|
+
// that shares the registry and messenger owned by this class.
|
|
471
|
+
if (__classPrivateFieldGet(this, _SnapKeyring_v1, "f") === undefined) {
|
|
472
|
+
__classPrivateFieldSet(this, _SnapKeyring_v1, new SnapKeyringV1_1.SnapKeyringV1({
|
|
473
|
+
messenger: __classPrivateFieldGet(this, _SnapKeyring_messenger, "f"),
|
|
474
|
+
callbacks: __classPrivateFieldGet(this, _SnapKeyring_callbacks, "f"),
|
|
475
|
+
registry: __classPrivateFieldGet(this, _SnapKeyring_registry, "f"),
|
|
476
|
+
isAnyAccountTypeAllowed: __classPrivateFieldGet(this, _SnapKeyring_isAnyAccountTypeAllowed, "f"),
|
|
477
|
+
}), "f");
|
|
478
|
+
__classPrivateFieldGet(this, _SnapKeyring_v1, "f").bindSnapId(state.snapId);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
else {
|
|
482
|
+
// v2 snap: tear down any stale v1 instance (e.g. after a manifest update).
|
|
483
|
+
await __classPrivateFieldGet(this, _SnapKeyring_v1, "f")?.destroy();
|
|
484
|
+
__classPrivateFieldSet(this, _SnapKeyring_v1, undefined, "f");
|
|
485
|
+
}
|
|
369
486
|
// Migrate v1 accounts to v2.
|
|
370
487
|
const migratedAccounts = {};
|
|
371
488
|
for (const [id, rawAccount] of Object.entries(state.accounts)) {
|
|
@@ -378,7 +495,7 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
378
495
|
}
|
|
379
496
|
}
|
|
380
497
|
// Apply the migrated state to the registry.
|
|
381
|
-
for (const id of [...this.
|
|
498
|
+
for (const id of [...__classPrivateFieldGet(this, _SnapKeyring_registry, "f").keys()]) {
|
|
382
499
|
this.removeAccount(id);
|
|
383
500
|
}
|
|
384
501
|
for (const account of Object.values(migratedAccounts)) {
|
|
@@ -387,14 +504,20 @@ class SnapKeyring extends SnapKeyringV1_1.SnapKeyringV1 {
|
|
|
387
504
|
}
|
|
388
505
|
}
|
|
389
506
|
exports.SnapKeyring = SnapKeyring;
|
|
390
|
-
_SnapKeyring_callbacks = new WeakMap(), _SnapKeyring_lock = new WeakMap(), _SnapKeyring_instances = new WeakSet(),
|
|
507
|
+
_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() {
|
|
508
|
+
/* istanbul ignore next */
|
|
509
|
+
if (__classPrivateFieldGet(this, _SnapKeyring_context, "f") === undefined) {
|
|
510
|
+
throw new Error('SnapKeyring is not bound to a snap ID');
|
|
511
|
+
}
|
|
512
|
+
return __classPrivateFieldGet(this, _SnapKeyring_context, "f").client;
|
|
513
|
+
}, _SnapKeyring_withLock =
|
|
391
514
|
/**
|
|
392
515
|
* Run a callback under the appropriate lock.
|
|
393
516
|
*
|
|
394
517
|
* Prefers the injected `withLock` callback (global lock provided by
|
|
395
518
|
* `SnapKeyring`) so that `createAccounts` calls across different snaps
|
|
396
519
|
* are serialized. Falls back to the per-instance `#lock` when no global
|
|
397
|
-
* lock is provided.g. standalone use in tests).
|
|
520
|
+
* lock is provided (e.g. standalone use in tests).
|
|
398
521
|
*
|
|
399
522
|
* @param callback - Operation to run under the lock.
|
|
400
523
|
* @returns The result of the callback.
|
|
@@ -402,6 +525,27 @@ _SnapKeyring_callbacks = new WeakMap(), _SnapKeyring_lock = new WeakMap(), _Snap
|
|
|
402
525
|
async function _SnapKeyring_withLock(callback) {
|
|
403
526
|
return (__classPrivateFieldGet(this, _SnapKeyring_callbacks, "f").withLock ??
|
|
404
527
|
(async (operation) => __classPrivateFieldGet(this, _SnapKeyring_lock, "f").runExclusive(operation)))(callback);
|
|
528
|
+
}, _SnapKeyring_assertInitialized = function _SnapKeyring_assertInitialized() {
|
|
529
|
+
if (__classPrivateFieldGet(this, _SnapKeyring_context, "f") === undefined) {
|
|
530
|
+
throw new Error('SnapKeyring has not been initialized: call deserialize() first');
|
|
531
|
+
}
|
|
532
|
+
}, _SnapKeyring_resolveKeyringCapabilities = function _SnapKeyring_resolveKeyringCapabilities() {
|
|
533
|
+
const snap = __classPrivateFieldGet(this, _SnapKeyring_messenger, "f").call('SnapController:getSnap', this.snapId);
|
|
534
|
+
// READ THIS CAREFULLY:
|
|
535
|
+
// We are not validating the shape of the capabilities here, because there is
|
|
536
|
+
// manifest validation done already on the snaps side, the snaps repo maintains
|
|
537
|
+
// a copy of the `KeyringCapabilitiesStruct`.
|
|
538
|
+
// We must ensure that both structs are always in-sync, otherwise the type-cast
|
|
539
|
+
// could cause runtime issues!
|
|
540
|
+
return snap?.manifest.initialPermissions['endowment:keyring']
|
|
541
|
+
?.capabilities;
|
|
542
|
+
}, _SnapKeyring_getExistingAccount = function _SnapKeyring_getExistingAccount(account) {
|
|
543
|
+
const address = (0, account_1.normalizeAccountAddress)(account);
|
|
544
|
+
const existing = __classPrivateFieldGet(this, _SnapKeyring_registry, "f").get(account.id);
|
|
545
|
+
if (existing && (0, account_1.normalizeAccountAddress)(existing) === address) {
|
|
546
|
+
return existing;
|
|
547
|
+
}
|
|
548
|
+
return undefined;
|
|
405
549
|
};
|
|
406
550
|
SnapKeyring.type = `${v2_1.KeyringType.Snap}`;
|
|
407
551
|
//# 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,4CAIoB;AACpB,wDAA8D;AAC9D,wDAAiD;AAMjD,sCAA2C;AAE3C;;;;;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;AAkCH;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,OAAgB;IAC5C,OAAO,OAAO,CAAC,IAAI,KAAK,gBAAW,CAAC,IAAI,CAAC;AAC3C,CAAC;AAFD,sCAEC;AAED;;;;;;;;;;GAU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AAY,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,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AAI,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;AA3jBe,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 // 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 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"]}
|