@metamask-previews/eth-snap-keyring 19.0.0-fd40efd → 20.0.0-5c366be

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +32 -1
  2. package/dist/SnapKeyring.cjs +169 -826
  3. package/dist/SnapKeyring.cjs.map +1 -1
  4. package/dist/SnapKeyring.d.cts +21 -11
  5. package/dist/SnapKeyring.d.cts.map +1 -1
  6. package/dist/SnapKeyring.d.mts +21 -11
  7. package/dist/SnapKeyring.d.mts.map +1 -1
  8. package/dist/SnapKeyring.mjs +169 -826
  9. package/dist/SnapKeyring.mjs.map +1 -1
  10. package/dist/SnapKeyringMessenger.cjs.map +1 -1
  11. package/dist/SnapKeyringMessenger.d.cts +2 -2
  12. package/dist/SnapKeyringMessenger.d.cts.map +1 -1
  13. package/dist/SnapKeyringMessenger.d.mts +2 -2
  14. package/dist/SnapKeyringMessenger.d.mts.map +1 -1
  15. package/dist/SnapKeyringMessenger.mjs.map +1 -1
  16. package/dist/SnapKeyringV1.cjs +736 -0
  17. package/dist/SnapKeyringV1.cjs.map +1 -0
  18. package/dist/SnapKeyringV1.d.cts +222 -0
  19. package/dist/SnapKeyringV1.d.cts.map +1 -0
  20. package/dist/SnapKeyringV1.d.mts +222 -0
  21. package/dist/SnapKeyringV1.d.mts.map +1 -0
  22. package/dist/SnapKeyringV1.mjs +732 -0
  23. package/dist/SnapKeyringV1.mjs.map +1 -0
  24. package/dist/SnapKeyringV2.cjs +375 -0
  25. package/dist/SnapKeyringV2.cjs.map +1 -0
  26. package/dist/SnapKeyringV2.d.cts +275 -0
  27. package/dist/SnapKeyringV2.d.cts.map +1 -0
  28. package/dist/SnapKeyringV2.d.mts +275 -0
  29. package/dist/SnapKeyringV2.d.mts.map +1 -0
  30. package/dist/SnapKeyringV2.mjs +371 -0
  31. package/dist/SnapKeyringV2.mjs.map +1 -0
  32. package/dist/events.d.cts +4 -4
  33. package/dist/events.d.mts +4 -4
  34. package/dist/index.cjs +2 -0
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +2 -0
  37. package/dist/index.d.cts.map +1 -1
  38. package/dist/index.d.mts +2 -0
  39. package/dist/index.d.mts.map +1 -1
  40. package/dist/index.mjs +2 -0
  41. package/dist/index.mjs.map +1 -1
  42. package/dist/util.cjs +16 -0
  43. package/dist/util.cjs.map +1 -1
  44. package/dist/util.d.cts +11 -0
  45. package/dist/util.d.cts.map +1 -1
  46. package/dist/util.d.mts +11 -0
  47. package/dist/util.d.mts.map +1 -1
  48. package/dist/util.mjs +15 -0
  49. package/dist/util.mjs.map +1 -1
  50. package/package.json +11 -10
  51. package/dist/DeferredPromise.cjs +0 -30
  52. package/dist/DeferredPromise.cjs.map +0 -1
  53. package/dist/DeferredPromise.d.cts +0 -16
  54. package/dist/DeferredPromise.d.cts.map +0 -1
  55. package/dist/DeferredPromise.d.mts +0 -16
  56. package/dist/DeferredPromise.d.mts.map +0 -1
  57. package/dist/DeferredPromise.mjs +0 -26
  58. package/dist/DeferredPromise.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SnapKeyringV1.mjs","sourceRoot":"","sources":["../src/SnapKeyringV1.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,kBAAkB,EAAE,uBAAuB;AAEpD,OAAO,EAAE,oBAAoB,EAAE,+BAA+B;AAY9D,OAAO,EACL,cAAc,EACd,SAAS,EACT,YAAY,EACZ,cAAc,EACd,0BAA0B,EAC1B,2BAA2B,EAC3B,iCAAiC,EACjC,kCAAkC,EAClC,qCAAqC,EACtC,8BAA8B;AAC/B,OAAO,EAAE,6BAA6B,EAAE,uCAAuC;AAC/E,OAAO,EAAE,yBAAyB,EAAE,+CAA+C;AACnF,OAAO,EAAE,sBAAsB,EAAE,8BAA8B;AAC/D,OAAO,EAEL,gCAAgC,EAChC,wBAAwB,EACzB,mCAAmC;AAEpC,OAAO,EAAE,UAAU,EAA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;AAED;;;;;;GAMG;AACH,KAAK,6CAAsB,QAG1B;IACC,MAAM,EAAE,OAAO,GAAG,EAAE,EAAE,GAAG,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,QAAQ,CAAC;IACzD,MAAM,GAAG,GAAG,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;IACjE,IAAI,GAAG,EAAE,CAAC;QACR,uBAAA,IAAI,oEAAqB,MAAzB,IAAI,EAAsB,GAAG,CAAC,CAAC;IACjC,CAAC;IACD,MAAM,uBAAA,IAAI,gCAAW,CAAC,YAAY,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AACnD,CAAC,mFAQoB,GAAW;IAC9B,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;IAChC,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,wBAAwB,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IACxE,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CAAC,SAAS,IAAI,CAAC,MAAM,cAAc,CAAC,CAAC;IACtD,CAAC;IACD,MAAM,cAAc,GAClB,IAAI,CAAC,QAAQ,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,EAAE,cAAc;QACrE,EAAE,CAAC;IACL,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CACb,wBAAwB,MAAM,uCAAuC,IAAI,CAAC,MAAM,GAAG,CACpF,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type { TypedTransaction } from '@ethereumjs/tx';\nimport { TransactionFactory } from '@ethereumjs/tx';\nimport type { TypedDataV1, TypedMessage } from '@metamask/eth-sig-util';\nimport { SignTypedDataVersion } from '@metamask/eth-sig-util';\nimport type {\n KeyringAccount,\n BtcMethod,\n CaipChainId,\n ResolvedAccountAddress,\n KeyringExecutionContext,\n EthBaseTransaction,\n EthBaseUserOperation,\n EthUserOperation,\n EthUserOperationPatch,\n} from '@metamask/keyring-api';\nimport {\n AnyAccountType,\n EthMethod,\n KeyringEvent,\n EthBytesStruct,\n EthBaseUserOperationStruct,\n EthUserOperationPatchStruct,\n AccountBalancesUpdatedEventStruct,\n AccountAssetListUpdatedEventStruct,\n AccountTransactionsUpdatedEventStruct,\n} from '@metamask/keyring-api';\nimport { toKeyringRequestWithoutOrigin } from '@metamask/keyring-internal-api';\nimport { KeyringInternalSnapClient } from '@metamask/keyring-internal-snap-client';\nimport { KeyringAccountRegistry } from '@metamask/keyring-sdk';\nimport {\n type GetSelectedAccountsResponse,\n GetSelectedAccountsRequestStruct,\n SnapManageAccountsMethod,\n} from '@metamask/keyring-snap-sdk';\nimport type { AccountId, JsonRpcRequest } from '@metamask/keyring-utils';\nimport { strictMask } from '@metamask/keyring-utils';\nimport type { ExtractEventPayload } from '@metamask/messenger';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { assert, mask, object, string } from '@metamask/superstruct';\nimport type { Hex, Json, DeferredPromise } from '@metamask/utils';\nimport {\n bigIntToHex,\n hasProperty,\n KnownCaipNamespace,\n toCaipChainId,\n createDeferredPromise,\n} from '@metamask/utils';\nimport { v4 as uuid } from 'uuid';\n\nimport { transformAccount } from './account';\nimport {\n AccountCreatedEventStruct,\n AccountUpdatedEventStruct,\n AccountDeletedEventStruct,\n RequestApprovedEventStruct,\n RequestRejectedEventStruct,\n} from './events';\nimport { projectLogger as log } from './logger';\nimport {\n getInternalOptionsOf,\n type SnapKeyringInternalOptions,\n} from './options';\nimport { PLATFORM_VERSION_FOR_KEYRING_REQUEST_WITH_ORIGIN } from './platform-versions';\nimport type {\n SnapKeyringEvents,\n SnapKeyringMessenger,\n} from './SnapKeyringMessenger';\nimport type { SnapMessage } from './types';\nimport { SnapMessageStruct } from './types';\nimport {\n equalsIgnoreCase,\n normalizeAccountAddress,\n sanitizeUrl,\n throwError,\n toJson,\n} from './util';\n\n// TODO: to be removed when this is added to the keyring-api\nexport type AccountMethod = EthMethod | BtcMethod;\n\n/**\n * Callback type to filter unknown account ID from a mapping account ID mapping.\n */\ntype FilterAccountIdFunction = <Entry>(\n accountMapping: Record<AccountId, Entry>,\n) => Record<AccountId, Entry>;\n\n/**\n * Callbacks injected by the parent `SnapKeyring` to delegate global concerns.\n *\n * These cover operations that span multiple snaps or require parent-level\n * coordination (account approval UI, persistence, global uniqueness checks).\n */\nexport type SnapKeyringV1Callbacks = {\n /**\n * Called when a new account is being created (v1 event-driven flow).\n * Handles the user-approval dialog and account registration in the UI.\n * The `snapId` is baked in at construction time.\n */\n addAccount: (\n address: string,\n handleUserInput: (accepted: boolean) => Promise<void>,\n onceSaved: Promise<AccountId>,\n accountNameSuggestion?: string,\n internalOptions?: SnapKeyringInternalOptions,\n ) => Promise<void>;\n\n /**\n * Called when an account is being deleted.\n * Handles the user-approval dialog and account removal in the UI.\n * The `snapId` is baked in at construction time.\n */\n removeAccount: (\n address: string,\n handleUserInput: (accepted: boolean) => Promise<void>,\n ) => Promise<void>;\n\n /**\n * Persist keyring state to disk via KeyringController.\n */\n saveState: () => Promise<void>;\n\n /**\n * Redirect the user to a URL after an async snap request.\n */\n redirectUser: (url: string, message: string) => Promise<void>;\n\n /**\n * Check global uniqueness (address + ID). Throws if the account cannot be used.\n * Must remain in the parent because it checks cross-snap invariants.\n */\n assertAccountCanBeUsed: (account: KeyringAccount) => Promise<void>;\n\n /**\n * Called synchronously whenever a new account is added to the registry.\n * Optional — consumers that don't need cross-instance indexing can omit this.\n */\n onRegister?: (accountId: AccountId) => void;\n\n /**\n * Called synchronously whenever an account is removed from the registry.\n * Optional — consumers that don't need cross-instance indexing can omit this.\n */\n onUnregister?: (accountId: AccountId) => void;\n};\n\n/**\n * Options for creating a `SnapKeyringV1` instance.\n */\nexport type SnapKeyringV1Options = {\n snapId: SnapId;\n messenger: SnapKeyringMessenger;\n callbacks: SnapKeyringV1Callbacks;\n /**\n * Whether to allow the creation and update of generic accounts.\n * Defaults to `false`.\n */\n isAnyAccountTypeAllowed?: boolean;\n};\n\n/**\n * Per-snap coordinator for the v1 (event-driven) keyring flow.\n *\n * Each instance is scoped to exactly one `SnapId`. It handles all Snap\n * keyring events (account lifecycle, request approval, asset updates) and\n * owns the per-snap request / internal-options state.\n *\n * Designed to be subclassed: `SnapKeyringV2` extends this class and adds the\n * `KeyringV2` interface on top, sharing the same registry and client.\n */\nexport class SnapKeyringV1 {\n /** The snap ID this instance is scoped to. */\n readonly snapId: SnapId;\n\n /** Account registry — shared with subclass (e.g. SnapKeyringV2). */\n protected readonly registry: KeyringAccountRegistry;\n\n /** Messenger for snap controller calls and event publishing. */\n protected readonly messenger: SnapKeyringMessenger;\n\n /** Snap client for keyring RPC calls. */\n protected readonly client: KeyringInternalSnapClient;\n\n /** Injected callbacks for parent-level coordination. */\n readonly #callbacks: SnapKeyringV1Callbacks;\n\n /** Whether to allow the creation and update of generic accounts. */\n readonly #isAnyAccountTypeAllowed: boolean;\n\n /**\n * Pending async request promises, keyed by request ID.\n * Plain Map is sufficient here since this instance is already snap-scoped.\n */\n readonly #requests: Map<string, DeferredPromise<any>>;\n\n /**\n * Correlation ID → internal options, used to thread options from\n * `createAccount` through to the `AccountCreated` event handler.\n */\n readonly #options: Map<string, SnapKeyringInternalOptions>;\n\n /**\n * The currently selected account IDs for this snap.\n */\n #selectedAccounts: AccountId[];\n\n constructor({\n snapId,\n messenger,\n callbacks,\n isAnyAccountTypeAllowed = false,\n }: SnapKeyringV1Options) {\n this.snapId = snapId;\n this.registry = new KeyringAccountRegistry();\n this.messenger = messenger;\n this.#callbacks = callbacks;\n this.#isAnyAccountTypeAllowed = isAnyAccountTypeAllowed;\n this.client = new KeyringInternalSnapClient({ messenger, snapId });\n this.#requests = new Map();\n this.#options = new Map();\n this.#selectedAccounts = [];\n }\n\n // ──────────────────────────────────────────────\n // Public API\n // ──────────────────────────────────────────────\n\n /**\n * Create a single account using the v1 event-driven flow.\n *\n * Handles the reserved 'metamask' field, correlation IDs, and internal\n * options registration. The account is ultimately added to the registry\n * via the `AccountCreated` event handler, not the return value.\n *\n * @param options - Account creation options.\n * @param internalOptions - Internal Snap keyring options.\n * @returns The account object returned by the snap.\n */\n async createAccount(\n options: Record<string, Json>,\n internalOptions?: SnapKeyringInternalOptions,\n ): Promise<KeyringAccount> {\n return this.#createSnapAccount(options, internalOptions);\n }\n\n /**\n * Handle an incoming message from the Snap.\n *\n * Routes the message to the appropriate private handler based on the method.\n *\n * @param message - The message sent by the Snap.\n * @returns The execution result.\n */\n async handleKeyringSnapMessage(message: SnapMessage): Promise<Json> {\n assert(message, SnapMessageStruct);\n switch (message.method) {\n case `${KeyringEvent.AccountCreated}`: {\n return this.#handleAccountCreated(message);\n }\n\n case `${KeyringEvent.AccountUpdated}`: {\n return this.#handleAccountUpdated(message);\n }\n\n case `${KeyringEvent.AccountDeleted}`: {\n return this.#handleAccountDeleted(message);\n }\n\n case `${KeyringEvent.RequestApproved}`: {\n return this.#handleRequestApproved(message);\n }\n\n case `${KeyringEvent.RequestRejected}`: {\n return this.#handleRequestRejected(message);\n }\n\n case `${KeyringEvent.AccountBalancesUpdated}`: {\n return this.#handleAccountBalancesUpdated(message);\n }\n\n case `${KeyringEvent.AccountAssetListUpdated}`: {\n return this.#handleAccountAssetListUpdated(message);\n }\n\n case `${KeyringEvent.AccountTransactionsUpdated}`: {\n return this.#handleAccountTransactionsUpdated(message);\n }\n\n case `${SnapManageAccountsMethod.GetSelectedAccounts}`: {\n return this.#handleGetSelectedAccounts(message);\n }\n\n default:\n throw new Error(`Method not supported: ${message.method}`);\n }\n }\n\n /**\n * Submit a snap request for the given account.\n *\n * Manages the request promise lifecycle (creation, resolution, cleanup) and\n * handles both synchronous and asynchronous (redirect) responses.\n *\n * @param options - The request options.\n * @param options.origin - The sender origin.\n * @param options.account - The account to submit the request for.\n * @param options.method - The method to call.\n * @param options.params - The method parameters.\n * @param options.scope - The CAIP-2 chain ID.\n * @param options.noPending - Whether the response is allowed to be pending.\n * @returns A promise that resolves to the keyring response.\n */\n async submitSnapRequest<Response extends Json>({\n origin,\n account,\n method,\n params,\n scope,\n noPending,\n }: {\n origin: string;\n account: KeyringAccount;\n method: AccountMethod;\n params?: Json[] | Record<string, Json> | undefined;\n scope: string;\n noPending: boolean;\n }): Promise<Response> {\n if (!(account.methods as AccountMethod[]).includes(method)) {\n throw new Error(\n `Method '${method}' not supported for account ${account.address}`,\n );\n }\n\n // Will both catch `undefined` and \"empty\" origins.\n if (!origin?.trim()) {\n throw new Error('An `origin` is required');\n }\n\n const requestId = uuid();\n\n // Create the promise before calling the Snap to prevent a race condition\n // where the Snap responds before we have a chance to create it.\n const requestPromise = this.#createRequestPromise<Response>(requestId);\n\n try {\n const useOrigin = this.messenger.call(\n 'SnapController:isMinimumPlatformVersion',\n this.snapId,\n PLATFORM_VERSION_FOR_KEYRING_REQUEST_WITH_ORIGIN,\n );\n\n const request = {\n id: requestId,\n origin,\n scope,\n account: account.id,\n request: {\n method,\n ...(params !== undefined && { params }),\n },\n };\n\n log('Submit Snap request: ', request);\n\n let response;\n if (useOrigin) {\n response = await this.client.submitRequest(request);\n } else {\n response = await this.client.submitRequestWithoutOrigin(\n toKeyringRequestWithoutOrigin(request),\n );\n }\n\n if (noPending && response.pending) {\n throw new Error(\n `Request '${requestId}' to Snap '${this.snapId}' is pending and noPending is true.`,\n );\n }\n\n if (!response.pending) {\n this.#requests.delete(requestId);\n return response.result as Response;\n }\n\n if (response.redirect?.message || response.redirect?.url) {\n await this.#handleAsyncRedirect(response.redirect);\n }\n\n return requestPromise.promise;\n } catch (error) {\n log('Snap Request failed: ', { requestId });\n this.#requests.delete(requestId);\n throw error;\n }\n }\n\n /**\n * Update the selected accounts for this snap.\n *\n * @param accountIds - The account IDs to set as selected.\n */\n async setSelectedAccounts(accountIds: AccountId[]): Promise<void> {\n this.#selectedAccounts = accountIds;\n try {\n await this.client.setSelectedAccounts(accountIds);\n } catch (error: any) {\n console.error(\n `Failed to set selected accounts for ${this.snapId} snap: '${error.message}'`,\n );\n }\n }\n\n /**\n * Resolve the account address associated with a signing request.\n *\n * Delegates directly to the snap-scoped client, which already has the\n * snap ID baked in from construction time.\n *\n * @param scope - CAIP-2 chain ID.\n * @param request - Signing request object.\n * @returns The resolved address if found, `null` otherwise.\n */\n async resolveAccountAddress(\n scope: CaipChainId,\n request: JsonRpcRequest,\n ): Promise<ResolvedAccountAddress | null> {\n return this.client.resolveAccountAddress(scope, request);\n }\n\n /**\n * Sign a transaction for the given account.\n *\n * @param account - The account to sign the transaction for.\n * @param transaction - The transaction to sign.\n * @param _opts - Transaction options (unused).\n * @returns A promise that resolves to the signed transaction.\n */\n async signTransaction(\n account: KeyringAccount,\n transaction: TypedTransaction,\n /* istanbul ignore next */\n _opts = {},\n ): Promise<Json | TypedTransaction> {\n const chainId = transaction.common.chainId();\n const tx = toJson({\n ...transaction.toJSON(),\n from: normalizeAccountAddress(account),\n type: `0x${transaction.type.toString(16)}`,\n chainId: bigIntToHex(chainId),\n });\n\n const signedTx = await this.submitSnapRequest({\n origin: 'metamask',\n account,\n method: EthMethod.SignTransaction,\n params: [tx],\n scope: toCaipChainId(KnownCaipNamespace.Eip155, `${chainId}`),\n noPending: false,\n });\n\n // ! It's *** CRITICAL *** that we mask the signature here, otherwise the\n // ! Snap could overwrite the transaction.\n const signature = mask(\n signedTx,\n object({\n r: string(),\n s: string(),\n v: string(),\n }),\n );\n\n return TransactionFactory.fromTxData({\n ...(tx as Record<string, Json>),\n r: signature.r as Hex,\n s: signature.s as Hex,\n v: signature.v as Hex,\n });\n }\n\n /**\n * Sign a typed data message for the given account.\n *\n * @param account - The account to sign the typed data for.\n * @param data - The typed data to sign.\n * @param opts - Signing options.\n * @param opts.version - The typed data version to use.\n * @returns A promise that resolves to the signature.\n */\n async signTypedData(\n account: KeyringAccount,\n data: Record<string, unknown>[] | TypedDataV1 | TypedMessage<any>,\n opts: { version: SignTypedDataVersion },\n ): Promise<string> {\n const methods = {\n [SignTypedDataVersion.V1]: EthMethod.SignTypedDataV1,\n [SignTypedDataVersion.V3]: EthMethod.SignTypedDataV3,\n [SignTypedDataVersion.V4]: EthMethod.SignTypedDataV4,\n };\n\n // Use 'V1' by default to match other keyring implementations. V1 will be\n // used if the version is not specified or not supported.\n const method = methods[opts.version] || EthMethod.SignTypedDataV1;\n\n // Extract chain ID as if it was a typed message (as defined by EIP-712), if\n // input is not a typed message, then chain ID will be undefined!\n const chainId = (data as TypedMessage<any>).domain?.chainId;\n\n const address = normalizeAccountAddress(account);\n return strictMask(\n await this.submitSnapRequest({\n origin: 'metamask',\n account,\n method,\n params: toJson<Json[]>([address, data]),\n scope:\n chainId === undefined\n ? ''\n : toCaipChainId(KnownCaipNamespace.Eip155, `${chainId}`),\n noPending: false,\n }),\n EthBytesStruct,\n );\n }\n\n /**\n * Sign a message (eth_sign) for the given account.\n *\n * @param account - The account to sign the message for.\n * @param hash - The data to sign.\n * @returns A promise that resolves to the signature.\n */\n async signMessage(account: KeyringAccount, hash: any): Promise<string> {\n const address = normalizeAccountAddress(account);\n return strictMask(\n await this.submitSnapRequest({\n origin: 'metamask',\n account,\n method: EthMethod.Sign,\n params: toJson<Json[]>([address, hash]),\n scope: '',\n noPending: false,\n }),\n EthBytesStruct,\n );\n }\n\n /**\n * Sign a personal message for the given account.\n *\n * Note: KeyringController says this should return a Buffer but it actually\n * expects a string.\n *\n * @param account - The account to sign the message for.\n * @param data - The data to sign.\n * @returns A promise that resolves to the signature.\n */\n async signPersonalMessage(\n account: KeyringAccount,\n data: any,\n ): Promise<string> {\n const address = normalizeAccountAddress(account);\n return strictMask(\n await this.submitSnapRequest({\n origin: 'metamask',\n account,\n method: EthMethod.PersonalSign,\n params: toJson<Json[]>([data, address]),\n scope: '',\n noPending: false,\n }),\n EthBytesStruct,\n );\n }\n\n /**\n * Convert a base transaction to a base UserOperation.\n *\n * @param account - The account to prepare the user operation for.\n * @param transactions - Base transactions to include in the UserOperation.\n * @param context - Keyring execution context.\n * @returns A pseudo-UserOperation that can be used to construct a real one.\n */\n async prepareUserOperation(\n account: KeyringAccount,\n transactions: EthBaseTransaction[],\n context: KeyringExecutionContext,\n ): Promise<EthBaseUserOperation> {\n return strictMask(\n await this.submitSnapRequest({\n origin: 'metamask',\n account,\n method: EthMethod.PrepareUserOperation,\n params: toJson<Json[]>(transactions),\n noPending: true,\n scope: toCaipChainId(KnownCaipNamespace.Eip155, context.chainId),\n }),\n EthBaseUserOperationStruct,\n );\n }\n\n /**\n * Patches properties of a UserOperation. Currently, only the\n * `paymasterAndData` can be patched.\n *\n * @param account - The account to patch the user operation for.\n * @param userOp - UserOperation to patch.\n * @param context - Keyring execution context.\n * @returns A patch to apply to the UserOperation.\n */\n async patchUserOperation(\n account: KeyringAccount,\n userOp: EthUserOperation,\n context: KeyringExecutionContext,\n ): Promise<EthUserOperationPatch> {\n return strictMask(\n await this.submitSnapRequest({\n origin: 'metamask',\n account,\n method: EthMethod.PatchUserOperation,\n params: toJson<Json[]>([userOp]),\n noPending: true,\n scope: toCaipChainId(KnownCaipNamespace.Eip155, context.chainId),\n }),\n EthUserOperationPatchStruct,\n );\n }\n\n /**\n * Signs a UserOperation.\n *\n * @param account - The account to sign the user operation for.\n * @param userOp - UserOperation to sign.\n * @param context - Keyring execution context.\n * @returns A promise that resolves to the signature.\n */\n async signUserOperation(\n account: KeyringAccount,\n userOp: EthUserOperation,\n context: KeyringExecutionContext,\n ): Promise<string> {\n return strictMask(\n await this.submitSnapRequest({\n origin: 'metamask',\n account,\n method: EthMethod.SignUserOperation,\n params: toJson<Json[]>([userOp]),\n noPending: false,\n scope: toCaipChainId(KnownCaipNamespace.Eip155, context.chainId),\n }),\n EthBytesStruct,\n );\n }\n\n // ──────────────────────────────────────────────\n // Private handlers\n // ──────────────────────────────────────────────\n\n /**\n * Handle an Account Created event from the Snap.\n *\n * @param message - Event message.\n * @returns `null`.\n */\n async #handleAccountCreated(message: SnapMessage): Promise<null> {\n assert(message, AccountCreatedEventStruct);\n const {\n metamask,\n account: newAccountFromEvent,\n accountNameSuggestion,\n displayAccountNameSuggestion,\n displayConfirmation,\n } = message.params;\n\n // READ THIS CAREFULLY:\n // ------------------------------------------------------------------------\n // The account creation flow is now asynchronous. We expect the Snap to\n // first create the account data and then fire the \"AccountCreated\" event.\n\n // Potentially migrate the account.\n const account = transformAccount(newAccountFromEvent);\n const address = normalizeAccountAddress(account);\n\n if (this.#getExistingAccount(account)) {\n // If the account already exists, we skip it.\n return null;\n }\n\n // Make sure this new account is valid.\n await this.#callbacks.assertAccountCanBeUsed(account);\n\n // A deferred promise that will be resolved once the Snap keyring has saved\n // its internal state.\n // This part of the flow is run asynchronously, so we have no other way of\n // letting the MetaMask client that this \"save\" has been run.\n // NOTE: Another way of fixing that could be to rely on events through the\n // messenger maybe?\n const onceSaved = createDeferredPromise<AccountId>();\n\n // Add the account to the keyring, but wait for the MetaMask client to\n // approve the account creation first.\n await this.#callbacks.addAccount(\n address,\n // This callback is passed to the MetaMask client, it will be called whenever\n // the end user will accept or not the account creation.\n async (accepted: boolean) => {\n if (accepted) {\n // We consider the account to be created on the Snap keyring only if\n // the user accepted it. Meaning that the Snap MIGHT HAVE created the\n // account on its own state, but the Snap keyring MIGHT NOT HAVE it yet.\n //\n // e.g The account creation dialog crashed on MetaMask, this callback\n // will never be called, but the Snap still has the account.\n this.registry.set(account);\n this.#callbacks.onRegister?.(account.id);\n\n // This is the \"true async part\". We do not `await` for this call, mainly\n // because this callback will persist the account on the client side\n // (through the `AccountsController`).\n //\n // Since this will happen after the Snap account creation and Snap\n // event, if anything goes wrong, we will delete the account by\n // calling `deleteAccount` on the Snap.\n // eslint-disable-next-line no-void\n void this.#callbacks\n .saveState()\n .then(() => {\n // This allows the MetaMask client to be \"notified\" when then\n // Snap keyring has truly persisted its state. From there, we should\n // be able to use the account (e.g. to display account creation\n // confirmation dialogs).\n onceSaved.resolve(account.id);\n })\n .catch(\n /* istanbul ignore next */\n async (error: unknown) => {\n // FIXME: There's a potential race condition here, if the Snap did\n // not persist the account yet (this should mostly be for older Snaps).\n this.registry.delete(account.id);\n this.#callbacks.onUnregister?.(account.id);\n await this.client\n .deleteAccount(account.id)\n /* istanbul ignore next */\n .catch(() => {\n // Swallow — best-effort cleanup.\n });\n\n // This allows the MetaMask client to be \"notified\" that something went\n // wrong with the Snap keyring. (e.g. useful to display account creation\n // error dialogs).\n onceSaved.reject(error);\n },\n );\n }\n },\n onceSaved.promise,\n accountNameSuggestion,\n getInternalOptionsOf([\n // 1. We use the internal options from the Snap keyring.\n this.#getInternalOptions(metamask?.correlationId) ?? {},\n // 2. We use the ones coming from the Snap.\n {\n displayConfirmation,\n displayAccountNameSuggestion,\n },\n ]),\n );\n\n return null;\n }\n\n /**\n * Handle an Account Updated event from the Snap.\n *\n * @param message - Event message.\n * @returns `null`.\n */\n async #handleAccountUpdated(message: SnapMessage): Promise<null> {\n assert(message, AccountUpdatedEventStruct);\n const { account: newAccountFromEvent } = message.params;\n const oldAccount =\n this.registry.get(newAccountFromEvent.id) ??\n throwError(`Account '${newAccountFromEvent.id}' not found`);\n\n // Potentially migrate the account.\n const newAccount = transformAccount(newAccountFromEvent);\n\n // The `AnyAccountType.Account` generic account type is allowed only during\n // development, so we check whether it's allowed before continuing.\n //\n // An account cannot be updated if the `isAnyAccountTypeAllowed` flag is\n // set to `false` and the new or old account is a generic account.\n const isGenericAccountInvolved =\n newAccount.type === AnyAccountType.Account ||\n oldAccount.type === AnyAccountType.Account;\n\n if (!this.#isAnyAccountTypeAllowed && isGenericAccountInvolved) {\n throw new Error(`Cannot update generic account '${newAccount.id}'`);\n }\n\n // The address of the account cannot be changed. In the future, we will\n // support changing the address of an account since it will be required to\n // support UTXO-based chains.\n if (!equalsIgnoreCase(oldAccount.address, newAccount.address)) {\n throw new Error(`Cannot change address of account '${newAccount.id}'`);\n }\n\n this.registry.set(newAccount);\n await this.#callbacks.saveState();\n return null;\n }\n\n /**\n * Handle an Account Deleted event from the Snap.\n *\n * @param message - Event message.\n * @returns `null`.\n */\n async #handleAccountDeleted(message: SnapMessage): Promise<null> {\n assert(message, AccountDeletedEventStruct);\n const { id } = message.params;\n const account = this.registry.get(id);\n\n // We can ignore the case where the account was already removed from the\n // keyring, making the deletion idempotent.\n //\n // This happens when the keyring calls the Snap to delete an account, and\n // the Snap calls the keyring back with an `AccountDeleted` event.\n if (account === undefined) {\n return null;\n }\n\n await this.#callbacks.removeAccount(\n normalizeAccountAddress(account),\n async (accepted) => {\n if (accepted) {\n await this.#callbacks.saveState();\n }\n },\n );\n return null;\n }\n\n /**\n * Handle a Request Approved event from the Snap.\n *\n * @param message - Event message.\n * @returns `null`.\n */\n async #handleRequestApproved(message: SnapMessage): Promise<null> {\n assert(message, RequestApprovedEventStruct);\n const { id, result } = message.params;\n const promise =\n this.#requests.get(id) ?? throwError(`Request '${id}' not found`);\n\n this.#requests.delete(id);\n promise.resolve(result);\n return null;\n }\n\n /**\n * Handle a Request Rejected event from the Snap.\n *\n * @param message - Event message.\n * @returns `null`.\n */\n async #handleRequestRejected(message: SnapMessage): Promise<null> {\n assert(message, RequestRejectedEventStruct);\n const { id } = message.params;\n const promise =\n this.#requests.get(id) ?? throwError(`Request '${id}' not found`);\n\n this.#requests.delete(id);\n promise.reject(new Error(`Request rejected by user or snap.`));\n return null;\n }\n\n /**\n * Handle a Get Selected Accounts method call from the Snap.\n *\n * @param message - Method call message.\n * @returns The selected accounts.\n */\n async #handleGetSelectedAccounts(\n message: SnapMessage,\n ): Promise<GetSelectedAccountsResponse> {\n assert(message, GetSelectedAccountsRequestStruct);\n return this.#selectedAccounts;\n }\n\n /**\n * Handle an Account Balances Updated event from the Snap.\n *\n * @param message - Event message.\n * @returns `null`.\n */\n async #handleAccountBalancesUpdated(message: SnapMessage): Promise<null> {\n assert(message, AccountBalancesUpdatedEventStruct);\n const event = message.params;\n return this.#rePublishAccountEvent(\n 'SnapKeyring:accountBalancesUpdated',\n (filter) => {\n event.balances = filter(event.balances);\n return [event];\n },\n );\n }\n\n /**\n * Handle an Account Asset List Updated event from the Snap.\n *\n * @param message - Event message.\n * @returns `null`.\n */\n async #handleAccountAssetListUpdated(message: SnapMessage): Promise<null> {\n assert(message, AccountAssetListUpdatedEventStruct);\n const event = message.params;\n return this.#rePublishAccountEvent(\n 'SnapKeyring:accountAssetListUpdated',\n (filter) => {\n event.assets = filter(event.assets);\n return [event];\n },\n );\n }\n\n /**\n * Handle an Account Transactions Updated event from the Snap.\n *\n * @param message - Event message.\n * @returns `null`.\n */\n async #handleAccountTransactionsUpdated(message: SnapMessage): Promise<null> {\n assert(message, AccountTransactionsUpdatedEventStruct);\n const event = message.params;\n return this.#rePublishAccountEvent(\n 'SnapKeyring:accountTransactionsUpdated',\n (filter) => {\n event.transactions = filter(event.transactions);\n return [event];\n },\n );\n }\n\n // ──────────────────────────────────────────────\n // Private helpers\n // ──────────────────────────────────────────────\n\n /**\n * Re-publish an account event after filtering out accounts that don't\n * belong to this snap.\n *\n * Uses the registry as the source of truth: only accounts present in\n * this snap's registry are forwarded. This prevents a snap from emitting\n * updates for accounts it doesn't own.\n *\n * @param event - The event type to re-publish.\n * @param filteredEventCallback - Callback that receives the filter function\n * and returns the event payload to publish.\n * @template EventType - A Snap keyring event type.\n * @returns `null`.\n */\n async #rePublishAccountEvent<EventType extends SnapKeyringEvents['type']>(\n event: EventType,\n filteredEventCallback: (\n filter: FilterAccountIdFunction,\n ) => ExtractEventPayload<SnapKeyringEvents, EventType>,\n ): Promise<null> {\n const filter: FilterAccountIdFunction = <Entry>(\n accountMapping: Record<AccountId, Entry>,\n ): Record<AccountId, Entry> => {\n return Object.entries(accountMapping).reduce<Record<AccountId, Entry>>(\n (filtered, [accountId, entry]) => {\n if (this.registry.has(accountId)) {\n filtered[accountId] = entry;\n } else {\n console.warn(\n `SnapKeyring - ${event} - Found an unknown account ID \"${accountId}\" for Snap ID \"${this.snapId}\". Skipping.`,\n );\n }\n return filtered;\n },\n {},\n );\n };\n\n this.messenger.publish(event, ...filteredEventCallback(filter));\n return null;\n }\n\n /**\n * Core logic for the v1 `createAccount` flow.\n *\n * Handles the reserved 'metamask' field, correlation IDs, and internal\n * options registration. The account is ultimately added to the registry\n * via the `AccountCreated` event handler, not the return value.\n *\n * @param options - Account creation options.\n * @param internalOptions - Internal Snap keyring options.\n * @returns The account object returned by the snap.\n */\n async #createSnapAccount(\n options: Record<string, Json>,\n internalOptions?: SnapKeyringInternalOptions,\n ): Promise<KeyringAccount> {\n const reserved = 'metamask';\n if (hasProperty(options, reserved)) {\n throw new Error(\n `The '${reserved}' property is reserved for internal use`,\n );\n }\n\n if (!internalOptions) {\n return await this.client.createAccount(options);\n }\n\n const correlationId = uuid();\n this.#options.set(correlationId, internalOptions);\n\n return await this.client.createAccount({\n ...options,\n metamask: {\n correlationId,\n },\n });\n }\n\n /**\n * Retrieve and consume internal options for a given correlation ID.\n *\n * NOTE: The options are deleted from the map on retrieval (pop semantics).\n *\n * @param correlationId - Correlation ID associated with the internal options.\n * @returns Internal options if found, `undefined` otherwise.\n */\n #getInternalOptions(\n correlationId: string | undefined,\n ): SnapKeyringInternalOptions | undefined {\n if (!correlationId) {\n return undefined;\n }\n\n const options = this.#options.get(correlationId);\n if (options) {\n this.#options.delete(correlationId);\n return options;\n }\n\n console.warn(\n `SnapKeyring - Received unmapped correlation ID: \"${correlationId}\"`,\n );\n return undefined;\n }\n\n /**\n * Idempotency check: account already exists in this snap with same address.\n *\n * @param account - The account to check.\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 /**\n * Create a deferred promise for a request and store it.\n *\n * @param requestId - The unique request identifier.\n * @returns The deferred promise.\n */\n #createRequestPromise<Response>(\n requestId: string,\n ): DeferredPromise<Response> {\n const promise = createDeferredPromise<Response>();\n this.#requests.set(requestId, promise);\n return promise;\n }\n\n /**\n * Handle an async redirect response from the Snap.\n *\n * @param redirect - The redirect information.\n * @param redirect.message - The message to show the user.\n * @param redirect.url - The URL to redirect to.\n */\n async #handleAsyncRedirect(redirect: {\n message?: string;\n url?: string;\n }): Promise<void> {\n const { message = '', url: redirectUrl = '' } = redirect;\n const url = redirectUrl ? sanitizeUrl(redirectUrl) : redirectUrl;\n if (url) {\n this.#validateRedirectUrl(url);\n }\n await this.#callbacks.redirectUser(url, message);\n }\n\n /**\n * Validates that a redirect URL is in the Snap's allowed origins.\n *\n * @param url - The URL to validate.\n * @throws An error if the URL's origin is not in the Snap's allowed origins.\n */\n #validateRedirectUrl(url: string): void {\n const { origin } = new URL(url);\n const snap = this.messenger.call('SnapController:getSnap', this.snapId);\n if (!snap) {\n throw new Error(`Snap '${this.snapId}' not found.`);\n }\n const allowedOrigins =\n snap.manifest.initialPermissions['endowment:keyring']?.allowedOrigins ??\n [];\n if (!allowedOrigins.includes(origin)) {\n throw new Error(\n `Redirect URL domain '${origin}' is not an allowed origin by snap '${this.snapId}'`,\n );\n }\n }\n}\n"]}
@@ -0,0 +1,375 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _SnapKeyringV2_instances, _SnapKeyringV2_callbacks, _SnapKeyringV2_lock, _SnapKeyringV2_getExistingAccount;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.SnapKeyringV2 = exports.SnapKeyringV2StateStruct = void 0;
16
+ const keyring_api_1 = require("@metamask/keyring-api");
17
+ const superstruct_1 = require("@metamask/superstruct");
18
+ const async_mutex_1 = require("async-mutex");
19
+ const account_1 = require("./account.cjs");
20
+ const migrations_1 = require("./migrations/index.cjs");
21
+ const SnapKeyringV1_1 = require("./SnapKeyringV1.cjs");
22
+ const util_1 = require("./util.cjs");
23
+ /**
24
+ * Superstruct schema for {@link SnapKeyringV2State}.
25
+ *
26
+ * Accepts both v1 accounts (missing `scopes`) and v2 accounts so that
27
+ * persisted state can be validated before migration.
28
+ */
29
+ exports.SnapKeyringV2StateStruct = (0, superstruct_1.object)({
30
+ snapId: (0, superstruct_1.string)(),
31
+ accounts: (0, superstruct_1.record)((0, superstruct_1.string)(), (0, superstruct_1.union)([keyring_api_1.KeyringAccountStruct, account_1.KeyringAccountV1Struct])),
32
+ });
33
+ /**
34
+ * Per-snap keyring wrapper that implements `KeyringV2`.
35
+ *
36
+ * Extends `SnapKeyringV1` — the v1 event-driven flow (account lifecycle,
37
+ * request handling, asset events) is inherited. This class adds the
38
+ * `KeyringV2` batch interface (`createAccounts`, `deleteAccount`, etc.) and
39
+ * owns the `capabilities` property.
40
+ *
41
+ * The `KeyringAccountRegistry`, snap client, and messenger are all inherited
42
+ * from `SnapKeyringV1` so there is no duplicated state.
43
+ */
44
+ class SnapKeyringV2 extends SnapKeyringV1_1.SnapKeyringV1 {
45
+ constructor(options) {
46
+ super(options);
47
+ _SnapKeyringV2_instances.add(this);
48
+ /**
49
+ * V2-typed view of the callbacks. Stored separately from the V1 private
50
+ * field so that V2-specific callbacks are accessible without casting.
51
+ * Both fields hold the same object reference.
52
+ */
53
+ _SnapKeyringV2_callbacks.set(this, void 0);
54
+ /**
55
+ * Mutex that serializes `createAccounts` calls on this snap instance.
56
+ * Owned here so that each `SnapKeyringV2` is fully self-contained.
57
+ */
58
+ _SnapKeyringV2_lock.set(this, void 0);
59
+ // ──────────────────────────────────────────────
60
+ // KeyringV2 properties
61
+ // ──────────────────────────────────────────────
62
+ this.type = `${keyring_api_1.KeyringType.Snap}`;
63
+ __classPrivateFieldSet(this, _SnapKeyringV2_callbacks, options.callbacks, "f");
64
+ __classPrivateFieldSet(this, _SnapKeyringV2_lock, new async_mutex_1.Mutex(), "f");
65
+ // Default capabilities — parent updates this when snap metadata is available.
66
+ // We cast here because KeyringCapabilities requires a non-empty scopes array,
67
+ // but we don't have the snap metadata at construction time (e.g. during deserialization).
68
+ this.capabilities = { scopes: [] };
69
+ }
70
+ // ──────────────────────────────────────────────
71
+ // KeyringV2 methods
72
+ // ──────────────────────────────────────────────
73
+ /**
74
+ * Returns all accounts managed by this keyring.
75
+ *
76
+ * @returns A promise that resolves to an array of all accounts.
77
+ */
78
+ async getAccounts() {
79
+ return this.accounts();
80
+ }
81
+ /**
82
+ * Returns the account with the specified ID.
83
+ *
84
+ * @param accountId - ID of the account to retrieve.
85
+ * @returns A promise that resolves to the account.
86
+ */
87
+ async getAccount(accountId) {
88
+ const account = this.lookupAccount(accountId);
89
+ if (!account) {
90
+ throw new Error(`Account '${accountId}' not found in snap '${this.snapId}'`);
91
+ }
92
+ return account;
93
+ }
94
+ /**
95
+ * Creates one or more new accounts according to the provided options.
96
+ *
97
+ * Deterministic account creation MUST be idempotent, meaning that for
98
+ * deterministic algorithms, like BIP-44, calling this method with the same
99
+ * options should always return the same accounts, even if the accounts
100
+ * already exist in the keyring.
101
+ *
102
+ * NOTE: If some accounts are not allowed (non-unique address, unsupported
103
+ * generic account), this method will skip their creation and ask the Snap
104
+ * to remove them from its state.
105
+ *
106
+ * @param options - Options describing how to create the account(s).
107
+ * @returns A promise that resolves to an array of the created account objects.
108
+ */
109
+ async createAccounts(options) {
110
+ return __classPrivateFieldGet(this, _SnapKeyringV2_lock, "f").runExclusive(async () => {
111
+ // Keep track of address/account ID part of this batch, to avoid having duplicates.
112
+ const batchAddresses = new Set();
113
+ const batchIds = new Set();
114
+ const accounts = [];
115
+ const newAccounts = [];
116
+ const snapAccounts = await this.client.createAccounts(options);
117
+ try {
118
+ for (const snapAccount of snapAccounts) {
119
+ let account = (0, account_1.transformAccount)(snapAccount);
120
+ const address = (0, util_1.normalizeAccountAddress)(account);
121
+ // Check for idempotency.
122
+ const existingAccount = __classPrivateFieldGet(this, _SnapKeyringV2_instances, "m", _SnapKeyringV2_getExistingAccount).call(this, account);
123
+ if (existingAccount) {
124
+ // NOTE: We re-use the account from the internal state to avoid having the Snap
125
+ // mutating the account object without updating the map.
126
+ account = existingAccount;
127
+ }
128
+ else {
129
+ await __classPrivateFieldGet(this, _SnapKeyringV2_callbacks, "f").assertAccountCanBeUsed(account);
130
+ // Also check for transient accounts that are not yet part of the keyring
131
+ // state.
132
+ if (batchAddresses.has(address) || batchIds.has(account.id)) {
133
+ throw new Error(`Account '${account.id}' is already part of this batch (same address or account ID)`);
134
+ }
135
+ batchAddresses.add(address);
136
+ batchIds.add(account.id);
137
+ // NOTE: This method does not rely on the `AccountCreated` event to add
138
+ // accounts to the keyring, so we have to add them to the state manually.
139
+ newAccounts.push(account);
140
+ }
141
+ // New AND existing accounts are returned to the caller no matter what.
142
+ accounts.push(account);
143
+ }
144
+ // We update the keyring state only if needed.
145
+ if (newAccounts.length > 0) {
146
+ for (const account of newAccounts) {
147
+ this.setAccount(account);
148
+ }
149
+ // NOTE: We assume this will never fail, thus, we don't need to rollback the
150
+ // keyring state if anything goes wrong here.
151
+ await __classPrivateFieldGet(this, _SnapKeyringV2_callbacks, "f").saveState();
152
+ }
153
+ return accounts;
154
+ }
155
+ catch (error) {
156
+ // Rollback Snap state.
157
+ for (const snapAccount of snapAccounts) {
158
+ // Make sure to only delete accounts that were not part of the keyring state.
159
+ if (!__classPrivateFieldGet(this, _SnapKeyringV2_instances, "m", _SnapKeyringV2_getExistingAccount).call(this, snapAccount)) {
160
+ try {
161
+ await this.client.deleteAccount(snapAccount.id);
162
+ }
163
+ catch (rollbackError) {
164
+ // Best-effort rollback; log snap-side failures for observability.
165
+ console.error(`Account '${snapAccount.id}' may not have been removed from snap '${this.snapId}' during createAccounts rollback:`, rollbackError);
166
+ }
167
+ }
168
+ }
169
+ throw error;
170
+ }
171
+ });
172
+ }
173
+ /**
174
+ * Deletes the account with the specified ID.
175
+ *
176
+ * Removes the account from the local registry (firing `onUnregister` so the
177
+ * parent can update its index), then asks the snap to delete it.
178
+ *
179
+ * @param accountId - ID of the account to delete.
180
+ */
181
+ async deleteAccount(accountId) {
182
+ // Always remove the account from the registry, even if the Snap is going to
183
+ // fail to delete it. removeAccount fires onUnregister to clean #accountIndex.
184
+ this.removeAccount(accountId);
185
+ try {
186
+ await this.client.deleteAccount(accountId);
187
+ }
188
+ catch (error) {
189
+ // If the Snap failed to delete the account, log the error and continue
190
+ // with the account deletion, otherwise the account will be stuck in the
191
+ // keyring.
192
+ console.error(`Account '${accountId}' may not have been removed from snap '${this.snapId}':`, error);
193
+ }
194
+ }
195
+ /**
196
+ * Submits a request to the keyring.
197
+ *
198
+ * Validates that the account belongs to this wrapper, then delegates
199
+ * to the inherited `submitSnapRequest` for the full request lifecycle
200
+ * (sync / async / redirect).
201
+ *
202
+ * @param request - The keyring request to submit.
203
+ * @param request.id - The request ID (unused — a fresh ID is generated internally).
204
+ * @param request.origin - The sender origin.
205
+ * @param request.scope - The CAIP-2 chain ID.
206
+ * @param request.account - The account ID.
207
+ * @param request.request - The inner JSON-RPC request.
208
+ * @param request.request.method - The method to call.
209
+ * @param request.request.params - The method parameters.
210
+ * @returns A promise that resolves to the response.
211
+ */
212
+ async submitRequest(request) {
213
+ const account = this.lookupAccount(request.account);
214
+ if (!account) {
215
+ throw new Error(`Account '${request.account}' not found in snap '${this.snapId}'`);
216
+ }
217
+ return this.submitSnapRequest({
218
+ origin: request.origin,
219
+ account,
220
+ method: request.request.method,
221
+ params: request.request.params,
222
+ scope: request.scope,
223
+ noPending: false,
224
+ });
225
+ }
226
+ // ──────────────────────────────────────────────
227
+ // Internal API (used by parent SnapKeyring for event handling, routing, etc.)
228
+ // ──────────────────────────────────────────────
229
+ /**
230
+ * Upsert an account into the registry.
231
+ *
232
+ * Fires `onRegister` only when the account is new (not already present).
233
+ * Safe to call for updates -- the parent index is already populated in that
234
+ * case and the no-op path avoids a redundant write.
235
+ *
236
+ * @param account - The account to add or update.
237
+ */
238
+ setAccount(account) {
239
+ const isNew = !this.registry.has(account.id);
240
+ this.registry.set(account);
241
+ if (isNew) {
242
+ __classPrivateFieldGet(this, _SnapKeyringV2_callbacks, "f").onRegister?.(account.id);
243
+ }
244
+ }
245
+ /**
246
+ * Remove an account from the registry.
247
+ *
248
+ * Fires `onUnregister` so the parent can drop the account from its index.
249
+ *
250
+ * @param id - The account ID to remove.
251
+ * @returns `true` if the account was removed, `false` if it was not found.
252
+ */
253
+ removeAccount(id) {
254
+ if (!this.registry.has(id)) {
255
+ return false;
256
+ }
257
+ this.registry.delete(id);
258
+ __classPrivateFieldGet(this, _SnapKeyringV2_callbacks, "f").onUnregister?.(id);
259
+ return true;
260
+ }
261
+ /**
262
+ * Check whether an account exists in this keyring.
263
+ *
264
+ * @param id - The account ID to check.
265
+ * @returns `true` if the account exists.
266
+ */
267
+ hasAccount(id) {
268
+ return this.registry.has(id);
269
+ }
270
+ /**
271
+ * Get an account by its ID.
272
+ *
273
+ * @param id - The account ID to look up.
274
+ * @returns The account, or `undefined` if not found.
275
+ */
276
+ lookupAccount(id) {
277
+ return this.registry.get(id);
278
+ }
279
+ /**
280
+ * Get an account by address (case-insensitive).
281
+ *
282
+ * Performs an O(1) exact lookup first; falls back to a linear scan to
283
+ * handle addresses stored with different casing.
284
+ *
285
+ * @param address - The address to look up.
286
+ * @returns The account, or `undefined` if not found.
287
+ */
288
+ lookupByAddress(address) {
289
+ const id = this.registry.getAccountId(address);
290
+ if (id !== undefined) {
291
+ return this.registry.get(id);
292
+ }
293
+ // The fallback only runs when the exact-match branch above misses,
294
+ // which in practice only happens for EVM addresses with casing
295
+ // differences (checksummed vs lowercase). Non-EVM addresses are
296
+ // case-sensitive and always resolve on the exact branch.
297
+ return this.registry
298
+ .values()
299
+ .find((account) => (0, util_1.equalsIgnoreCase)(account.address, address));
300
+ }
301
+ /**
302
+ * Get all accounts in this keyring (synchronous).
303
+ *
304
+ * This exists alongside the async `getAccounts()` (from `KeyringV2`) because
305
+ * `SnapKeyring` needs synchronous access for iteration in `serialize`,
306
+ * `listAccounts`, `hasSnapId`, etc. without awaiting.
307
+ *
308
+ * @returns An array of all accounts.
309
+ */
310
+ accounts() {
311
+ return this.registry.values();
312
+ }
313
+ /**
314
+ * Serialize this keyring's state.
315
+ *
316
+ * The returned object uses the internal per-snap format; the parent
317
+ * `SnapKeyring` reconstructs the flat external format in its own
318
+ * `serialize()`.
319
+ *
320
+ * @returns The serialized state.
321
+ */
322
+ async serialize() {
323
+ const accounts = {};
324
+ for (const account of this.registry.values()) {
325
+ accounts[account.id] = account;
326
+ }
327
+ const state = {
328
+ snapId: this.snapId,
329
+ accounts,
330
+ };
331
+ return state;
332
+ }
333
+ /**
334
+ * Restore this keyring from a serialized state.
335
+ *
336
+ * Validates the payload (accepting both v1 and v2 accounts), migrates any
337
+ * v1 accounts to v2, then replaces the registry. If validation fails, the
338
+ * existing registry is left untouched.
339
+ *
340
+ * @param state - The state to deserialize.
341
+ * @returns A promise that resolves when deserialization is complete.
342
+ */
343
+ async deserialize(state) {
344
+ // Validate the raw payload — accepts both v1 and v2 account shapes.
345
+ (0, superstruct_1.assert)(state, exports.SnapKeyringV2StateStruct);
346
+ // Migrate v1 accounts to v2.
347
+ const migratedAccounts = {};
348
+ for (const [id, rawAccount] of Object.entries(state.accounts)) {
349
+ if ((0, migrations_1.isAccountV1)(rawAccount)) {
350
+ console.info(`SnapKeyring - Found a KeyringAccountV1, migrating to V2: ${rawAccount.id}`);
351
+ migratedAccounts[id] = (0, migrations_1.migrateAccountV1)(rawAccount);
352
+ }
353
+ else {
354
+ migratedAccounts[id] = rawAccount;
355
+ }
356
+ }
357
+ // Apply the migrated state to the registry.
358
+ for (const id of [...this.registry.keys()]) {
359
+ this.removeAccount(id);
360
+ }
361
+ for (const account of Object.values(migratedAccounts)) {
362
+ this.setAccount(account);
363
+ }
364
+ }
365
+ }
366
+ exports.SnapKeyringV2 = SnapKeyringV2;
367
+ _SnapKeyringV2_callbacks = new WeakMap(), _SnapKeyringV2_lock = new WeakMap(), _SnapKeyringV2_instances = new WeakSet(), _SnapKeyringV2_getExistingAccount = function _SnapKeyringV2_getExistingAccount(account) {
368
+ const address = (0, util_1.normalizeAccountAddress)(account);
369
+ const existing = this.lookupAccount(account.id);
370
+ if (existing && (0, util_1.normalizeAccountAddress)(existing) === address) {
371
+ return existing;
372
+ }
373
+ return undefined;
374
+ };
375
+ //# sourceMappingURL=SnapKeyringV2.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SnapKeyringV2.cjs","sourceRoot":"","sources":["../src/SnapKeyringV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAMA,uDAA0E;AAG1E,uDAA8E;AAE9E,6CAAoC;AAEpC,2CAAqE;AACrE,uDAA6D;AAC7D,uDAAgD;AAMhD,qCAAmE;AAEnE;;;;;GAKG;AACU,QAAA,wBAAwB,GAAG,IAAA,oBAAM,EAAC;IAC7C,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;AAyBH;;;;;;;;;;GAUG;AACH,MAAa,aAAc,SAAQ,6BAAa;IA0B9C,YAAY,OAA6B;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;;QA1BjB;;;;WAIG;Q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QAC5D,KAAK,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC9D,IAAI,IAAA,wBAAW,EAAC,UAAU,CAAC,EAAE,CAAC;gBAC5B,OAAO,CAAC,IAAI,CACV,4DAA4D,UAAU,CAAC,EAAE,EAAE,CAC5E,CAAC;gBACF,gBAAgB,CAAC,EAAE,CAAC,GAAG,IAAA,6BAAgB,EAAC,UAAU,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACN,gBAAgB,CAAC,EAAE,CAAC,GAAG,UAA4B,CAAC;YACtD,CAAC;QACH,CAAC;QAED,4CAA4C;QAC5C,KAAK,MAAM,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;YAC3C,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC;QACzB,CAAC;QAED,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,EAAE,CAAC;YACtD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QAC3B,CAAC;IACH,CAAC;CAoBF;AA/YD,sCA+YC;wMARqB,OAAuB;IACzC,MAAM,OAAO,GAAG,IAAA,8BAAuB,EAAC,OAAO,CAAC,CAAC;IACjD,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IAChD,IAAI,QAAQ,IAAI,IAAA,8BAAuB,EAAC,QAAQ,CAAC,KAAK,OAAO,EAAE,CAAC;QAC9D,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type {\n KeyringAccount,\n CreateAccountOptions,\n KeyringV2,\n KeyringCapabilities,\n} from '@metamask/keyring-api';\nimport { KeyringAccountStruct, KeyringType } from '@metamask/keyring-api';\nimport type { AccountId } from '@metamask/keyring-utils';\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 { KeyringAccountV1Struct, transformAccount } from './account';\nimport { isAccountV1, migrateAccountV1 } from './migrations';\nimport { SnapKeyringV1 } from './SnapKeyringV1';\nimport type {\n AccountMethod,\n SnapKeyringV1Callbacks,\n SnapKeyringV1Options,\n} from './SnapKeyringV1';\nimport { equalsIgnoreCase, normalizeAccountAddress } from './util';\n\n/**\n * Superstruct schema for {@link SnapKeyringV2State}.\n *\n * Accepts both v1 accounts (missing `scopes`) and v2 accounts so that\n * persisted state can be validated before migration.\n */\nexport const SnapKeyringV2StateStruct = object({\n snapId: string(),\n accounts: record(\n string(),\n union([KeyringAccountStruct, KeyringAccountV1Struct]),\n ),\n});\n\n/**\n * Serialized state of a single SnapKeyringV2 instance.\n *\n * Note: this is an internal format only used between SnapKeyringV2 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 SnapKeyringV2StateStruct}: `snapId` is `string`\n * (not the branded `SnapId`) so the shape stays JSON-compatible without\n * unsafe casts.\n */\nexport type SnapKeyringV2State = Infer<typeof SnapKeyringV2StateStruct>;\n\n/**\n * Callbacks injected by the parent `SnapKeyring` for global coordination.\n */\nexport type SnapKeyringV2Callbacks = SnapKeyringV1Callbacks;\n\n/**\n * Options for creating a `SnapKeyringV2` instance.\n */\ntype SnapKeyringV2Options = SnapKeyringV1Options;\n\n/**\n * Per-snap keyring wrapper that implements `KeyringV2`.\n *\n * Extends `SnapKeyringV1` — the v1 event-driven flow (account lifecycle,\n * request handling, asset events) is inherited. This class adds the\n * `KeyringV2` batch interface (`createAccounts`, `deleteAccount`, etc.) and\n * owns the `capabilities` property.\n *\n * The `KeyringAccountRegistry`, snap client, and messenger are all inherited\n * from `SnapKeyringV1` so there is no duplicated state.\n */\nexport class SnapKeyringV2 extends SnapKeyringV1 implements KeyringV2 {\n /**\n * V2-typed view of the callbacks. Stored separately from the V1 private\n * field so that V2-specific callbacks are accessible without casting.\n * Both fields hold the same object reference.\n */\n readonly #callbacks: SnapKeyringV2Callbacks;\n\n /**\n * Mutex that serializes `createAccounts` calls on this snap instance.\n * Owned here so that each `SnapKeyringV2` is fully self-contained.\n */\n readonly #lock: Mutex;\n\n // ──────────────────────────────────────────────\n // KeyringV2 properties\n // ──────────────────────────────────────────────\n\n readonly type = `${KeyringType.Snap}` as const;\n\n /**\n * Capabilities are snap-specific. Initialized empty and can be updated\n * by the parent when snap metadata becomes available.\n */\n capabilities: KeyringCapabilities;\n\n constructor(options: SnapKeyringV2Options) {\n super(options);\n this.#callbacks = options.callbacks;\n this.#lock = new Mutex();\n\n // Default capabilities — parent updates this when snap metadata is available.\n // We cast here because KeyringCapabilities requires a non-empty scopes array,\n // but we don't have the snap metadata at construction time (e.g. during deserialization).\n this.capabilities = { scopes: [] } as unknown as KeyringCapabilities;\n }\n\n // ──────────────────────────────────────────────\n // KeyringV2 methods\n // ──────────────────────────────────────────────\n\n /**\n * Returns all accounts managed by this keyring.\n *\n * @returns A promise that resolves to an array of all accounts.\n */\n async getAccounts(): Promise<KeyringAccount[]> {\n return this.accounts();\n }\n\n /**\n * Returns the account with the specified ID.\n *\n * @param accountId - ID of the account to retrieve.\n * @returns A promise that resolves to the account.\n */\n async getAccount(accountId: AccountId): Promise<KeyringAccount> {\n const account = this.lookupAccount(accountId);\n if (!account) {\n throw new Error(\n `Account '${accountId}' not found in snap '${this.snapId}'`,\n );\n }\n return account;\n }\n\n /**\n * Creates one or more new accounts according to the provided options.\n *\n * Deterministic account creation MUST be idempotent, meaning that for\n * deterministic algorithms, like BIP-44, calling this method with the same\n * options should always return the same accounts, even if the accounts\n * already exist in the keyring.\n *\n * NOTE: If some accounts are not allowed (non-unique address, unsupported\n * generic account), this method will skip their creation and ask the Snap\n * to remove them from its state.\n *\n * @param options - Options describing how to create the account(s).\n * @returns A promise that resolves to an array of the created account objects.\n */\n async createAccounts(\n options: CreateAccountOptions,\n ): Promise<KeyringAccount[]> {\n return this.#lock.runExclusive(async () => {\n // Keep track of address/account ID part of this batch, to avoid having duplicates.\n const batchAddresses = new Set<string>();\n const batchIds = new Set<string>();\n\n const accounts: KeyringAccount[] = [];\n const newAccounts: KeyringAccount[] = [];\n const snapAccounts = await this.client.createAccounts(options);\n\n try {\n for (const snapAccount of snapAccounts) {\n let account = transformAccount(snapAccount);\n const address = normalizeAccountAddress(account);\n\n // Check for idempotency.\n const existingAccount = this.#getExistingAccount(account);\n if (existingAccount) {\n // NOTE: We re-use the account from the internal state to avoid having the Snap\n // mutating the account object without updating the map.\n account = existingAccount;\n } else {\n await this.#callbacks.assertAccountCanBeUsed(account);\n\n // Also check for transient accounts that are not yet part of the keyring\n // state.\n if (batchAddresses.has(address) || batchIds.has(account.id)) {\n throw new Error(\n `Account '${account.id}' is already part of this batch (same address or account ID)`,\n );\n }\n batchAddresses.add(address);\n batchIds.add(account.id);\n\n // NOTE: This method does not rely on the `AccountCreated` event to add\n // accounts to the keyring, so we have to add them to the state manually.\n newAccounts.push(account);\n }\n\n // New AND existing accounts are returned to the caller no matter what.\n accounts.push(account);\n }\n\n // We update the keyring state only if needed.\n if (newAccounts.length > 0) {\n for (const account of newAccounts) {\n this.setAccount(account);\n }\n\n // NOTE: We assume this will never fail, thus, we don't need to rollback the\n // keyring state if anything goes wrong here.\n await this.#callbacks.saveState();\n }\n\n return accounts;\n } catch (error) {\n // Rollback Snap state.\n for (const snapAccount of snapAccounts) {\n // Make sure to only delete accounts that were not part of the keyring state.\n if (!this.#getExistingAccount(snapAccount)) {\n try {\n await this.client.deleteAccount(snapAccount.id);\n } catch (rollbackError) {\n // Best-effort rollback; log snap-side failures for observability.\n console.error(\n `Account '${snapAccount.id}' may not have been removed from snap '${this.snapId}' during createAccounts rollback:`,\n rollbackError,\n );\n }\n }\n }\n\n throw error;\n }\n });\n }\n\n /**\n * Deletes the account with the specified ID.\n *\n * Removes the account from the local registry (firing `onUnregister` so the\n * parent can update its index), then asks the snap to delete it.\n *\n * @param accountId - ID of the account to delete.\n */\n async deleteAccount(accountId: AccountId): Promise<void> {\n // Always remove the account from the registry, even if the Snap is going to\n // fail to delete it. removeAccount fires onUnregister to clean #accountIndex.\n this.removeAccount(accountId);\n\n try {\n await this.client.deleteAccount(accountId);\n } catch (error) {\n // If the Snap failed to delete the account, log the error and continue\n // with the account deletion, otherwise the account will be stuck in the\n // keyring.\n console.error(\n `Account '${accountId}' may not have been removed from snap '${this.snapId}':`,\n error,\n );\n }\n }\n\n /**\n * Submits a request to the keyring.\n *\n * Validates that the account belongs to this wrapper, then delegates\n * to the inherited `submitSnapRequest` for the full request lifecycle\n * (sync / async / redirect).\n *\n * @param request - The keyring request to submit.\n * @param request.id - The request ID (unused — a fresh ID is generated internally).\n * @param request.origin - The sender origin.\n * @param request.scope - The CAIP-2 chain ID.\n * @param request.account - The account ID.\n * @param request.request - The inner JSON-RPC request.\n * @param request.request.method - The method to call.\n * @param request.request.params - The method parameters.\n * @returns A promise that resolves to the response.\n */\n async submitRequest(request: {\n id: string;\n origin: string;\n scope: string;\n account: AccountId;\n request: {\n method: string;\n params?: Json[] | Record<string, Json>;\n };\n }): Promise<Json> {\n const account = this.lookupAccount(request.account);\n if (!account) {\n throw new Error(\n `Account '${request.account}' not found in snap '${this.snapId}'`,\n );\n }\n return this.submitSnapRequest({\n origin: request.origin,\n account,\n method: request.request.method as AccountMethod,\n params: request.request.params,\n scope: request.scope,\n noPending: false,\n });\n }\n\n // ──────────────────────────────────────────────\n // Internal API (used by parent SnapKeyring for event handling, routing, etc.)\n // ──────────────────────────────────────────────\n\n /**\n * Upsert an account into the registry.\n *\n * Fires `onRegister` only when the account is new (not already present).\n * Safe to call for updates -- the parent index is already populated in that\n * case and the no-op path avoids a redundant write.\n *\n * @param account - The account to add or update.\n */\n setAccount(account: KeyringAccount): void {\n const isNew = !this.registry.has(account.id);\n this.registry.set(account);\n if (isNew) {\n this.#callbacks.onRegister?.(account.id);\n }\n }\n\n /**\n * Remove an account from the registry.\n *\n * Fires `onUnregister` so the parent can drop the account from its index.\n *\n * @param id - The account ID to remove.\n * @returns `true` if the account was removed, `false` if it was not found.\n */\n removeAccount(id: AccountId): boolean {\n if (!this.registry.has(id)) {\n return false;\n }\n this.registry.delete(id);\n this.#callbacks.onUnregister?.(id);\n return true;\n }\n\n /**\n * Check whether an account exists in this keyring.\n *\n * @param id - The account ID to check.\n * @returns `true` if the account exists.\n */\n hasAccount(id: AccountId): boolean {\n return this.registry.has(id);\n }\n\n /**\n * Get an account by its ID.\n *\n * @param id - The account ID to look up.\n * @returns The account, or `undefined` if not found.\n */\n lookupAccount(id: AccountId): KeyringAccount | undefined {\n return this.registry.get(id);\n }\n\n /**\n * Get an account by address (case-insensitive).\n *\n * Performs an O(1) exact lookup first; falls back to a linear scan to\n * handle addresses stored with different casing.\n *\n * @param address - The address to look up.\n * @returns The account, or `undefined` if not found.\n */\n lookupByAddress(address: string): KeyringAccount | undefined {\n const id = this.registry.getAccountId(address);\n if (id !== undefined) {\n return this.registry.get(id);\n }\n // The fallback only runs when the exact-match branch above misses,\n // which in practice only happens for EVM addresses with casing\n // differences (checksummed vs lowercase). Non-EVM addresses are\n // case-sensitive and always resolve on the exact branch.\n return this.registry\n .values()\n .find((account) => equalsIgnoreCase(account.address, address));\n }\n\n /**\n * Get all accounts in this keyring (synchronous).\n *\n * This exists alongside the async `getAccounts()` (from `KeyringV2`) 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<SnapKeyringV2State> {\n const accounts: SnapKeyringV2State['accounts'] = {};\n for (const account of this.registry.values()) {\n accounts[account.id] = account;\n }\n const state: SnapKeyringV2State = {\n snapId: this.snapId,\n accounts,\n };\n return state;\n }\n\n /**\n * Restore this keyring from a serialized state.\n *\n * Validates the payload (accepting both v1 and v2 accounts), migrates any\n * v1 accounts to v2, then replaces the registry. If validation fails, the\n * existing registry is left untouched.\n *\n * @param state - The state to deserialize.\n * @returns A promise that resolves when deserialization is complete.\n */\n async deserialize(state: Json): Promise<void> {\n // Validate the raw payload — accepts both v1 and v2 account shapes.\n assert(state, SnapKeyringV2StateStruct);\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 * Idempotency check: account exists in this wrapper with same address.\n *\n * @param account - The account to check.\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.lookupAccount(account.id);\n if (existing && normalizeAccountAddress(existing) === address) {\n return existing;\n }\n return undefined;\n }\n}\n"]}