@metamask-previews/eth-snap-keyring 22.3.0-e51c895 → 22.4.0-5951828

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"SnapKeyring.mjs","sourceRoot":"","sources":["../src/SnapKeyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,OAAO,EAAE,oBAAoB,EAAE,+BAA+B;AAY9D,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,8BAA8B;AAMrE,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EAAE,uBAAuB,EAAE,sBAAkB;AAGpD,OAAO,EAAE,iBAAiB,EAAE,mCAA+B;AAG3D,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,mBAAe;AAC5C,OAAO,EAAE,WAAW,IAAI,aAAa,EAAE,6BAAyB;AAEhE,MAAM,CAAC,MAAM,iBAAiB,GAAG,cAAc,CAAC;AAwChD;;GAEG;AACH,MAAM,OAAO,WAAW;IAiEtB;;;;;;;;OAQG;IACH,YAAY,EACV,SAAS,EACT,SAAS,EACT,uBAAuB,GAAG,KAAK,GAKhC;;QA7ED,0DAA0D;QAC1D,SAAI,GAA6B,iBAAiB,CAAC;QAEnD,UAAK,GAAG,IAAI,CAAC;QAEb;;WAEG;QACM,yCAAiC;QAE1C;;;;WAIG;QACM,4CAA0C;QAEnD;;;;;;WAMG;QACM,4CAAsC;QAE/C;;WAEG;QACM,yCAAiC;QAE1C;;;;WAIG;QACM,uDAAkC;QAE3C;;;;;;;;;WASG;QACM,oCAAa;QAEtB;;;;;;;WAOG;QACM,sDAA+B;QAoBtC,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC;QAC7B,uBAAA,IAAI,0BAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,6BAAiB,IAAI,GAAG,EAAE,MAAA,CAAC;QAC/B,uBAAA,IAAI,6BAAiB,IAAI,GAAG,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AAC;YACb,OAAO,EAAE;gBACP,IAAI,EAAE,IAAI,CAAC,IAAI;aAChB;YACD,GAAG,CAAC,IAAI,KAAK,SAAS,IAAI,EAAE,IAAI,EAAE,CAAC;SACpC;KACF,CAAC;AACJ,CAAC;AAjvBM,gBAAI,GAAW,iBAAiB,AAA5B,CAA6B","sourcesContent":["import type { TypedTransaction } from '@ethereumjs/tx';\nimport type { TypedDataV1, TypedMessage } from '@metamask/eth-sig-util';\nimport { SignTypedDataVersion } from '@metamask/eth-sig-util';\nimport type {\n KeyringAccount,\n KeyringExecutionContext,\n EthBaseTransaction,\n EthBaseUserOperation,\n EthUserOperation,\n EthUserOperationPatch,\n ResolvedAccountAddress,\n CaipChainId,\n CreateAccountOptions,\n} from '@metamask/keyring-api';\nimport { AnyAccountType, KeyringEvent } from '@metamask/keyring-api';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { AccountId, JsonRpcRequest } from '@metamask/keyring-utils';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type { Snap } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport { normalizeAccountAddress } from './account';\nimport type { SnapKeyringInternalOptions } from './options';\nimport type { SnapKeyringMessenger } from './SnapKeyringMessenger';\nimport { SNAP_KEYRING_NAME } from './SnapKeyringMessenger';\nimport type { AccountMethod } from './SnapKeyringV1';\nimport type { SnapMessage } from './types';\nimport { throwError, unique } from './util';\nimport { SnapKeyring as SnapKeyringV2 } from './v2/SnapKeyring';\n\nexport const SNAP_KEYRING_TYPE = 'Snap Keyring';\n\n/**\n * Snap keyring state.\n *\n * This state is persisted by the keyring controller and passed to the Snap\n * keyring when it's created.\n */\nexport type KeyringState = {\n accounts: Record<string, { account: KeyringAccount; snapId: SnapId }>;\n};\n\n/**\n * Snap keyring callbacks.\n *\n * These callbacks are used to interact with other components.\n */\nexport type SnapKeyringCallbacks = {\n saveState: () => Promise<void>;\n\n addressExists(address: string): Promise<boolean>;\n\n addAccount(\n address: string,\n snapId: SnapId,\n handleUserInput: (accepted: boolean) => Promise<void>,\n onceSaved: Promise<AccountId>,\n accountNameSuggestion?: string,\n internalOptions?: SnapKeyringInternalOptions,\n ): Promise<void>;\n\n removeAccount(\n address: string,\n snapId: SnapId,\n handleUserInput: (accepted: boolean) => Promise<void>,\n ): Promise<void>;\n\n redirectUser(snapId: SnapId, url: string, message: string): Promise<void>;\n};\n\n/**\n * Keyring bridge implementation to support Snaps.\n */\nexport class SnapKeyring {\n static type: string = SNAP_KEYRING_TYPE;\n\n type: string;\n\n // Name and state are required for modular initialisation.\n name: typeof SNAP_KEYRING_NAME = SNAP_KEYRING_NAME;\n\n state = null;\n\n /**\n * Messenger to dispatch requests to the Snaps controller.\n */\n readonly #messenger: SnapKeyringMessenger;\n\n /**\n * Per-snap keyring instances. Each `SnapKeyringV2` (which extends\n * `SnapKeyringV1`) owns a single `KeyringAccountRegistry` and handles\n * both the event-driven v1 flow and the `KeyringV2` batch interface.\n */\n readonly #snapKeyrings: Map<SnapId, SnapKeyringV2>;\n\n /**\n * Reverse index from account ID to the owning Snap ID.\n *\n * Populated and kept in sync via the `onRegister` / `onUnregister`\n * callbacks injected into each entry. Enables O(1) routing for\n * any \"which snap owns this account?\" query.\n */\n readonly #accountIndex: Map<AccountId, SnapId>;\n\n /**\n * Callbacks used to interact with other components.\n */\n readonly #callbacks: SnapKeyringCallbacks;\n\n /**\n * Whether to allow the creation and update of generic accounts.\n *\n * Account deletion is not affected by this flag and is always allowed.\n */\n readonly #isAnyAccountTypeAllowed: boolean;\n\n /**\n * Global mutex that serializes `createAccounts` calls across all snaps.\n *\n * `assertAccountCanBeUsed` checks global state (`#accountIndex` for ID\n * uniqueness, `addressExists` for address uniqueness). Without serialization,\n * two concurrent `createAccounts` calls from different snaps could both pass\n * the uniqueness check before either one calls `setAccount`, leading to\n * duplicate accounts. Injected into each `SnapKeyringV2` via the optional\n * `withLock` callback.\n */\n readonly #lock: Mutex;\n\n /**\n * Serializes lazy keyring initialization in {@link SnapKeyring.#getOrCreateKeyring}.\n *\n * Kept separate from {@link SnapKeyring.#lock} (which guards `createAccounts`\n * uniqueness checks) to avoid mixing concerns. The lock is held only for the\n * duration of a single keyring's initialization - released before the caller\n * proceeds with its operation.\n */\n readonly #getOrCreateKeyringLock: Mutex;\n\n /**\n * Create a new Snap keyring.\n *\n * @param options - Constructor options.\n * @param options.messenger - Snap keyring messenger.\n * @param options.callbacks - Callbacks used to interact with other components.\n * @param options.isAnyAccountTypeAllowed - Whether to allow the `AnyAccountType` generic account type.\n * @returns A new Snap keyring.\n */\n constructor({\n messenger,\n callbacks,\n isAnyAccountTypeAllowed = false,\n }: {\n messenger: SnapKeyringMessenger;\n callbacks: SnapKeyringCallbacks;\n isAnyAccountTypeAllowed?: boolean;\n }) {\n this.type = SnapKeyring.type;\n this.#messenger = messenger;\n this.#snapKeyrings = new Map();\n this.#accountIndex = new Map();\n this.#callbacks = callbacks;\n this.#isAnyAccountTypeAllowed = isAnyAccountTypeAllowed;\n this.#lock = new Mutex();\n this.#getOrCreateKeyringLock = new Mutex();\n }\n\n /**\n * Get the SnapKeyringEntry for a Snap, creating and initializing it if it\n * does not exist yet.\n *\n * When a new keyring is created it is immediately initialized by calling\n * `deserialize({ snapId, accounts: {} })` so that `snapId` and the internal\n * snap client are available before any event handler or method runs.\n *\n * Both v1 and v2 share the same KeyringAccountRegistry instance. The\n * onRegister / onUnregister callbacks keep #accountIndex in sync regardless\n * of which class mutates the registry.\n *\n * @param snapId - Snap ID.\n * @returns The SnapKeyringEntry for the given Snap.\n */\n async #getOrCreateKeyring(snapId: SnapId): Promise<SnapKeyringV2> {\n // Fast path: keyring already exists, no lock needed.\n const existing = this.#snapKeyrings.get(snapId);\n if (existing) {\n return existing;\n }\n\n return this.#getOrCreateKeyringLock.runExclusive(async () => {\n // Double-check: a concurrent caller may have created the keyring while\n // we were waiting for the lock.\n const keyring = this.#snapKeyrings.get(snapId);\n if (keyring) {\n return keyring;\n }\n\n const newKeyring = new SnapKeyringV2({\n messenger: this.#messenger,\n isAnyAccountTypeAllowed: this.#isAnyAccountTypeAllowed,\n callbacks: {\n // Optional callbacks that mutate accounts are responsible for keeping\n // #accountIndex in sync via these callbacks.\n onRegister: (id: AccountId): void => {\n // We can safely use `snapId` here because we create the keyring\n // instance right away.\n this.#accountIndex.set(id, snapId);\n },\n onUnregister: (id: AccountId): void => {\n this.#accountIndex.delete(id);\n },\n // Required callbacks:\n // NOTE: `keyringSnapId` and `snapId` are the same value. The `keyringSnapId` is coming from\n // the `deserialize` call right after.\n addAccount: async (\n address,\n keyringSnapId,\n handleUserInput,\n onceSaved,\n accountNameSuggestion,\n internalOptions,\n ): Promise<void> =>\n this.#callbacks.addAccount(\n address,\n keyringSnapId,\n handleUserInput,\n onceSaved,\n accountNameSuggestion,\n internalOptions,\n ),\n removeAccount: async (\n address,\n keyringSnapId,\n handleUserInput,\n ): Promise<void> =>\n this.#callbacks.removeAccount(\n address,\n keyringSnapId,\n handleUserInput,\n ),\n saveState: async (): Promise<void> => this.#callbacks.saveState(),\n redirectUser: async (id, url, message): Promise<void> =>\n this.#callbacks.redirectUser(id, url, message),\n assertAccountCanBeUsed: async (account): Promise<void> =>\n this.#assertAccountCanBeUsed(account),\n withLock: async <Result>(\n callback: () => Promise<Result>,\n ): Promise<Result> => this.#lock.runExclusive(callback),\n },\n });\n\n // Initialize the keyring with its snap ID (no accounts yet).\n await newKeyring.deserialize({ snapId, accounts: {} });\n\n // Keyring is fully initialized; register it before releasing the lock so\n // that no concurrent caller can create a duplicate.\n this.#snapKeyrings.set(snapId, newKeyring);\n\n return newKeyring;\n });\n }\n\n /**\n * Drop a per-snap keyring from {@link #snapKeyrings} when it has no accounts.\n *\n * Without this, deleting every account for a Snap would leave an empty\n * `SnapKeyringV2` in the map for the rest of the session (unlike the old\n * `SnapIdMap`, which dropped entries on delete).\n *\n * @param snapId - Snap ID whose keyring may be removed.\n */\n async #removeSnapKeyringIfEmpty(snapId: SnapId): Promise<void> {\n const keyring = this.#snapKeyrings.get(snapId);\n if (keyring?.accounts().length === 0) {\n await keyring.destroy();\n this.#snapKeyrings.delete(snapId);\n }\n }\n\n /**\n * Asserts that an account can be used within the Snap keyring. (e.g. generic accounts, unique\n * addresses, etc...).\n *\n * @param account - The account to check.\n * @throws If the account cannot be used.\n */\n async #assertAccountCanBeUsed(account: KeyringAccount): Promise<void> {\n const address = normalizeAccountAddress(account);\n\n // The `AnyAccountType.Account` generic account type is allowed only during\n // development, so we check whether it's allowed before continuing.\n if (\n !this.#isAnyAccountTypeAllowed &&\n account.type === AnyAccountType.Account\n ) {\n throw new Error(`Cannot create generic account '${account.id}'`);\n }\n\n // A Snap could try to create an account with a different address but with\n // an existing ID, so the above test only is not enough.\n // Account IDs are globally unique across all snaps.\n if (this.#accountIndex.has(account.id)) {\n throw new Error(`Account '${account.id}' already exists`);\n }\n\n // The UI still uses the account address to identify accounts, so we need\n // to block the creation of duplicate accounts for now to prevent accounts\n // from being overwritten.\n if (await this.#callbacks.addressExists(address)) {\n throw new Error(`Account address '${address}' already exists`);\n }\n }\n\n /**\n * Handle a message from a Snap.\n *\n * Only `AccountCreated` triggers lazy keyring creation via\n * `#getOrCreateKeyring`, since that is the single entry point for the v1\n * event-driven flow. All other events from unknown snaps throw an error.\n * After handling `AccountCreated`, `#removeSnapKeyringIfEmpty` always runs\n * (via `try/finally`) to clean up if account creation was rejected.\n *\n * @param snapId - ID of the Snap.\n * @param message - Message sent by the Snap.\n * @returns The execution result.\n */\n async handleKeyringSnapMessage(\n snapId: SnapId,\n message: SnapMessage,\n ): Promise<Json> {\n let keyring = this.#snapKeyrings.get(snapId);\n\n // We can create a new keyring if the message is an AccountCreated event.\n const isAccountCreated =\n message.method === `${KeyringEvent.AccountCreated}`;\n if (!keyring && isAccountCreated) {\n keyring = await this.#getOrCreateKeyring(snapId);\n }\n\n if (!keyring) {\n throw new Error(\n `SnapKeyring - Received a message for an unknown snap keyring '${snapId}'`,\n );\n }\n\n try {\n return await keyring.handleKeyringSnapMessage(message);\n } finally {\n // Clean up if AccountCreated was rejected (e.g. duplicate address,\n // invalid account), leaving the snap with no registered accounts.\n if (isAccountCreated) {\n await this.#removeSnapKeyringIfEmpty(snapId);\n }\n }\n }\n\n /**\n * Serialize the keyring state.\n *\n * Delegates to each per-snap v2 keyring and flattens back into the original\n * external format so that `KeyringController` sees no change.\n *\n * @returns Serialized keyring state.\n */\n async serialize(): Promise<KeyringState> {\n const accounts: KeyringState['accounts'] = {};\n for (const keyring of this.#snapKeyrings.values()) {\n for (const account of keyring.accounts()) {\n accounts[account.id] = { account, snapId: keyring.snapId };\n }\n }\n return { accounts };\n }\n\n /**\n * Deserialize the keyring state into this keyring.\n *\n * Groups the flat persisted state by `snapId`, clears both indexes, then\n * rebuilds each per-snap entry. The `onRegister` callbacks fired during\n * `v2.deserialize()` automatically repopulate `#accountIndex`.\n *\n * @param state - Serialized keyring state.\n */\n async deserialize(state: KeyringState | undefined): Promise<void> {\n // If the state is undefined, it means that this is a new keyring, so we\n // don't need to do anything.\n if (state === undefined) {\n return;\n }\n\n // Group flat state by snapId. Migrations and migration logging are handled\n // inside v2.deserialize().\n const bySnap = new Map<SnapId, Record<AccountId, KeyringAccount>>();\n for (const entry of Object.values(state.accounts)) {\n const snapAccounts = bySnap.get(entry.snapId) ?? {};\n snapAccounts[entry.account.id] = entry.account;\n bySnap.set(entry.snapId, snapAccounts);\n }\n\n // Destroy existing keyrings before clearing — rejects any pending requests.\n for (const keyring of this.#snapKeyrings.values()) {\n await keyring.destroy();\n }\n\n // Clear both indexes before rebuilding — they must always be consistent.\n this.#snapKeyrings.clear();\n this.#accountIndex.clear();\n\n // Rebuild per-snap keyrings. Each keyring handles its own validation\n // and migration internally. #getOrCreateKeyring initializes the keyring\n // with an empty state; the second deserialize call loads the real accounts.\n for (const [snapId, accounts] of bySnap) {\n const keyring = await this.#getOrCreateKeyring(snapId);\n await keyring.deserialize({ snapId, accounts });\n // onRegister callbacks fired above have repopulated #accountIndex.\n await this.#removeSnapKeyringIfEmpty(snapId);\n }\n }\n\n /**\n * Get an account and its associated Snap ID from its ID.\n *\n * @param id - Account ID.\n * @throws An error if the account could not be found.\n * @returns The account associated with the given account ID in this keyring.\n */\n #getAccount(id: string): { account: KeyringAccount; snapId: SnapId } {\n const snapId = this.#accountIndex.get(id);\n const account = snapId\n ? this.#snapKeyrings.get(snapId)?.lookupAccount(id)\n : undefined;\n\n if (!snapId || !account) {\n throw new Error(`Unable to get account: unknown account ID: '${id}'`);\n }\n return { account, snapId };\n }\n\n /**\n * Get the addresses of the accounts in this keyring.\n *\n * @returns The addresses of the accounts in this keyring.\n */\n async getAccounts(): Promise<string[]> {\n const addresses: string[] = [];\n for (const keyring of this.#snapKeyrings.values()) {\n for (const account of keyring.accounts()) {\n addresses.push(normalizeAccountAddress(account));\n }\n }\n return unique(addresses);\n }\n\n /**\n * Get the addresses of the accounts associated with a given Snap.\n *\n * @param snapId - Snap ID to filter by.\n * @returns The addresses of the accounts associated with the given Snap.\n */\n async getAccountsBySnapId(snapId: SnapId): Promise<string[]> {\n return unique(\n (this.#snapKeyrings.get(snapId)?.accounts() ?? []).map(\n normalizeAccountAddress,\n ),\n );\n }\n\n /**\n * Create an account (v1 event-driven flow).\n *\n * Delegates to the per-snap SnapKeyringV1 instance.\n *\n * @param snapId - Snap ID to create the account for.\n * @param options - Account creation options. Differs between keyrings.\n * @param internalOptions - Internal Snap keyring options.\n * @returns The account object.\n */\n async createAccount(\n snapId: SnapId,\n options: Record<string, Json>,\n internalOptions?: SnapKeyringInternalOptions,\n ): Promise<KeyringAccount> {\n const keyring = await this.#getOrCreateKeyring(snapId);\n return keyring.createAccount(options, internalOptions);\n }\n\n /**\n * Creates one or more new accounts according to the provided options.\n *\n * Delegates to the per-snap SnapKeyringV2 instance which handles\n * idempotency, validation, batch tracking, state persistence, and rollback.\n *\n * @param snapId - Snap ID to create the account(s) for.\n * @param options - Options describing how to create the account(s).\n * @returns An array of the created account objects.\n */\n async createAccounts(\n snapId: SnapId,\n options: CreateAccountOptions,\n ): Promise<KeyringAccount[]> {\n const keyring = await this.#getOrCreateKeyring(snapId);\n return keyring.createAccounts(options);\n }\n\n /**\n * Checks if a Snap ID is known from the keyring.\n *\n * @param snapId - Snap ID.\n * @returns `true` if the Snap ID is known, `false` otherwise.\n */\n hasSnapId(snapId: SnapId): boolean {\n const keyring = this.#snapKeyrings.get(snapId);\n return keyring !== undefined && keyring.accounts().length > 0;\n }\n\n /**\n * Resolve the Snap account's address associated from a signing request.\n *\n * @param snapId - Snap ID.\n * @param scope - CAIP-2 chain ID.\n * @param request - Signing request object.\n * @throws An error if the Snap ID is not known from the keyring.\n * @returns The resolved address if found, `null` otherwise.\n */\n async resolveAccountAddress(\n snapId: SnapId,\n scope: CaipChainId,\n request: JsonRpcRequest,\n ): Promise<ResolvedAccountAddress | null> {\n // We do check that the incoming Snap ID is known by the keyring.\n if (!this.hasSnapId(snapId)) {\n throw new Error(\n `Unable to resolve account address: unknown Snap ID: ${snapId}`,\n );\n }\n\n const keyring = await this.#getOrCreateKeyring(snapId);\n return keyring.resolveAccountAddress(scope, request);\n }\n\n /**\n * Submit a request to a Snap from an account ID.\n *\n * This request cannot be an asynchronous keyring request.\n *\n * @param opts - Request options.\n * @param opts.origin - Send origin.\n * @param opts.account - Account ID.\n * @param opts.method - Method to call.\n * @param opts.params - Method parameters.\n * @param opts.scope - Selected chain ID (CAIP-2).\n * @returns Promise that resolves to the result of the method call.\n */\n async submitRequest({\n origin,\n account: accountId,\n method,\n params,\n scope,\n }: {\n origin: string;\n // NOTE: We use `account` here rather than `id` to avoid ambiguity with a \"request ID\".\n // We already use this same field name for `KeyringAccount`s.\n account: string;\n method: string;\n params?: Json[] | Record<string, Json>;\n scope: string;\n }): Promise<Json> {\n const { account, snapId } = this.#getAccount(accountId);\n /* istanbul ignore next */\n const keyring =\n this.#snapKeyrings.get(snapId) ??\n throwError(`No keyring found for snap '${snapId}'`);\n\n return await keyring.submitSnapRequest({\n origin,\n account,\n method: method as AccountMethod,\n params,\n scope,\n // For non-EVM (in the context of the multichain API and SIP-26), we enforce responses\n // to be synchronous.\n noPending: true,\n });\n }\n\n /**\n * Sign a transaction.\n *\n * @param address - Sender's address.\n * @param transaction - Transaction.\n * @param _opts - Transaction options (not used).\n * @returns A promise that resolves to the signed transaction.\n */\n async signTransaction(\n address: string,\n transaction: TypedTransaction,\n _opts = {},\n ): Promise<Json | TypedTransaction> {\n const { account, keyring } = this.#resolveAddress(address);\n return keyring.signTransaction(account, transaction, _opts);\n }\n\n /**\n * Sign a typed data message.\n *\n * @param address - Signer's address.\n * @param data - Data to sign.\n * @param opts - Signing options.\n * @returns The signature.\n */\n async signTypedData(\n address: string,\n data: Record<string, unknown>[] | TypedDataV1 | TypedMessage<any>,\n opts = { version: SignTypedDataVersion.V1 },\n ): Promise<string> {\n const { account, keyring } = this.#resolveAddress(address);\n return keyring.signTypedData(account, data, opts);\n }\n\n /**\n * Sign a message.\n *\n * @param address - Signer's address.\n * @param hash - Data to sign.\n * @returns The signature.\n */\n async signMessage(address: string, hash: any): Promise<string> {\n const { account, keyring } = this.#resolveAddress(address);\n return keyring.signMessage(account, hash);\n }\n\n /**\n * Sign a personal message.\n *\n * Note: KeyringController says this should return a Buffer but it actually\n * expects a string.\n *\n * @param address - Signer's address.\n * @param data - Data to sign.\n * @returns Promise of the signature.\n */\n async signPersonalMessage(address: string, data: any): Promise<string> {\n const { account, keyring } = this.#resolveAddress(address);\n return keyring.signPersonalMessage(account, data);\n }\n\n /**\n * Convert a base transaction to a base UserOperation.\n *\n * @param address - Address of the sender.\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.\n */\n async prepareUserOperation(\n address: string,\n transactions: EthBaseTransaction[],\n context: KeyringExecutionContext,\n ): Promise<EthBaseUserOperation> {\n const { account, keyring } = this.#resolveAddress(address);\n return keyring.prepareUserOperation(account, transactions, context);\n }\n\n /**\n * Patches properties of a UserOperation. Currently, only the\n * `paymasterAndData` can be patched.\n *\n * @param address - Address of the sender.\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 address: string,\n userOp: EthUserOperation,\n context: KeyringExecutionContext,\n ): Promise<EthUserOperationPatch> {\n const { account, keyring } = this.#resolveAddress(address);\n return keyring.patchUserOperation(account, userOp, context);\n }\n\n /**\n * Signs a UserOperation.\n *\n * @param address - Address of the sender.\n * @param userOp - UserOperation to sign.\n * @param context - Keyring execution context.\n * @returns The signature of the UserOperation.\n */\n async signUserOperation(\n address: string,\n userOp: EthUserOperation,\n context: KeyringExecutionContext,\n ): Promise<string> {\n const { account, keyring } = this.#resolveAddress(address);\n return keyring.signUserOperation(account, userOp, context);\n }\n\n /**\n * Gets the private data associated with the given address so\n * that it may be exported.\n *\n * If this keyring contains duplicate public keys the first\n * matching address is exported.\n *\n * Used by the UI to export an account.\n *\n * @param _address - Address of the account to export.\n */\n exportAccount(_address: string): [Uint8Array, Json] | undefined {\n throw new Error('Exporting accounts from snaps is not supported.');\n }\n\n /**\n * Removes the account matching the given address.\n *\n * Delegates to the per-snap SnapKeyringV2 keyring which handles\n * registry removal, index cleanup, and snap communication.\n *\n * @param address - Address of the account to remove.\n */\n async removeAccount(address: string): Promise<void> {\n const { account, keyring } = this.#resolveAddress(address);\n await keyring.deleteAccount(account.id);\n await this.#removeSnapKeyringIfEmpty(keyring.snapId);\n }\n\n /**\n * Resolve an address to an account and its owning keyring entry.\n *\n * @param address - Address of the account to resolve.\n * @returns Account and the per-snap keyring that owns it. Throws if not\n * found.\n */\n #resolveAddress(address: string): {\n account: KeyringAccount;\n keyring: SnapKeyringV2;\n } {\n for (const keyring of this.#snapKeyrings.values()) {\n const account = keyring.lookupByAddress(address);\n if (account) {\n return { account, keyring };\n }\n }\n return throwError(`Account '${address}' not found`);\n }\n\n /**\n * Set the selected accounts.\n *\n * Distributes the global list by snap and forwards to each v1 instance.\n *\n * @param accounts - The accounts to set as selected.\n */\n async setSelectedAccounts(accounts: AccountId[]): Promise<void> {\n // Build per-snap distribution using the account index.\n const bySnap = new Map<SnapId, AccountId[]>();\n for (const accountId of accounts) {\n const snapId = this.#accountIndex.get(accountId);\n if (!snapId) {\n continue;\n }\n const snapAccounts = bySnap.get(snapId) ?? [];\n snapAccounts.push(accountId);\n bySnap.set(snapId, snapAccounts);\n }\n\n await Promise.all(\n [...this.#snapKeyrings.entries()].map(async ([snapId, keyring]) =>\n keyring.setSelectedAccounts(\n /* istanbul ignore next */\n bySnap.get(snapId) ?? [],\n ),\n ),\n );\n }\n\n /**\n * Get the Snap associated with the given Snap ID.\n *\n * @param snapId - Snap ID.\n * @returns The Snap or undefined if the Snap cannot be found.\n */\n #getSnap(snapId: SnapId): Snap | null {\n return this.#messenger.call('SnapController:getSnap', snapId);\n }\n\n /**\n * Get the metadata of a Snap keyring account.\n *\n * @param snapId - Snap ID.\n * @returns The Snap metadata or undefined if the Snap cannot be found.\n */\n #getSnapMetadata(\n snapId: SnapId,\n ): InternalAccount['metadata']['snap'] | undefined {\n const snap = this.#getSnap(snapId);\n return snap ? { id: snapId } : undefined;\n }\n\n #transformToInternalAccount(\n account: KeyringAccount,\n snapId: SnapId,\n ): InternalAccount {\n const snap = this.#getSnapMetadata(snapId);\n\n return {\n ...account,\n // TODO: Do not convert the address to lowercase.\n //\n // This is a workaround to support the current UI which expects the\n // account address to be lowercase. This workaround should be removed\n // once we migrated the UI to use the account ID instead of the account\n // address.\n //\n // NOTE: We convert the address only for EVM accounts, see\n // `normalizeAccountAddress`.\n address: normalizeAccountAddress(account),\n metadata: {\n name: '',\n importTime: 0,\n keyring: {\n type: this.type,\n },\n ...(snap !== undefined && { snap }),\n },\n };\n }\n\n /**\n * Return an internal account object for a given address.\n *\n * @param address - Address of the account to return.\n * @returns An internal account object for the given address.\n */\n getAccountByAddress(address: string): InternalAccount | undefined {\n for (const [snapId, keyring] of this.#snapKeyrings) {\n const account = keyring.lookupByAddress(address);\n if (account) {\n return this.#transformToInternalAccount(account, snapId);\n }\n }\n return undefined;\n }\n\n /**\n * List all Snap keyring accounts.\n * This method is expensive on mobile devices and could takes tens or hundreds of milliseconds to complete.\n * Use with caution.\n *\n * @returns An array containing all Snap keyring accounts.\n */\n listAccounts(): InternalAccount[] {\n const accounts: InternalAccount[] = [];\n for (const [snapId, keyring] of this.#snapKeyrings) {\n for (const account of keyring.accounts()) {\n accounts.push(this.#transformToInternalAccount(account, snapId));\n }\n }\n return accounts;\n }\n}\n"]}
1
+ {"version":3,"file":"SnapKeyring.mjs","sourceRoot":"","sources":["../src/SnapKeyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,OAAO,EAAE,oBAAoB,EAAE,+BAA+B;AAY9D,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,8BAA8B;AAMrE,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EAAE,uBAAuB,EAAE,sBAAkB;AAGpD,OAAO,EAAE,iBAAiB,EAAE,mCAA+B;AAG3D,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,mBAAe;AAC5C,OAAO,EAAE,WAAW,IAAI,aAAa,EAAE,6BAAyB;AAEhE;;;;;;;GAOG;AACH,SAAS,eAAe,CACtB,OAAsB,EACtB,OAAe;IAEf,OAAO,CACL,OAAO,CAAC,EAAE;QACV,UAAU,CAAC,SAAS,OAAO,CAAC,MAAM,yBAAyB,OAAO,EAAE,CAAC,CACtE,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,iBAAiB,GAAG,cAAc,CAAC;AAwChD;;GAEG;AACH,MAAM,OAAO,WAAW;IAkEtB;;;;;;;;OAQG;IACH,YAAY,EACV,SAAS,EACT,SAAS,EACT,uBAAuB,GAAG,KAAK,GAKhC;;QA9ED,0DAA0D;QAC1D,SAAI,GAA6B,iBAAiB,CAAC;QAEnD,UAAK,GAAG,IAAI,CAAC;QAEb;;WAEG;QACM,yCAAi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;IACH,CAAC;IACD,OAAO,UAAU,CAAC,YAAY,OAAO,aAAa,CAAC,CAAC;AACtD,CAAC,uDAwCQ,MAAc;IACrB,OAAO,uBAAA,IAAI,8BAAW,CAAC,IAAI,CAAC,wBAAwB,EAAE,MAAM,CAAC,CAAC;AAChE,CAAC,uEASC,MAAc;IAEd,MAAM,IAAI,GAAG,uBAAA,IAAI,oDAAS,MAAb,IAAI,EAAU,MAAM,CAAC,CAAC;IACnC,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAC3C,CAAC,6FAGC,OAAuB,EACvB,MAAc;IAEd,MAAM,IAAI,GAAG,uBAAA,IAAI,4DAAiB,MAArB,IAAI,EAAkB,MAAM,CAAC,CAAC;IAE3C,OAAO;QACL,GAAG,OAAO;QACV,iDAAiD;QACjD,EAAE;QACF,mEAAmE;QACnE,qEAAqE;QACrE,uEAAuE;QACvE,WAAW;QACX,EAAE;QACF,0DAA0D;QAC1D,6BAA6B;QAC7B,OAAO,EAAE,uBAAuB,CAAC,OAAO,CAAC;QACzC,QAAQ,EAAE;YACR,IAAI,EAAE,EAAE;YACR,UAAU,EAAE,CAAC;YACb,OAAO,EAAE;gBACP,IAAI,EAAE,IAAI,CAAC,IAAI;aAChB;YACD,GAAG,CAAC,IAAI,KAAK,SAAS,IAAI,EAAE,IAAI,EAAE,CAAC;SACpC;KACF,CAAC;AACJ,CAAC;AAnxBM,gBAAI,GAAW,iBAAiB,AAA5B,CAA6B","sourcesContent":["import type { TypedTransaction } from '@ethereumjs/tx';\nimport type { TypedDataV1, TypedMessage } from '@metamask/eth-sig-util';\nimport { SignTypedDataVersion } from '@metamask/eth-sig-util';\nimport type {\n KeyringAccount,\n KeyringExecutionContext,\n EthBaseTransaction,\n EthBaseUserOperation,\n EthUserOperation,\n EthUserOperationPatch,\n ResolvedAccountAddress,\n CaipChainId,\n CreateAccountOptions,\n} from '@metamask/keyring-api';\nimport { AnyAccountType, KeyringEvent } from '@metamask/keyring-api';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { AccountId, JsonRpcRequest } from '@metamask/keyring-utils';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type { Snap } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport { normalizeAccountAddress } from './account';\nimport type { SnapKeyringInternalOptions } from './options';\nimport type { SnapKeyringMessenger } from './SnapKeyringMessenger';\nimport { SNAP_KEYRING_NAME } from './SnapKeyringMessenger';\nimport type { AccountMethod, SnapKeyringV1 } from './SnapKeyringV1';\nimport type { SnapMessage } from './types';\nimport { throwError, unique } from './util';\nimport { SnapKeyring as SnapKeyringV2 } from './v2/SnapKeyring';\n\n/**\n * Return the v1 instance of a per-snap keyring, throwing if the snap only\n * supports the v2 protocol.\n *\n * @param keyring - The per-snap v2 keyring.\n * @param feature - Human-readable feature name used in the error message.\n * @returns The v1 instance.\n */\nfunction getKeyringV1For(\n keyring: SnapKeyringV2,\n feature: string,\n): SnapKeyringV1 {\n return (\n keyring.v1 ??\n throwError(`Snap '${keyring.snapId}' does not support v1 ${feature}`)\n );\n}\n\nexport const SNAP_KEYRING_TYPE = 'Snap Keyring';\n\n/**\n * Snap keyring state.\n *\n * This state is persisted by the keyring controller and passed to the Snap\n * keyring when it's created.\n */\nexport type KeyringState = {\n accounts: Record<string, { account: KeyringAccount; snapId: SnapId }>;\n};\n\n/**\n * Snap keyring callbacks.\n *\n * These callbacks are used to interact with other components.\n */\nexport type SnapKeyringCallbacks = {\n saveState: () => Promise<void>;\n\n addressExists(address: string): Promise<boolean>;\n\n addAccount(\n address: string,\n snapId: SnapId,\n handleUserInput: (accepted: boolean) => Promise<void>,\n onceSaved: Promise<AccountId>,\n accountNameSuggestion?: string,\n internalOptions?: SnapKeyringInternalOptions,\n ): Promise<void>;\n\n removeAccount(\n address: string,\n snapId: SnapId,\n handleUserInput: (accepted: boolean) => Promise<void>,\n ): Promise<void>;\n\n redirectUser(snapId: SnapId, url: string, message: string): Promise<void>;\n};\n\n/**\n * Keyring bridge implementation to support Snaps.\n */\nexport class SnapKeyring {\n static type: string = SNAP_KEYRING_TYPE;\n\n type: string;\n\n // Name and state are required for modular initialisation.\n name: typeof SNAP_KEYRING_NAME = SNAP_KEYRING_NAME;\n\n state = null;\n\n /**\n * Messenger to dispatch requests to the Snaps controller.\n */\n readonly #messenger: SnapKeyringMessenger;\n\n /**\n * Per-snap keyring instances. Each `SnapKeyringV2` owns the\n * `KeyringAccountRegistry` and handles the `KeyringV2` batch interface.\n * For v1 snaps, `SnapKeyringV2.v1` holds a `SnapKeyringV1` instance\n * (with a shared registry reference) for the event-driven flow.\n */\n readonly #snapKeyrings: Map<SnapId, SnapKeyringV2>;\n\n /**\n * Reverse index from account ID to the owning Snap ID.\n *\n * Populated and kept in sync via the `onRegister` / `onUnregister`\n * callbacks injected into each entry. Enables O(1) routing for\n * any \"which snap owns this account?\" query.\n */\n readonly #accountIndex: Map<AccountId, SnapId>;\n\n /**\n * Callbacks used to interact with other components.\n */\n readonly #callbacks: SnapKeyringCallbacks;\n\n /**\n * Whether to allow the creation and update of generic accounts.\n *\n * Account deletion is not affected by this flag and is always allowed.\n */\n readonly #isAnyAccountTypeAllowed: boolean;\n\n /**\n * Global mutex that serializes `createAccounts` calls across all snaps.\n *\n * `assertAccountCanBeUsed` checks global state (`#accountIndex` for ID\n * uniqueness, `addressExists` for address uniqueness). Without serialization,\n * two concurrent `createAccounts` calls from different snaps could both pass\n * the uniqueness check before either one calls `setAccount`, leading to\n * duplicate accounts. Injected into each `SnapKeyringV2` via the optional\n * `withLock` callback.\n */\n readonly #lock: Mutex;\n\n /**\n * Serializes lazy keyring initialization in {@link SnapKeyring.#getOrCreateKeyring}.\n *\n * Kept separate from {@link SnapKeyring.#lock} (which guards `createAccounts`\n * uniqueness checks) to avoid mixing concerns. The lock is held only for the\n * duration of a single keyring's initialization - released before the caller\n * proceeds with its operation.\n */\n readonly #getOrCreateKeyringLock: Mutex;\n\n /**\n * Create a new Snap keyring.\n *\n * @param options - Constructor options.\n * @param options.messenger - Snap keyring messenger.\n * @param options.callbacks - Callbacks used to interact with other components.\n * @param options.isAnyAccountTypeAllowed - Whether to allow the `AnyAccountType` generic account type.\n * @returns A new Snap keyring.\n */\n constructor({\n messenger,\n callbacks,\n isAnyAccountTypeAllowed = false,\n }: {\n messenger: SnapKeyringMessenger;\n callbacks: SnapKeyringCallbacks;\n isAnyAccountTypeAllowed?: boolean;\n }) {\n this.type = SnapKeyring.type;\n this.#messenger = messenger;\n this.#snapKeyrings = new Map();\n this.#accountIndex = new Map();\n this.#callbacks = callbacks;\n this.#isAnyAccountTypeAllowed = isAnyAccountTypeAllowed;\n this.#lock = new Mutex();\n this.#getOrCreateKeyringLock = new Mutex();\n }\n\n /**\n * Get the SnapKeyringEntry for a Snap, creating and initializing it if it\n * does not exist yet.\n *\n * When a new keyring is created it is immediately initialized by calling\n * `deserialize({ snapId, accounts: {} })` so that `snapId` and the internal\n * snap client are available before any event handler or method runs.\n *\n * Both v1 and v2 share the same KeyringAccountRegistry instance. The\n * onRegister / onUnregister callbacks keep #accountIndex in sync regardless\n * of which class mutates the registry.\n *\n * @param snapId - Snap ID.\n * @returns The SnapKeyringEntry for the given Snap.\n */\n async #getOrCreateKeyring(snapId: SnapId): Promise<SnapKeyringV2> {\n // Fast path: keyring already exists, no lock needed.\n const existing = this.#snapKeyrings.get(snapId);\n if (existing) {\n return existing;\n }\n\n return this.#getOrCreateKeyringLock.runExclusive(async () => {\n // Double-check: a concurrent caller may have created the keyring while\n // we were waiting for the lock.\n const keyring = this.#snapKeyrings.get(snapId);\n if (keyring) {\n return keyring;\n }\n\n const newKeyring = new SnapKeyringV2({\n messenger: this.#messenger,\n isAnyAccountTypeAllowed: this.#isAnyAccountTypeAllowed,\n callbacks: {\n // Optional callbacks that mutate accounts are responsible for keeping\n // #accountIndex in sync via these callbacks.\n onRegister: (id: AccountId): void => {\n // We can safely use `snapId` here because we create the keyring\n // instance right away.\n this.#accountIndex.set(id, snapId);\n },\n onUnregister: (id: AccountId): void => {\n this.#accountIndex.delete(id);\n },\n // Required callbacks:\n // NOTE: `keyringSnapId` and `snapId` are the same value. The `keyringSnapId` is coming from\n // the `deserialize` call right after.\n addAccount: async (\n address,\n keyringSnapId,\n handleUserInput,\n onceSaved,\n accountNameSuggestion,\n internalOptions,\n ): Promise<void> =>\n this.#callbacks.addAccount(\n address,\n keyringSnapId,\n handleUserInput,\n onceSaved,\n accountNameSuggestion,\n internalOptions,\n ),\n removeAccount: async (\n address,\n keyringSnapId,\n handleUserInput,\n ): Promise<void> =>\n this.#callbacks.removeAccount(\n address,\n keyringSnapId,\n handleUserInput,\n ),\n saveState: async (): Promise<void> => this.#callbacks.saveState(),\n redirectUser: async (id, url, message): Promise<void> =>\n this.#callbacks.redirectUser(id, url, message),\n assertAccountCanBeUsed: async (account): Promise<void> =>\n this.#assertAccountCanBeUsed(account),\n withLock: async <Result>(\n callback: () => Promise<Result>,\n ): Promise<Result> => this.#lock.runExclusive(callback),\n },\n });\n\n // Initialize the keyring with its snap ID (no accounts yet).\n await newKeyring.deserialize({ snapId, accounts: {} });\n\n // Keyring is fully initialized; register it before releasing the lock so\n // that no concurrent caller can create a duplicate.\n this.#snapKeyrings.set(snapId, newKeyring);\n\n return newKeyring;\n });\n }\n\n /**\n * Drop a per-snap keyring from {@link #snapKeyrings} when it has no accounts.\n *\n * Without this, deleting every account for a Snap would leave an empty\n * `SnapKeyringV2` in the map for the rest of the session (unlike the old\n * `SnapIdMap`, which dropped entries on delete).\n *\n * @param snapId - Snap ID whose keyring may be removed.\n */\n async #removeSnapKeyringIfEmpty(snapId: SnapId): Promise<void> {\n const keyring = this.#snapKeyrings.get(snapId);\n if (keyring?.accounts().length === 0) {\n await keyring.destroy();\n this.#snapKeyrings.delete(snapId);\n }\n }\n\n /**\n * Asserts that an account can be used within the Snap keyring. (e.g. generic accounts, unique\n * addresses, etc...).\n *\n * @param account - The account to check.\n * @throws If the account cannot be used.\n */\n async #assertAccountCanBeUsed(account: KeyringAccount): Promise<void> {\n const address = normalizeAccountAddress(account);\n\n // The `AnyAccountType.Account` generic account type is allowed only during\n // development, so we check whether it's allowed before continuing.\n if (\n !this.#isAnyAccountTypeAllowed &&\n account.type === AnyAccountType.Account\n ) {\n throw new Error(`Cannot create generic account '${account.id}'`);\n }\n\n // A Snap could try to create an account with a different address but with\n // an existing ID, so the above test only is not enough.\n // Account IDs are globally unique across all snaps.\n if (this.#accountIndex.has(account.id)) {\n throw new Error(`Account '${account.id}' already exists`);\n }\n\n // The UI still uses the account address to identify accounts, so we need\n // to block the creation of duplicate accounts for now to prevent accounts\n // from being overwritten.\n if (await this.#callbacks.addressExists(address)) {\n throw new Error(`Account address '${address}' already exists`);\n }\n }\n\n /**\n * Handle a message from a Snap.\n *\n * Only `AccountCreated` triggers lazy keyring creation via\n * `#getOrCreateKeyring`, since that is the single entry point for the v1\n * event-driven flow. All other events from unknown snaps throw an error.\n * After handling `AccountCreated`, `#removeSnapKeyringIfEmpty` always runs\n * (via `try/finally`) to clean up if account creation was rejected.\n *\n * @param snapId - ID of the Snap.\n * @param message - Message sent by the Snap.\n * @returns The execution result.\n */\n async handleKeyringSnapMessage(\n snapId: SnapId,\n message: SnapMessage,\n ): Promise<Json> {\n let keyring = this.#snapKeyrings.get(snapId);\n\n // We can create a new keyring if the message is an AccountCreated event.\n const isAccountCreated =\n message.method === `${KeyringEvent.AccountCreated}`;\n if (!keyring && isAccountCreated) {\n keyring = await this.#getOrCreateKeyring(snapId);\n }\n\n if (!keyring) {\n throw new Error(\n `SnapKeyring - Received a message for an unknown snap keyring '${snapId}'`,\n );\n }\n\n try {\n return await getKeyringV1For(\n keyring,\n 'messages',\n ).handleKeyringSnapMessage(message);\n } finally {\n // Clean up if AccountCreated was rejected (e.g. duplicate address,\n // invalid account), leaving the snap with no registered accounts.\n if (isAccountCreated) {\n await this.#removeSnapKeyringIfEmpty(snapId);\n }\n }\n }\n\n /**\n * Serialize the keyring state.\n *\n * Delegates to each per-snap v2 keyring and flattens back into the original\n * external format so that `KeyringController` sees no change.\n *\n * @returns Serialized keyring state.\n */\n async serialize(): Promise<KeyringState> {\n const accounts: KeyringState['accounts'] = {};\n for (const keyring of this.#snapKeyrings.values()) {\n for (const account of keyring.accounts()) {\n accounts[account.id] = { account, snapId: keyring.snapId };\n }\n }\n return { accounts };\n }\n\n /**\n * Deserialize the keyring state into this keyring.\n *\n * Groups the flat persisted state by `snapId`, clears both indexes, then\n * rebuilds each per-snap entry. The `onRegister` callbacks fired during\n * `v2.deserialize()` automatically repopulate `#accountIndex`.\n *\n * @param state - Serialized keyring state.\n */\n async deserialize(state: KeyringState | undefined): Promise<void> {\n // If the state is undefined, it means that this is a new keyring, so we\n // don't need to do anything.\n if (state === undefined) {\n return;\n }\n\n // Group flat state by snapId. Migrations and migration logging are handled\n // inside v2.deserialize().\n const bySnap = new Map<SnapId, Record<AccountId, KeyringAccount>>();\n for (const entry of Object.values(state.accounts)) {\n const snapAccounts = bySnap.get(entry.snapId) ?? {};\n snapAccounts[entry.account.id] = entry.account;\n bySnap.set(entry.snapId, snapAccounts);\n }\n\n // Destroy existing keyrings before clearing — rejects any pending requests.\n for (const keyring of this.#snapKeyrings.values()) {\n await keyring.destroy();\n }\n\n // Clear both indexes before rebuilding — they must always be consistent.\n this.#snapKeyrings.clear();\n this.#accountIndex.clear();\n\n // Rebuild per-snap keyrings. Each keyring handles its own validation\n // and migration internally. #getOrCreateKeyring initializes the keyring\n // with an empty state; the second deserialize call loads the real accounts.\n for (const [snapId, accounts] of bySnap) {\n const keyring = await this.#getOrCreateKeyring(snapId);\n await keyring.deserialize({ snapId, accounts });\n // onRegister callbacks fired above have repopulated #accountIndex.\n await this.#removeSnapKeyringIfEmpty(snapId);\n }\n }\n\n /**\n * Get an account and its associated Snap ID from its ID.\n *\n * @param id - Account ID.\n * @throws An error if the account could not be found.\n * @returns The account associated with the given account ID in this keyring.\n */\n #getAccount(id: string): { account: KeyringAccount; snapId: SnapId } {\n const snapId = this.#accountIndex.get(id);\n const account = snapId\n ? this.#snapKeyrings.get(snapId)?.lookupAccount(id)\n : undefined;\n\n if (!snapId || !account) {\n throw new Error(`Unable to get account: unknown account ID: '${id}'`);\n }\n return { account, snapId };\n }\n\n /**\n * Get the addresses of the accounts in this keyring.\n *\n * @returns The addresses of the accounts in this keyring.\n */\n async getAccounts(): Promise<string[]> {\n const addresses: string[] = [];\n for (const keyring of this.#snapKeyrings.values()) {\n for (const account of keyring.accounts()) {\n addresses.push(normalizeAccountAddress(account));\n }\n }\n return unique(addresses);\n }\n\n /**\n * Get the addresses of the accounts associated with a given Snap.\n *\n * @param snapId - Snap ID to filter by.\n * @returns The addresses of the accounts associated with the given Snap.\n */\n async getAccountsBySnapId(snapId: SnapId): Promise<string[]> {\n return unique(\n (this.#snapKeyrings.get(snapId)?.accounts() ?? []).map(\n normalizeAccountAddress,\n ),\n );\n }\n\n /**\n * Create an account (v1 event-driven flow).\n *\n * Delegates to the per-snap SnapKeyringV2 instance (v1 flow).\n *\n * @param snapId - Snap ID to create the account for.\n * @param options - Account creation options. Differs between keyrings.\n * @param internalOptions - Internal Snap keyring options.\n * @returns The account object.\n */\n async createAccount(\n snapId: SnapId,\n options: Record<string, Json>,\n internalOptions?: SnapKeyringInternalOptions,\n ): Promise<KeyringAccount> {\n const keyring = await this.#getOrCreateKeyring(snapId);\n return getKeyringV1For(keyring, 'account creation').createAccount(\n options,\n internalOptions,\n );\n }\n\n /**\n * Creates one or more new accounts according to the provided options.\n *\n * Delegates to the per-snap SnapKeyringV2 instance which handles\n * idempotency, validation, batch tracking, state persistence, and rollback.\n *\n * @param snapId - Snap ID to create the account(s) for.\n * @param options - Options describing how to create the account(s).\n * @returns An array of the created account objects.\n */\n async createAccounts(\n snapId: SnapId,\n options: CreateAccountOptions,\n ): Promise<KeyringAccount[]> {\n const keyring = await this.#getOrCreateKeyring(snapId);\n return keyring.createAccounts(options);\n }\n\n /**\n * Checks if a Snap ID is known from the keyring.\n *\n * @param snapId - Snap ID.\n * @returns `true` if the Snap ID is known, `false` otherwise.\n */\n hasSnapId(snapId: SnapId): boolean {\n const keyring = this.#snapKeyrings.get(snapId);\n return keyring !== undefined && keyring.accounts().length > 0;\n }\n\n /**\n * Resolve the Snap account's address associated from a signing request.\n *\n * @param snapId - Snap ID.\n * @param scope - CAIP-2 chain ID.\n * @param request - Signing request object.\n * @throws An error if the Snap ID is not known from the keyring.\n * @returns The resolved address if found, `null` otherwise.\n */\n async resolveAccountAddress(\n snapId: SnapId,\n scope: CaipChainId,\n request: JsonRpcRequest,\n ): Promise<ResolvedAccountAddress | null> {\n // We do check that the incoming Snap ID is known by the keyring.\n if (!this.hasSnapId(snapId)) {\n throw new Error(\n `Unable to resolve account address: unknown Snap ID: ${snapId}`,\n );\n }\n\n const keyring = await this.#getOrCreateKeyring(snapId);\n return getKeyringV1For(keyring, 'address resolution').resolveAccountAddress(\n scope,\n request,\n );\n }\n\n /**\n * Submit a request to a Snap from an account ID.\n *\n * This request cannot be an asynchronous keyring request.\n *\n * @param opts - Request options.\n * @param opts.origin - Send origin.\n * @param opts.account - Account ID.\n * @param opts.method - Method to call.\n * @param opts.params - Method parameters.\n * @param opts.scope - Selected chain ID (CAIP-2).\n * @returns Promise that resolves to the result of the method call.\n */\n async submitRequest({\n origin,\n account: accountId,\n method,\n params,\n scope,\n }: {\n origin: string;\n // NOTE: We use `account` here rather than `id` to avoid ambiguity with a \"request ID\".\n // We already use this same field name for `KeyringAccount`s.\n account: string;\n method: string;\n params?: Json[] | Record<string, Json>;\n scope: string;\n }): Promise<Json> {\n const { account, snapId } = this.#getAccount(accountId);\n /* istanbul ignore next */\n const keyring =\n this.#snapKeyrings.get(snapId) ??\n throwError(`No keyring found for snap '${snapId}'`);\n\n return await getKeyringV1For(keyring, 'requests').submitSnapRequest({\n origin,\n account,\n method: method as AccountMethod,\n params,\n scope,\n // For non-EVM (in the context of the multichain API and SIP-26), we enforce responses\n // to be synchronous.\n noPending: true,\n });\n }\n\n /**\n * Sign a transaction.\n *\n * @param address - Sender's address.\n * @param transaction - Transaction.\n * @param _opts - Transaction options (not used).\n * @returns A promise that resolves to the signed transaction.\n */\n async signTransaction(\n address: string,\n transaction: TypedTransaction,\n _opts = {},\n ): Promise<Json | TypedTransaction> {\n const { account, keyring } = this.#resolveAddress(address);\n return getKeyringV1For(keyring, 'signing').signTransaction(\n account,\n transaction,\n _opts,\n );\n }\n\n /**\n * Sign a typed data message.\n *\n * @param address - Signer's address.\n * @param data - Data to sign.\n * @param opts - Signing options.\n * @returns The signature.\n */\n async signTypedData(\n address: string,\n data: Record<string, unknown>[] | TypedDataV1 | TypedMessage<any>,\n opts = { version: SignTypedDataVersion.V1 },\n ): Promise<string> {\n const { account, keyring } = this.#resolveAddress(address);\n return getKeyringV1For(keyring, 'signing').signTypedData(\n account,\n data,\n opts,\n );\n }\n\n /**\n * Sign a message.\n *\n * @param address - Signer's address.\n * @param hash - Data to sign.\n * @returns The signature.\n */\n async signMessage(address: string, hash: any): Promise<string> {\n const { account, keyring } = this.#resolveAddress(address);\n return getKeyringV1For(keyring, 'signing').signMessage(account, hash);\n }\n\n /**\n * Sign a personal message.\n *\n * Note: KeyringController says this should return a Buffer but it actually\n * expects a string.\n *\n * @param address - Signer's address.\n * @param data - Data to sign.\n * @returns Promise of the signature.\n */\n async signPersonalMessage(address: string, data: any): Promise<string> {\n const { account, keyring } = this.#resolveAddress(address);\n return getKeyringV1For(keyring, 'signing').signPersonalMessage(\n account,\n data,\n );\n }\n\n /**\n * Convert a base transaction to a base UserOperation.\n *\n * @param address - Address of the sender.\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.\n */\n async prepareUserOperation(\n address: string,\n transactions: EthBaseTransaction[],\n context: KeyringExecutionContext,\n ): Promise<EthBaseUserOperation> {\n const { account, keyring } = this.#resolveAddress(address);\n return getKeyringV1For(\n keyring,\n 'prepareUserOperation',\n ).prepareUserOperation(account, transactions, context);\n }\n\n /**\n * Patches properties of a UserOperation. Currently, only the\n * `paymasterAndData` can be patched.\n *\n * @param address - Address of the sender.\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 address: string,\n userOp: EthUserOperation,\n context: KeyringExecutionContext,\n ): Promise<EthUserOperationPatch> {\n const { account, keyring } = this.#resolveAddress(address);\n return getKeyringV1For(keyring, 'patchUserOperation').patchUserOperation(\n account,\n userOp,\n context,\n );\n }\n\n /**\n * Signs a UserOperation.\n *\n * @param address - Address of the sender.\n * @param userOp - UserOperation to sign.\n * @param context - Keyring execution context.\n * @returns The signature of the UserOperation.\n */\n async signUserOperation(\n address: string,\n userOp: EthUserOperation,\n context: KeyringExecutionContext,\n ): Promise<string> {\n const { account, keyring } = this.#resolveAddress(address);\n return getKeyringV1For(keyring, 'signUserOperation').signUserOperation(\n account,\n userOp,\n context,\n );\n }\n\n /**\n * Gets the private data associated with the given address so\n * that it may be exported.\n *\n * If this keyring contains duplicate public keys the first\n * matching address is exported.\n *\n * Used by the UI to export an account.\n *\n * @param _address - Address of the account to export.\n */\n exportAccount(_address: string): [Uint8Array, Json] | undefined {\n throw new Error('Exporting accounts from snaps is not supported.');\n }\n\n /**\n * Removes the account matching the given address.\n *\n * Delegates to the per-snap SnapKeyringV2 keyring which handles\n * registry removal, index cleanup, and snap communication.\n *\n * @param address - Address of the account to remove.\n */\n async removeAccount(address: string): Promise<void> {\n const { account, keyring } = this.#resolveAddress(address);\n await keyring.deleteAccount(account.id);\n await this.#removeSnapKeyringIfEmpty(keyring.snapId);\n }\n\n /**\n * Resolve an address to an account and its owning keyring entry.\n *\n * @param address - Address of the account to resolve.\n * @returns Account and the per-snap keyring that owns it. Throws if not\n * found.\n */\n #resolveAddress(address: string): {\n account: KeyringAccount;\n keyring: SnapKeyringV2;\n } {\n for (const keyring of this.#snapKeyrings.values()) {\n const account = keyring.lookupByAddress(address);\n if (account) {\n return { account, keyring };\n }\n }\n return throwError(`Account '${address}' not found`);\n }\n\n /**\n * Set the selected accounts.\n *\n * Distributes the global list by snap and forwards to each v1 instance.\n *\n * @param accounts - The accounts to set as selected.\n */\n async setSelectedAccounts(accounts: AccountId[]): Promise<void> {\n // Build per-snap distribution using the account index.\n const bySnap = new Map<SnapId, AccountId[]>();\n for (const accountId of accounts) {\n const snapId = this.#accountIndex.get(accountId);\n if (!snapId) {\n continue;\n }\n const snapAccounts = bySnap.get(snapId) ?? [];\n snapAccounts.push(accountId);\n bySnap.set(snapId, snapAccounts);\n }\n\n // v1 snaps receive a keyring_setSelectedAccounts notification; v2 snaps\n // have no equivalent concept in the protocol so they are intentionally skipped.\n await Promise.all(\n [...this.#snapKeyrings.entries()].map(async ([snapId, keyring]) =>\n keyring.v1?.setSelectedAccounts(\n /* istanbul ignore next */\n bySnap.get(snapId) ?? [],\n ),\n ),\n );\n }\n\n /**\n * Get the Snap associated with the given Snap ID.\n *\n * @param snapId - Snap ID.\n * @returns The Snap or undefined if the Snap cannot be found.\n */\n #getSnap(snapId: SnapId): Snap | null {\n return this.#messenger.call('SnapController:getSnap', snapId);\n }\n\n /**\n * Get the metadata of a Snap keyring account.\n *\n * @param snapId - Snap ID.\n * @returns The Snap metadata or undefined if the Snap cannot be found.\n */\n #getSnapMetadata(\n snapId: SnapId,\n ): InternalAccount['metadata']['snap'] | undefined {\n const snap = this.#getSnap(snapId);\n return snap ? { id: snapId } : undefined;\n }\n\n #transformToInternalAccount(\n account: KeyringAccount,\n snapId: SnapId,\n ): InternalAccount {\n const snap = this.#getSnapMetadata(snapId);\n\n return {\n ...account,\n // TODO: Do not convert the address to lowercase.\n //\n // This is a workaround to support the current UI which expects the\n // account address to be lowercase. This workaround should be removed\n // once we migrated the UI to use the account ID instead of the account\n // address.\n //\n // NOTE: We convert the address only for EVM accounts, see\n // `normalizeAccountAddress`.\n address: normalizeAccountAddress(account),\n metadata: {\n name: '',\n importTime: 0,\n keyring: {\n type: this.type,\n },\n ...(snap !== undefined && { snap }),\n },\n };\n }\n\n /**\n * Return an internal account object for a given address.\n *\n * @param address - Address of the account to return.\n * @returns An internal account object for the given address.\n */\n getAccountByAddress(address: string): InternalAccount | undefined {\n for (const [snapId, keyring] of this.#snapKeyrings) {\n const account = keyring.lookupByAddress(address);\n if (account) {\n return this.#transformToInternalAccount(account, snapId);\n }\n }\n return undefined;\n }\n\n /**\n * List all Snap keyring accounts.\n * This method is expensive on mobile devices and could takes tens or hundreds of milliseconds to complete.\n * Use with caution.\n *\n * @returns An array containing all Snap keyring accounts.\n */\n listAccounts(): InternalAccount[] {\n const accounts: InternalAccount[] = [];\n for (const [snapId, keyring] of this.#snapKeyrings) {\n for (const account of keyring.accounts()) {\n accounts.push(this.#transformToInternalAccount(account, snapId));\n }\n }\n return accounts;\n }\n}\n"]}
@@ -73,7 +73,7 @@ class SnapKeyringV1 {
73
73
  get client() {
74
74
  return this.context.client;
75
75
  }
76
- constructor({ messenger, callbacks, isAnyAccountTypeAllowed = false, }) {
76
+ constructor({ messenger, callbacks, isAnyAccountTypeAllowed = false, registry, }) {
77
77
  _SnapKeyringV1_instances.add(this);
78
78
  /** Snap ID and RPC client. Set via {@link bindSnapId}. */
79
79
  _SnapKeyringV1_context.set(this, void 0);
@@ -95,7 +95,7 @@ class SnapKeyringV1 {
95
95
  * The currently selected account IDs for this snap.
96
96
  */
97
97
  _SnapKeyringV1_selectedAccounts.set(this, void 0);
98
- this.registry = new keyring_sdk_1.KeyringAccountRegistry();
98
+ this.registry = registry ?? new keyring_sdk_1.KeyringAccountRegistry();
99
99
  this.messenger = messenger;
100
100
  __classPrivateFieldSet(this, _SnapKeyringV1_callbacks, callbacks, "f");
101
101
  __classPrivateFieldSet(this, _SnapKeyringV1_isAnyAccountTypeAllowed, isAnyAccountTypeAllowed, "f");
@@ -155,6 +155,20 @@ class SnapKeyringV1 {
155
155
  async createAccount(options, internalOptions) {
156
156
  return __classPrivateFieldGet(this, _SnapKeyringV1_instances, "m", _SnapKeyringV1_createSnapAccount).call(this, options, internalOptions);
157
157
  }
158
+ /**
159
+ * Create one or more accounts using the v1 synchronous RPC flow.
160
+ *
161
+ * Delegates to the v1 internal snap client, which wraps `options` in
162
+ * `{ options }` before sending `keyring_createAccounts` — unlike the v2
163
+ * client which sends flat `options`. Called by `SnapKeyring` (v2) when the
164
+ * snap has no declared capabilities (i.e. it is a v1 snap).
165
+ *
166
+ * @param options - Account creation options forwarded to the snap.
167
+ * @returns The array of accounts returned by the snap.
168
+ */
169
+ async createAccounts(options) {
170
+ return this.client.createAccounts(options);
171
+ }
158
172
  /**
159
173
  * Handle an incoming message from the Snap.
160
174
  *
@@ -1 +1 @@
1
- {"version":3,"file":"SnapKeyringV1.cjs","sourceRoot":"","sources":["../src/SnapKeyringV1.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,uCAAoD;AAEpD,yDAA8D;AAY9D,uDAU+B;AAC/B,yEAA+E;AAC/E,yFAAmF;AACnF,uDAA+D;AAC/D,iEAGoC;AAGpC,2DAAqD;AAGrD,uDAAqE;AAErE,2CAMyB;AACzB,+BAAkC;AAElC,2CAA+D;AAC/D,2CAAoD;AACpD,yCAMkB;AAClB,yCAAgD;AAChD,2CAAiD;AAEjD,+DAAuF;AAMvF,uCAA4C;AAC5C,qCAA2E;AA6F3E;;;;;;;;;GASG;AACH,MAAa,aAAa;IAiCxB;;;;;OAKG;IACH,IAAc,OAAO;QACnB,IAAI,uBAAA,IAAI,8BAAS,KAAK,SAAS,EAAE,CAAC;YAChC,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;QACJ,CAAC;QACD,OAAO,uBAAA,IAAI,8BAAS,CAAC;IACvB,CAAC;IAED;;;;;OAKG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;IAC7B,CAAC;IAED;;;;;OAKG;IACH,IAAc,MAAM;QAClB,O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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 GetSelectedAccountsRequestStruct,\n SnapManageAccountsMethod,\n} from '@metamask/keyring-snap-sdk';\nimport type { GetSelectedAccountsResponse } 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 { normalizeAccount, transformAccount } from './account';\nimport { normalizeAccountAddress } from './account';\nimport {\n AccountCreatedEventStruct,\n AccountUpdatedEventStruct,\n AccountDeletedEventStruct,\n RequestApprovedEventStruct,\n RequestRejectedEventStruct,\n} from './events';\nimport { projectLogger as log } from './logger';\nimport { getInternalOptionsOf } from './options';\nimport type { SnapKeyringInternalOptions } 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 { equalsIgnoreCase, sanitizeUrl, throwError, toJson } from './util';\n\n// TODO: to be removed when this is added to the keyring-api\nexport type AccountMethod = EthMethod | BtcMethod;\n\n/**\n * Holds the snap ID and its RPC client once a {@link SnapKeyringV1} instance\n * has been bound via {@link SnapKeyringV1.bindSnapId}.\n */\ntype SnapKeyringV1Context = {\n snapId: SnapId;\n client: KeyringInternalSnapClient;\n};\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 */\n addAccount: (\n address: string,\n snapId: SnapId,\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 */\n removeAccount: (\n address: string,\n snapId: SnapId,\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: (snapId: SnapId, 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 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 /** Snap ID and RPC client. Set via {@link bindSnapId}. */\n #context: SnapKeyringV1Context | undefined;\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 /** 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 /**\n * Initialized context (snap ID + RPC client).\n *\n * @throws If the keyring has not been initialized yet.\n * @returns The initialized context.\n */\n protected get context(): SnapKeyringV1Context {\n if (this.#context === undefined) {\n throw new Error(\n 'SnapKeyring has not been initialized: call deserialize() first',\n );\n }\n return this.#context;\n }\n\n /**\n * The snap ID this instance is scoped to.\n *\n * @throws If the keyring has not been initialized yet.\n * @returns The snap ID.\n */\n get snapId(): SnapId {\n return this.context.snapId;\n }\n\n /**\n * Snap client for keyring RPC calls.\n *\n * @throws If the keyring has not been initialized yet.\n * @returns The internal snap client.\n */\n protected get client(): KeyringInternalSnapClient {\n return this.context.client;\n }\n\n constructor({\n messenger,\n callbacks,\n isAnyAccountTypeAllowed = false,\n }: SnapKeyringV1Options) {\n this.registry = new KeyringAccountRegistry();\n this.messenger = messenger;\n this.#callbacks = callbacks;\n this.#isAnyAccountTypeAllowed = isAnyAccountTypeAllowed;\n this.#requests = new Map();\n this.#options = new Map();\n this.#selectedAccounts = [];\n }\n\n /**\n * Bind this keyring to a snap ID and create the internal snap 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 this keyring to.\n * @throws If the keyring is already bound to a different snap ID.\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 // Public API\n // ──────────────────────────────────────────────\n\n /**\n * Destroy this keyring, rejecting any pending requests.\n *\n * Called when the per-snap entry is removed from the parent `SnapKeyring`,\n * either because all accounts were deleted or because state was re-deserialized.\n */\n async destroy(): Promise<void> {\n for (const promise of this.#requests.values()) {\n promise.reject(\n new Error(`Keyring for snap '${this.snapId}' has been destroyed`),\n );\n }\n this.#requests.clear();\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 = normalizeAccount(transformAccount(newAccountFromEvent));\n const { address } = 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.snapId,\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((deleteError: unknown) => {\n console.error(\n `Account '${account.id}' may not have been removed from snap '${this.snapId}':`,\n deleteError,\n );\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 this.snapId,\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 * Protected so that `SnapKeyringV2` can reuse it without duplicating the\n * logic.\n *\n * @param account - The account to check.\n * @returns The existing account if found, `undefined` otherwise.\n */\n protected getExistingAccount(\n account: KeyringAccount,\n ): 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(this.snapId, 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"]}
1
+ {"version":3,"file":"SnapKeyringV1.cjs","sourceRoot":"","sources":["../src/SnapKeyringV1.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,uCAAoD;AAEpD,yDAA8D;AAY9D,uDAU+B;AAE/B,yEAA+E;AAC/E,yFAAmF;AACnF,uDAA+D;AAC/D,iEAGoC;AAGpC,2DAAqD;AAGrD,uDAAqE;AAErE,2CAMyB;AACzB,+BAAkC;AAElC,2CAA+D;AAC/D,2CAAoD;AACpD,yCAMkB;AAClB,yCAAgD;AAChD,2CAAiD;AAEjD,+DAAuF;AAMvF,uCAA4C;AAC5C,qCAA2E;AAmG3E;;;;;;;;;GASG;AACH,MAAa,aAAa;IAiCxB;;;;;OAKG;IACH,IAAc,OAAO;QACnB,IAAI,uBAAA,IAAI,8BAAS,KAAK,SAAS,EAAE,CAAC;YAChC,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;QACJ,CAAC;QACD,OAAO,uBAAA,IAAI,8BAAS,CAAC;IACvB,CAAC;IAED;;;;;OAKG;IACH,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;IAC7B,CAAC;IAED;;;;;OAKG;IACH,IAAc,MAAM;QAClB,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;IAC7B,CAAC;IAED,YAAY,EACV,SAAS,EACT,SAAS,EACT,uBAAuB,GAAG,KAAK,EAC/B,QAAQ,GACa;;QAxEvB,0DAA0D;QAC1D,yCAA2C;QAQ3C,wDAAwD;QAC/C,2CAAmC;QAE5C,oEAAoE;QAC3D,yDAAkC;QAE3C;;;WAGG;QACM,0CAA6C;QAEtD;;;WAGG;QACM,yCAAkD;QAE3D;;WAEG;QACH,kDAA+B;QA2C7B,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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 type { CreateAccountOptions } from '@metamask/keyring-api/v2';\nimport { toKeyringRequestWithoutOrigin } from '@metamask/keyring-internal-api';\nimport { KeyringInternalSnapClient } from '@metamask/keyring-internal-snap-client';\nimport { KeyringAccountRegistry } from '@metamask/keyring-sdk';\nimport {\n GetSelectedAccountsRequestStruct,\n SnapManageAccountsMethod,\n} from '@metamask/keyring-snap-sdk';\nimport type { GetSelectedAccountsResponse } 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 { normalizeAccount, transformAccount } from './account';\nimport { normalizeAccountAddress } from './account';\nimport {\n AccountCreatedEventStruct,\n AccountUpdatedEventStruct,\n AccountDeletedEventStruct,\n RequestApprovedEventStruct,\n RequestRejectedEventStruct,\n} from './events';\nimport { projectLogger as log } from './logger';\nimport { getInternalOptionsOf } from './options';\nimport type { SnapKeyringInternalOptions } 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 { equalsIgnoreCase, sanitizeUrl, throwError, toJson } from './util';\n\n// TODO: to be removed when this is added to the keyring-api\nexport type AccountMethod = EthMethod | BtcMethod;\n\n/**\n * Holds the snap ID and its RPC client once a {@link SnapKeyringV1} instance\n * has been bound via {@link SnapKeyringV1.bindSnapId}.\n */\ntype SnapKeyringV1Context = {\n snapId: SnapId;\n client: KeyringInternalSnapClient;\n};\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 */\n addAccount: (\n address: string,\n snapId: SnapId,\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 */\n removeAccount: (\n address: string,\n snapId: SnapId,\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: (snapId: SnapId, 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 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 * Account registry to use. When provided (e.g. by a owning `SnapKeyring`\n * v2 instance), the registry is shared by reference. When omitted, a new\n * registry is created (useful for standalone / test usage).\n */\n registry?: KeyringAccountRegistry;\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 /** Snap ID and RPC client. Set via {@link bindSnapId}. */\n #context: SnapKeyringV1Context | undefined;\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 /** 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 /**\n * Initialized context (snap ID + RPC client).\n *\n * @throws If the keyring has not been initialized yet.\n * @returns The initialized context.\n */\n protected get context(): SnapKeyringV1Context {\n if (this.#context === undefined) {\n throw new Error(\n 'SnapKeyring has not been initialized: call deserialize() first',\n );\n }\n return this.#context;\n }\n\n /**\n * The snap ID this instance is scoped to.\n *\n * @throws If the keyring has not been initialized yet.\n * @returns The snap ID.\n */\n get snapId(): SnapId {\n return this.context.snapId;\n }\n\n /**\n * Snap client for keyring RPC calls.\n *\n * @throws If the keyring has not been initialized yet.\n * @returns The internal snap client.\n */\n protected get client(): KeyringInternalSnapClient {\n return this.context.client;\n }\n\n constructor({\n messenger,\n callbacks,\n isAnyAccountTypeAllowed = false,\n registry,\n }: SnapKeyringV1Options) {\n this.registry = registry ?? new KeyringAccountRegistry();\n this.messenger = messenger;\n this.#callbacks = callbacks;\n this.#isAnyAccountTypeAllowed = isAnyAccountTypeAllowed;\n this.#requests = new Map();\n this.#options = new Map();\n this.#selectedAccounts = [];\n }\n\n /**\n * Bind this keyring to a snap ID and create the internal snap 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 this keyring to.\n * @throws If the keyring is already bound to a different snap ID.\n */\n 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 // Public API\n // ──────────────────────────────────────────────\n\n /**\n * Destroy this keyring, rejecting any pending requests.\n *\n * Called when the per-snap entry is removed from the parent `SnapKeyring`,\n * either because all accounts were deleted or because state was re-deserialized.\n */\n async destroy(): Promise<void> {\n for (const promise of this.#requests.values()) {\n promise.reject(\n new Error(`Keyring for snap '${this.snapId}' has been destroyed`),\n );\n }\n this.#requests.clear();\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 * Create one or more accounts using the v1 synchronous RPC flow.\n *\n * Delegates to the v1 internal snap client, which wraps `options` in\n * `{ options }` before sending `keyring_createAccounts` — unlike the v2\n * client which sends flat `options`. Called by `SnapKeyring` (v2) when the\n * snap has no declared capabilities (i.e. it is a v1 snap).\n *\n * @param options - Account creation options forwarded to the snap.\n * @returns The array of accounts returned by the snap.\n */\n async createAccounts(\n options: CreateAccountOptions,\n ): Promise<KeyringAccount[]> {\n return this.client.createAccounts(options);\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 = normalizeAccount(transformAccount(newAccountFromEvent));\n const { address } = 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.snapId,\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((deleteError: unknown) => {\n console.error(\n `Account '${account.id}' may not have been removed from snap '${this.snapId}':`,\n deleteError,\n );\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 this.snapId,\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 * Protected so that `SnapKeyringV2` can reuse it without duplicating the\n * logic.\n *\n * @param account - The account to check.\n * @returns The existing account if found, `undefined` otherwise.\n */\n protected getExistingAccount(\n account: KeyringAccount,\n ): 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(this.snapId, 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"]}
@@ -3,6 +3,7 @@ import type { TypedDataV1, TypedMessage } from "@metamask/eth-sig-util";
3
3
  import { SignTypedDataVersion } from "@metamask/eth-sig-util";
4
4
  import type { KeyringAccount, BtcMethod, CaipChainId, ResolvedAccountAddress, KeyringExecutionContext, EthBaseTransaction, EthBaseUserOperation, EthUserOperation, EthUserOperationPatch } from "@metamask/keyring-api";
5
5
  import { EthMethod } from "@metamask/keyring-api";
6
+ import type { CreateAccountOptions } from "@metamask/keyring-api/v2";
6
7
  import { KeyringInternalSnapClient } from "@metamask/keyring-internal-snap-client";
7
8
  import { KeyringAccountRegistry } from "@metamask/keyring-sdk";
8
9
  import type { AccountId, JsonRpcRequest } from "@metamask/keyring-utils";
@@ -72,6 +73,12 @@ export type SnapKeyringV1Options = {
72
73
  * Defaults to `false`.
73
74
  */
74
75
  isAnyAccountTypeAllowed?: boolean;
76
+ /**
77
+ * Account registry to use. When provided (e.g. by a owning `SnapKeyring`
78
+ * v2 instance), the registry is shared by reference. When omitted, a new
79
+ * registry is created (useful for standalone / test usage).
80
+ */
81
+ registry?: KeyringAccountRegistry;
75
82
  };
76
83
  /**
77
84
  * Per-snap coordinator for the v1 (event-driven) keyring flow.
@@ -110,7 +117,7 @@ export declare class SnapKeyringV1 {
110
117
  * @returns The internal snap client.
111
118
  */
112
119
  protected get client(): KeyringInternalSnapClient;
113
- constructor({ messenger, callbacks, isAnyAccountTypeAllowed, }: SnapKeyringV1Options);
120
+ constructor({ messenger, callbacks, isAnyAccountTypeAllowed, registry, }: SnapKeyringV1Options);
114
121
  /**
115
122
  * Bind this keyring to a snap ID and create the internal snap client.
116
123
  *
@@ -120,7 +127,7 @@ export declare class SnapKeyringV1 {
120
127
  * @param snapId - The snap ID to bind this keyring to.
121
128
  * @throws If the keyring is already bound to a different snap ID.
122
129
  */
123
- protected bindSnapId(snapId: SnapId): void;
130
+ bindSnapId(snapId: SnapId): void;
124
131
  /**
125
132
  * Destroy this keyring, rejecting any pending requests.
126
133
  *
@@ -140,6 +147,18 @@ export declare class SnapKeyringV1 {
140
147
  * @returns The account object returned by the snap.
141
148
  */
142
149
  createAccount(options: Record<string, Json>, internalOptions?: SnapKeyringInternalOptions): Promise<KeyringAccount>;
150
+ /**
151
+ * Create one or more accounts using the v1 synchronous RPC flow.
152
+ *
153
+ * Delegates to the v1 internal snap client, which wraps `options` in
154
+ * `{ options }` before sending `keyring_createAccounts` — unlike the v2
155
+ * client which sends flat `options`. Called by `SnapKeyring` (v2) when the
156
+ * snap has no declared capabilities (i.e. it is a v1 snap).
157
+ *
158
+ * @param options - Account creation options forwarded to the snap.
159
+ * @returns The array of accounts returned by the snap.
160
+ */
161
+ createAccounts(options: CreateAccountOptions): Promise<KeyringAccount[]>;
143
162
  /**
144
163
  * Handle an incoming message from the Snap.
145
164
  *