@metamask-previews/eth-snap-keyring 22.4.0-5951828 → 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.
- package/CHANGELOG.md +15 -1
- package/dist/v2/SnapKeyring.cjs +0 -3
- package/dist/v2/SnapKeyring.cjs.map +1 -1
- package/dist/v2/SnapKeyring.d.cts.map +1 -1
- package/dist/v2/SnapKeyring.d.mts.map +1 -1
- package/dist/v2/SnapKeyring.mjs +0 -3
- package/dist/v2/SnapKeyring.mjs.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -7,11 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [23.0.1]
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- Fix deadlock in `SnapKeyring.createAccounts` (v2) ([#591](https://github.com/MetaMask/accounts/pull/591))
|
|
15
|
+
- We do not need to call `saveState` here, we expect this call to be wrapped in a `:withKeyringV2` transaction call.
|
|
16
|
+
|
|
17
|
+
## [23.0.0]
|
|
18
|
+
|
|
10
19
|
### Changed
|
|
11
20
|
|
|
12
21
|
- **BREAKING:** `SnapKeyring` (v2) no longer inherits `SnapKeyringV1` ([#584](https://github.com/MetaMask/accounts/pull/584))
|
|
13
22
|
- Use `.v1` getter to access a v1 instance instead.
|
|
14
23
|
- `.v1` will yield `undefined` if the Snap declares v2 `capabilities` in its `endowment:keyring`.
|
|
24
|
+
- Bump `@metamask/superstruct` from `^3.1.0` to `^3.3.0` ([#580](https://github.com/MetaMask/accounts/pull/580))
|
|
25
|
+
- Bump `@metamask/keyring-internal-snap-client` from `^10.0.4` to `^10.0.5` ([#587](https://github.com/MetaMask/accounts/pull/587))
|
|
26
|
+
- Bump `@metamask/keyring-snap-sdk` from `^9.1.0` to `^9.2.0` ([#587](https://github.com/MetaMask/accounts/pull/587))
|
|
15
27
|
|
|
16
28
|
## [22.4.0]
|
|
17
29
|
|
|
@@ -764,7 +776,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
764
776
|
|
|
765
777
|
- Initial release.
|
|
766
778
|
|
|
767
|
-
[Unreleased]: https://github.com/MetaMask/accounts/compare/@metamask/eth-snap-keyring@
|
|
779
|
+
[Unreleased]: https://github.com/MetaMask/accounts/compare/@metamask/eth-snap-keyring@23.0.1...HEAD
|
|
780
|
+
[23.0.1]: https://github.com/MetaMask/accounts/compare/@metamask/eth-snap-keyring@23.0.0...@metamask/eth-snap-keyring@23.0.1
|
|
781
|
+
[23.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-snap-keyring@22.4.0...@metamask/eth-snap-keyring@23.0.0
|
|
768
782
|
[22.4.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-snap-keyring@22.3.0...@metamask/eth-snap-keyring@22.4.0
|
|
769
783
|
[22.3.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-snap-keyring@22.2.0...@metamask/eth-snap-keyring@22.3.0
|
|
770
784
|
[22.2.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-snap-keyring@22.1.0...@metamask/eth-snap-keyring@22.2.0
|
package/dist/v2/SnapKeyring.cjs
CHANGED
|
@@ -242,9 +242,6 @@ class SnapKeyring {
|
|
|
242
242
|
for (const account of newAccounts) {
|
|
243
243
|
this.setAccount(account);
|
|
244
244
|
}
|
|
245
|
-
// NOTE: We assume this will never fail, thus, we don't need to rollback the
|
|
246
|
-
// keyring state if anything goes wrong here.
|
|
247
|
-
await __classPrivateFieldGet(this, _SnapKeyring_callbacks, "f").saveState();
|
|
248
245
|
}
|
|
249
246
|
return accounts;
|
|
250
247
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SnapKeyring.cjs","sourceRoot":"","sources":["../../src/v2/SnapKeyring.ts"],"names":[],"mappings":";;;;;;;;;;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AAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,CACtC,CAAC,QAAQ,CAAC,CAAC;AACd,CAAC;IA8ZC,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;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"]}
|
|
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,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,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;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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SnapKeyring.d.cts","sourceRoot":"","sources":["../../src/v2/SnapKeyring.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,8BAA8B;AAE5D,OAAO,KAAK,EACV,oBAAoB,EACpB,OAAO,EACP,mBAAmB,EACpB,iCAAiC;AAIlC,OAAO,KAAK,EAAE,SAAS,EAAE,gCAAgC;AACzD,OAAO,KAAK,EAAE,MAAM,EAAE,4BAA4B;AAClD,OAAO,KAAK,EAAE,KAAK,EAAE,8BAA8B;AAEnD,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAU5C,OAAO,KAAK,EAAE,oBAAoB,EAAE,oCAAgC;AACpE,OAAO,EAAE,aAAa,EAAE,6BAAyB;AACjD,OAAO,KAAK,EAAiB,sBAAsB,EAAE,6BAAyB;AAG9E;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,EAAE,mBAE/B,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eA0FjC;;;eAGG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAHH;;;eAGG;;;;;EAvFH,CAAC;AAEH;;;;;;;;;;GAUG;AACH,MAAM,MAAM,gBAAgB,GAAG,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAEpE;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG,sBAAsB,GAAG;IAC1D;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;CACzE,CAAC;AAEF,KAAK,kBAAkB,GAAG;IACxB,SAAS,EAAE,oBAAoB,CAAC;I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EAAE,cAAc,GAAG,IAAI;IAQzC;;;;;;;OAOG;IACH,aAAa,CAAC,EAAE,EAAE,SAAS,GAAG,OAAO;IASrC;;;;;OAKG;IACH,UAAU,CAAC,EAAE,EAAE,SAAS,GAAG,OAAO;IAIlC;;;;;OAKG;IACH,aAAa,CAAC,EAAE,EAAE,SAAS,GAAG,cAAc,GAAG,SAAS;IAIxD;;;;;;;;OAQG;IACH,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS;IAc5D;;;;;;;;OAQG;IACH,QAAQ,IAAI,cAAc,EAAE;IAI5B;;;;;;;;OAQG;IACG,SAAS,IAAI,OAAO,CAAC,gBAAgB,CAAC;IAY5C;;;;;;;;;;;OAWG;IACG,WAAW,CAAC,KAAK,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;CA0G9C"}
|
package/dist/v2/SnapKeyring.mjs
CHANGED
|
@@ -238,9 +238,6 @@ export class SnapKeyring {
|
|
|
238
238
|
for (const account of newAccounts) {
|
|
239
239
|
this.setAccount(account);
|
|
240
240
|
}
|
|
241
|
-
// NOTE: We assume this will never fail, thus, we don't need to rollback the
|
|
242
|
-
// keyring state if anything goes wrong here.
|
|
243
|
-
await __classPrivateFieldGet(this, _SnapKeyring_callbacks, "f").saveState();
|
|
244
241
|
}
|
|
245
242
|
return accounts;
|
|
246
243
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SnapKeyring.mjs","sourceRoot":"","sources":["../../src/v2/SnapKeyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,oBAAoB,EAAE,8BAA8B;AAM7D,OAAO,EAAE,WAAW,EAAE,iCAAiC;AACvD,OAAO,EAAE,yBAAyB,EAAE,kDAAkD;AACtF,OAAO,EAAE,sBAAsB,EAAE,8BAA8B;AAI/D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,8BAA8B;AAE9E,O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3D,uBAAA,IAAI,yBAAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,CACtC,CAAC,QAAQ,CAAC,CAAC;AACd,CAAC;IA8ZC,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,uBAAuB,CAAC,OAAO,CAAC,CAAC;IACjD,MAAM,QAAQ,GAAG,uBAAA,IAAI,6BAAU,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAChD,IAAI,QAAQ,IAAI,uBAAuB,CAAC,QAAQ,CAAC,KAAK,OAAO,EAAE,CAAC;QAC9D,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AA3jBe,gBAAI,GAAG,GAAG,WAAW,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"]}
|
|
1
|
+
{"version":3,"file":"SnapKeyring.mjs","sourceRoot":"","sources":["../../src/v2/SnapKeyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,oBAAoB,EAAE,8BAA8B;AAM7D,OAAO,EAAE,WAAW,EAAE,iCAAiC;AACvD,OAAO,EAAE,yBAAyB,EAAE,kDAAkD;AACtF,OAAO,EAAE,sBAAsB,EAAE,8BAA8B;AAI/D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,8BAA8B;AAE9E,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EACL,sBAAsB,EACtB,gBAAgB,EAChB,uBAAuB,EACvB,gBAAgB,EACjB,uBAAmB;AACpB,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,gCAAsB;AAE9D,OAAO,EAAE,aAAa,EAAE,6BAAyB;AAEjD,OAAO,EAAE,gBAAgB,EAAE,oBAAgB;AAE3C;;;;GAIG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAwB,MAAM,CAAC,MAAM,CAAC;IACnE,MAAM,EAAE,EAAE;CACX,CAAC,CAAC;AAEH;;;;;GAKG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAM,CAAC;IAC3C,MAAM,EAAE,MAAM,EAAE;IAChB,QAAQ,EAAE,MAAM,CACd,MAAM,EAAE,EACR,KAAK,CAAC,CAAC,oBAAoB,EAAE,sBAAsB,CAAC,CAAC,CACtD;CACF,CAAC,CAAC;AA6CH;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,OAAgB;IAC5C,OAAO,OAAO,CAAC,IAAI,KAAK,WAAW,CAAC,IAAI,CAAC;AAC3C,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,OAAO,WAAW;IAwCtB,YAAY,EACV,SAAS,EACT,S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AW,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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/eth-snap-keyring",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "23.0.1-1fa477f",
|
|
4
4
|
"description": "Snaps keyring bridge",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"keyring",
|
|
@@ -69,11 +69,11 @@
|
|
|
69
69
|
"dependencies": {
|
|
70
70
|
"@ethereumjs/tx": "^5.4.0",
|
|
71
71
|
"@metamask/eth-sig-util": "^8.2.0",
|
|
72
|
-
"@metamask/keyring-api": "23.
|
|
72
|
+
"@metamask/keyring-api": "23.5.0",
|
|
73
73
|
"@metamask/keyring-internal-api": "11.0.1",
|
|
74
|
-
"@metamask/keyring-internal-snap-client": "10.0.
|
|
74
|
+
"@metamask/keyring-internal-snap-client": "10.0.5",
|
|
75
75
|
"@metamask/keyring-sdk": "2.2.0",
|
|
76
|
-
"@metamask/keyring-snap-sdk": "9.
|
|
76
|
+
"@metamask/keyring-snap-sdk": "9.2.0",
|
|
77
77
|
"@metamask/keyring-utils": "3.3.1",
|
|
78
78
|
"@metamask/messenger": "^1.1.1",
|
|
79
79
|
"@metamask/snaps-controllers": "^19.0.1",
|
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
"@lavamoat/allow-scripts": "^3.2.1",
|
|
90
90
|
"@lavamoat/preinstall-always-fail": "^2.1.0",
|
|
91
91
|
"@metamask/auto-changelog": "^6.1.0",
|
|
92
|
-
"@metamask/keyring-api": "23.
|
|
92
|
+
"@metamask/keyring-api": "23.5.0",
|
|
93
93
|
"@ts-bridge/cli": "^0.6.3",
|
|
94
94
|
"@types/jest": "^29.5.12",
|
|
95
95
|
"@types/node": "^20.12.12",
|