@metamask-previews/account-tree-controller 7.6.1-preview-58a4a8b71 → 7.6.1-preview-4c8a5dfcb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +1 -5
  2. package/dist/AccountTreeController-method-action-types.cjs.map +1 -1
  3. package/dist/AccountTreeController-method-action-types.d.cts +1 -34
  4. package/dist/AccountTreeController-method-action-types.d.cts.map +1 -1
  5. package/dist/AccountTreeController-method-action-types.d.mts +1 -34
  6. package/dist/AccountTreeController-method-action-types.d.mts.map +1 -1
  7. package/dist/AccountTreeController-method-action-types.mjs.map +1 -1
  8. package/dist/AccountTreeController.cjs +0 -42
  9. package/dist/AccountTreeController.cjs.map +1 -1
  10. package/dist/AccountTreeController.d.cts +0 -29
  11. package/dist/AccountTreeController.d.cts.map +1 -1
  12. package/dist/AccountTreeController.d.mts +0 -29
  13. package/dist/AccountTreeController.d.mts.map +1 -1
  14. package/dist/AccountTreeController.mjs +0 -42
  15. package/dist/AccountTreeController.mjs.map +1 -1
  16. package/dist/index.cjs +1 -10
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +1 -6
  19. package/dist/index.d.cts.map +1 -1
  20. package/dist/index.d.mts +1 -6
  21. package/dist/index.d.mts.map +1 -1
  22. package/dist/index.mjs +0 -3
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/types.cjs.map +1 -1
  25. package/dist/types.d.cts +3 -3
  26. package/dist/types.d.cts.map +1 -1
  27. package/dist/types.d.mts +3 -3
  28. package/dist/types.d.mts.map +1 -1
  29. package/dist/types.mjs.map +1 -1
  30. package/package.json +1 -3
  31. package/dist/state/export.cjs +0 -210
  32. package/dist/state/export.cjs.map +0 -1
  33. package/dist/state/export.d.cts +0 -40
  34. package/dist/state/export.d.cts.map +0 -1
  35. package/dist/state/export.d.mts +0 -40
  36. package/dist/state/export.d.mts.map +0 -1
  37. package/dist/state/export.mjs +0 -204
  38. package/dist/state/export.mjs.map +0 -1
  39. package/dist/state/id-map.cjs +0 -59
  40. package/dist/state/id-map.cjs.map +0 -1
  41. package/dist/state/id-map.d.cts +0 -41
  42. package/dist/state/id-map.d.cts.map +0 -1
  43. package/dist/state/id-map.d.mts +0 -41
  44. package/dist/state/id-map.d.mts.map +0 -1
  45. package/dist/state/id-map.mjs +0 -55
  46. package/dist/state/id-map.mjs.map +0 -1
  47. package/dist/state/import.cjs +0 -233
  48. package/dist/state/import.cjs.map +0 -1
  49. package/dist/state/import.d.cts +0 -29
  50. package/dist/state/import.d.cts.map +0 -1
  51. package/dist/state/import.d.mts +0 -29
  52. package/dist/state/import.d.mts.map +0 -1
  53. package/dist/state/import.mjs +0 -229
  54. package/dist/state/import.mjs.map +0 -1
  55. package/dist/state/payload.cjs +0 -159
  56. package/dist/state/payload.cjs.map +0 -1
  57. package/dist/state/payload.d.cts +0 -287
  58. package/dist/state/payload.d.cts.map +0 -1
  59. package/dist/state/payload.d.mts +0 -287
  60. package/dist/state/payload.d.mts.map +0 -1
  61. package/dist/state/payload.mjs +0 -152
  62. package/dist/state/payload.mjs.map +0 -1
  63. package/dist/state/snapshot.cjs +0 -203
  64. package/dist/state/snapshot.cjs.map +0 -1
  65. package/dist/state/snapshot.d.cts +0 -111
  66. package/dist/state/snapshot.d.cts.map +0 -1
  67. package/dist/state/snapshot.d.mts +0 -111
  68. package/dist/state/snapshot.d.mts.map +0 -1
  69. package/dist/state/snapshot.mjs +0 -199
  70. package/dist/state/snapshot.mjs.map +0 -1
@@ -1,233 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.importState = void 0;
4
- const account_api_1 = require("@metamask/account-api");
5
- const accounts_controller_1 = require("@metamask/accounts-controller");
6
- const v2_1 = require("@metamask/eth-hd-keyring/v2");
7
- const keyring_api_1 = require("@metamask/keyring-api");
8
- const keyring_controller_1 = require("@metamask/keyring-controller");
9
- const keyring_sdk_1 = require("@metamask/keyring-sdk");
10
- const export_js_1 = require("./export.cjs");
11
- const payload_js_1 = require("./payload.cjs");
12
- /**
13
- * Searches the local wallet tree for an entropy wallet whose stable payload ID
14
- * matches `payloadWalletId`. The entropy source ID is derived on-the-fly via
15
- * `KeyringController:withKeyringV2Unsafe` rather than relying on cached metadata.
16
- *
17
- * @param context - Import context.
18
- * @param payloadWalletId - Payload wallet ID to match against.
19
- * @returns The matching local entropy wallet, or `undefined` if not found.
20
- */
21
- async function findLocalWalletMnemonicFromPayloadId(context, payloadWalletId) {
22
- const wallets = Object.values(context.getState().accountTree.wallets);
23
- for (const wallet of wallets) {
24
- if ((0, export_js_1.isMnemonicWalletObject)(wallet)) {
25
- const result = await context.messenger.call('KeyringController:withKeyringV2Unsafe', { id: wallet.metadata.entropy.id }, async ({ keyring }) => {
26
- const hdKeyring = keyring;
27
- return (0, payload_js_1.toWalletPayloadId)(await hdKeyring.toEntropySourceId());
28
- });
29
- const localPayloadId = result;
30
- if (localPayloadId === payloadWalletId) {
31
- return wallet;
32
- }
33
- }
34
- }
35
- return undefined;
36
- }
37
- /**
38
- * Returns the local entropy wallet for the given ID.
39
- *
40
- * @param context - Import context.
41
- * @param id - Local wallet ID.
42
- * @returns The entropy wallet object.
43
- * @throws If the wallet is not found or is not an entropy wallet.
44
- */
45
- function findLocalWalletMnemonicFromId(context, id) {
46
- const localWallets = context.getState().accountTree.wallets;
47
- const localWallet = localWallets[id];
48
- if (!localWallet) {
49
- throw new Error(`Failed to import mnemonic wallet: wallet not found after creation`);
50
- }
51
- if (!(0, export_js_1.isMnemonicWalletObject)(localWallet)) {
52
- throw new Error(`Failed to import mnemonic wallet: wallet is not of type 'mnemonic'`);
53
- }
54
- return localWallet;
55
- }
56
- /**
57
- * Applies name, pinned, and hidden metadata from a payload group entry to a local group.
58
- *
59
- * @param context - Import context providing the metadata setters.
60
- * @param localGroupId - Local group ID to update.
61
- * @param payloadGroupMetadata - Metadata from the payload group entry.
62
- */
63
- function setGroupMetadata(context, localGroupId, payloadGroupMetadata) {
64
- context.setGroupName(localGroupId, payloadGroupMetadata.name);
65
- context.setGroupPinned(localGroupId, payloadGroupMetadata.pinned);
66
- context.setGroupHidden(localGroupId, payloadGroupMetadata.hidden);
67
- }
68
- /**
69
- * Computes the contiguous ranges of group indices that are present in the payload
70
- * but absent from the local wallet, so they can be created in batches.
71
- *
72
- * @param localWallet - The local entropy wallet to check existing groups against.
73
- * @param payloadGroups - Ordered group entries from the payload.
74
- * @returns An array of `[fromGroupIndex, toGroupIndex]` ranges to create.
75
- */
76
- function getRangesFromPayloadGroups(localWallet, payloadGroups) {
77
- let rangeIndex;
78
- const ranges = [];
79
- // Keep track of the last payload group so we can close the final range if needed.
80
- let lastPayloadGroup;
81
- for (const payloadGroup of payloadGroups) {
82
- const localGroupId = (0, account_api_1.toMultichainAccountGroupId)(localWallet.id, payloadGroup.groupIndex);
83
- if (localWallet.groups[localGroupId]) {
84
- if (rangeIndex !== undefined) {
85
- ranges.push([rangeIndex, payloadGroup.groupIndex - 1]);
86
- rangeIndex = undefined;
87
- }
88
- continue;
89
- }
90
- rangeIndex ?? (rangeIndex = payloadGroup.groupIndex);
91
- lastPayloadGroup = payloadGroup;
92
- }
93
- if (rangeIndex !== undefined && lastPayloadGroup !== undefined) {
94
- ranges.push([rangeIndex, lastPayloadGroup.groupIndex]);
95
- }
96
- return ranges;
97
- }
98
- /**
99
- * Applies a mnemonic wallet payload entry to the local state.
100
- *
101
- * If no local wallet with the same entropy source ID exists and a mnemonic is
102
- * present in the payload, a new HD wallet is created via
103
- * `MultichainAccountService:createMultichainAccountWallet`. Missing groups are
104
- * created in batches via `MultichainAccountService:createMultichainAccountGroups`.
105
- * Metadata (name, pinned, hidden) is applied to all groups afterward.
106
- *
107
- * @param context - Import context.
108
- * @param payloadWallet - The mnemonic wallet entry from the payload.
109
- */
110
- async function importMnemonicWallet(context, payloadWallet) {
111
- // Find the local wallet with the same entropy source ID if it exists.
112
- let localWallet = await findLocalWalletMnemonicFromPayloadId(context, payloadWallet.id);
113
- if (!localWallet) {
114
- if (!payloadWallet.value) {
115
- // No mnemonic in payload and wallet doesn't exist locally -- nothing to do.
116
- return;
117
- }
118
- // Import the mnemonic as a new HD wallet.
119
- const mnemonic = (0, keyring_sdk_1.decodeMnemonicWords)(payloadWallet.value);
120
- const { id } = await context.messenger.call('MultichainAccountService:createMultichainAccountWallet', { type: 'import', mnemonic });
121
- // Event handlers fire synchronously, so the wallet is in the tree now.
122
- localWallet = findLocalWalletMnemonicFromId(context, id);
123
- }
124
- context.setWalletName(localWallet.id, payloadWallet.metadata.name);
125
- for (const range of getRangesFromPayloadGroups(localWallet, payloadWallet.groups)) {
126
- await context.messenger.call('MultichainAccountService:createMultichainAccountGroups', {
127
- entropySource: localWallet.metadata.entropy.id,
128
- fromGroupIndex: range[0],
129
- toGroupIndex: range[1],
130
- });
131
- }
132
- // Re-read wallet after groups creation.
133
- localWallet = findLocalWalletMnemonicFromId(context, localWallet.id);
134
- for (const payloadGroup of payloadWallet.groups) {
135
- const localGroupId = (0, account_api_1.toMultichainAccountGroupId)(localWallet.id, payloadGroup.groupIndex);
136
- setGroupMetadata(context, localGroupId, payloadGroup.metadata);
137
- }
138
- }
139
- /**
140
- * Applies private-key wallet group entries from the payload to the local state.
141
- *
142
- * For each group the account address is derived from the payload group ID. If the
143
- * account does not yet exist locally and a private key is provided, it is imported
144
- * via `KeyringController:withKeyringV2` using the `'private-key:import'` constructor.
145
- * Metadata (name, pinned, hidden) is then applied to the local group.
146
- *
147
- * @param context - Import context.
148
- * @param payloadGroups - Private-key group entries from the payload.
149
- */
150
- async function importPrivateKeyWallet(context, payloadGroups) {
151
- for (const payloadGroup of payloadGroups) {
152
- // Only EVM EOA accounts are supported for now. Non-EVM private keys require
153
- // Snap-based import routing (ADR-0007), which is not yet implemented. Skip the
154
- // entire entry so payloads from future clients are accepted without crashing.
155
- const privateKeyType = payloadGroup.value?.type;
156
- if (privateKeyType !== undefined && privateKeyType !== keyring_api_1.EthAccountType.Eoa) {
157
- continue;
158
- }
159
- // Payload group ID format: "wallet:private-key/<address>"
160
- const payloadAccountAddress = (0, payload_js_1.parsePayloadGroupId)(payloadGroup.id).subId;
161
- const payloadAccountId = (0, accounts_controller_1.getUUIDFromAddressOfNormalAccount)(payloadAccountAddress);
162
- const localWalletId = (0, account_api_1.toAccountWalletId)(account_api_1.AccountWalletType.Keyring, keyring_controller_1.KeyringTypes.simple);
163
- const localGroupId = (0, account_api_1.toAccountGroupId)(localWalletId, payloadAccountAddress);
164
- let localWallets = context.getState().accountTree.wallets;
165
- let localWallet = localWallets[localWalletId];
166
- let localGroup = localWallet?.groups[localGroupId];
167
- // EVM accounts have deterministic IDs, so we can re-use this to find the local group if it exists.
168
- const hasAccount = localGroup?.accounts.some((id) => id === payloadAccountId) ?? false;
169
- // If it doesn't exist, we need to import the private key.
170
- if (!hasAccount) {
171
- if (!payloadGroup.value) {
172
- // No importable secret -- skip this account.
173
- continue;
174
- }
175
- const { privateKey, encoding } = payloadGroup.value;
176
- const accounts = await context.messenger.call('KeyringController:withController', async (controller) => {
177
- // Find the existing simple keyring or create one if this is the
178
- // first private-key import (e.g. during onboarding).
179
- const existing = controller.keyrings.find(({ keyring }) => keyring.type === keyring_controller_1.KeyringTypes.simple);
180
- const { keyringV2 } = existing ?? (await controller.addNewKeyring(keyring_controller_1.KeyringTypes.simple));
181
- if (!keyringV2) {
182
- throw new Error('Simple keyring has no v2 interface');
183
- }
184
- return keyringV2.createAccounts({
185
- type: 'private-key:import',
186
- accountType: keyring_api_1.EthAccountType.Eoa,
187
- privateKey,
188
- encoding,
189
- });
190
- });
191
- // There should only be 1 account in the keyring after import.
192
- const [account] = accounts;
193
- if (!account) {
194
- throw new Error('Failed to import private key for account');
195
- }
196
- }
197
- // Find the local group that contains this account.
198
- localWallets = context.getState().accountTree.wallets;
199
- localWallet = localWallets[localWalletId];
200
- localGroup = localWallet?.groups[localGroupId];
201
- if (!localGroup) {
202
- continue;
203
- }
204
- setGroupMetadata(context, localGroup.id, payloadGroup.metadata);
205
- }
206
- }
207
- /**
208
- * Applies an {@link AccountTreeSnapshot} to the current controller state.
209
- *
210
- * The snapshot must already have been validated — typically via
211
- * {@link AccountTreeSnapshot.deserialize}. For each retained wallet:
212
- *
213
- * - `'mnemonic'`: imports the mnemonic when provided and not already present,
214
- * then applies metadata to all groups.
215
- * - `'private-key'`: imports each retained group's key when provided and not
216
- * already present, then applies metadata.
217
- *
218
- * @param context - Import context providing state, messenger, and setters.
219
- * @param snapshot - The validated snapshot to import.
220
- */
221
- async function importState(context, snapshot) {
222
- const payload = snapshot.serialize();
223
- for (const wallet of payload.data.wallets) {
224
- if (wallet.type === 'mnemonic') {
225
- await importMnemonicWallet(context, wallet);
226
- }
227
- else {
228
- await importPrivateKeyWallet(context, wallet.groups);
229
- }
230
- }
231
- }
232
- exports.importState = importState;
233
- //# sourceMappingURL=import.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"import.cjs","sourceRoot":"","sources":["../../src/state/import.ts"],"names":[],"mappings":";;;AAAA,uDAK+B;AAE/B,uEAAkF;AAClF,oDAAwD;AACxD,uDAAuE;AACvE,qEAA4D;AAC5D,uDAA4D;AAO5D,4CAAqD;AAOrD,8CAAsE;AActE;;;;;;;;GAQG;AACH,KAAK,UAAU,oCAAoC,CACjD,OAAsB,EACtB,eAAuC;IAEvC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAEtE,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,IAAA,kCAAsB,EAAC,MAAM,CAAC,EAAE,CAAC;YACnC,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,SAAS,CAAC,IAAI,CACzC,uCAAuC,EACvC,EAAE,EAAE,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,EAAE,EAClC,KAAK,EAAE,EAAE,OAAO,EAAE,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AAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC9C,CAAC;aAAM,CAAC;YACN,MAAM,sBAAsB,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;AACH,CAAC;AAbD,kCAaC","sourcesContent":["import {\n AccountWalletType,\n toAccountGroupId,\n toAccountWalletId,\n toMultichainAccountGroupId,\n} from '@metamask/account-api';\nimport type { AccountGroupId, AccountWalletId } from '@metamask/account-api';\nimport { getUUIDFromAddressOfNormalAccount } from '@metamask/accounts-controller';\nimport { HdKeyring } from '@metamask/eth-hd-keyring/v2';\nimport { EthAccountType, KeyringAccount } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport { decodeMnemonicWords } from '@metamask/keyring-sdk';\n\nimport type {\n AccountTreeControllerMessenger,\n AccountTreeControllerState,\n} from '../types.js';\nimport type { AccountWalletEntropyObject } from '../wallet.js';\nimport { isMnemonicWalletObject } from './export.js';\nimport type {\n AccountWalletMnemonicGroupEntry,\n AccountWalletMnemonicPayload,\n AccountWalletPayloadId,\n AccountWalletPrivateKeyGroupEntry,\n} from './payload.js';\nimport { parsePayloadGroupId, toWalletPayloadId } from './payload.js';\nimport type { AccountTreeSnapshot } from './snapshot.js';\n\n/** Context required by {@link importState}. */\nexport type ImportContext = {\n getState: () => AccountTreeControllerState;\n messenger: AccountTreeControllerMessenger;\n setWalletName: (walletId: AccountWalletId, name: string) => void;\n /** Sets a group name. Implementations must resolve name conflicts automatically. */\n setGroupName: (groupId: AccountGroupId, name: string) => void;\n setGroupPinned: (groupId: AccountGroupId, pinned: boolean) => void;\n setGroupHidden: (groupId: AccountGroupId, hidden: boolean) => void;\n};\n\n/**\n * Searches the local wallet tree for an entropy wallet whose stable payload ID\n * matches `payloadWalletId`. The entropy source ID is derived on-the-fly via\n * `KeyringController:withKeyringV2Unsafe` rather than relying on cached metadata.\n *\n * @param context - Import context.\n * @param payloadWalletId - Payload wallet ID to match against.\n * @returns The matching local entropy wallet, or `undefined` if not found.\n */\nasync function findLocalWalletMnemonicFromPayloadId(\n context: ImportContext,\n payloadWalletId: AccountWalletPayloadId,\n): Promise<AccountWalletEntropyObject | undefined> {\n const wallets = Object.values(context.getState().accountTree.wallets);\n\n for (const wallet of wallets) {\n if (isMnemonicWalletObject(wallet)) {\n const result = await context.messenger.call(\n 'KeyringController:withKeyringV2Unsafe',\n { id: wallet.metadata.entropy.id },\n async ({ keyring }) => {\n const hdKeyring = keyring as HdKeyring;\n\n return toWalletPayloadId(await hdKeyring.toEntropySourceId());\n },\n );\n\n const localPayloadId = result as AccountWalletPayloadId;\n if (localPayloadId === payloadWalletId) {\n return wallet;\n }\n }\n }\n\n return undefined;\n}\n\n/**\n * Returns the local entropy wallet for the given ID.\n *\n * @param context - Import context.\n * @param id - Local wallet ID.\n * @returns The entropy wallet object.\n * @throws If the wallet is not found or is not an entropy wallet.\n */\nfunction findLocalWalletMnemonicFromId(\n context: ImportContext,\n id: AccountWalletId,\n): AccountWalletEntropyObject {\n const localWallets = context.getState().accountTree.wallets;\n const localWallet = localWallets[id];\n\n if (!localWallet) {\n throw new Error(\n `Failed to import mnemonic wallet: wallet not found after creation`,\n );\n }\n if (!isMnemonicWalletObject(localWallet)) {\n throw new Error(\n `Failed to import mnemonic wallet: wallet is not of type 'mnemonic'`,\n );\n }\n return localWallet;\n}\n\n/**\n * Applies name, pinned, and hidden metadata from a payload group entry to a local group.\n *\n * @param context - Import context providing the metadata setters.\n * @param localGroupId - Local group ID to update.\n * @param payloadGroupMetadata - Metadata from the payload group entry.\n */\nfunction setGroupMetadata(\n context: ImportContext,\n localGroupId: AccountGroupId,\n payloadGroupMetadata: AccountWalletMnemonicGroupEntry['metadata'],\n): void {\n context.setGroupName(localGroupId, payloadGroupMetadata.name);\n context.setGroupPinned(localGroupId, payloadGroupMetadata.pinned);\n context.setGroupHidden(localGroupId, payloadGroupMetadata.hidden);\n}\n\n/**\n * Computes the contiguous ranges of group indices that are present in the payload\n * but absent from the local wallet, so they can be created in batches.\n *\n * @param localWallet - The local entropy wallet to check existing groups against.\n * @param payloadGroups - Ordered group entries from the payload.\n * @returns An array of `[fromGroupIndex, toGroupIndex]` ranges to create.\n */\nfunction getRangesFromPayloadGroups(\n localWallet: AccountWalletEntropyObject,\n payloadGroups: AccountWalletMnemonicGroupEntry[],\n): [number, number][] {\n let rangeIndex: number | undefined;\n const ranges: [number, number][] = [];\n\n // Keep track of the last payload group so we can close the final range if needed.\n let lastPayloadGroup: AccountWalletMnemonicGroupEntry | undefined;\n for (const payloadGroup of payloadGroups) {\n const localGroupId = toMultichainAccountGroupId(\n localWallet.id,\n payloadGroup.groupIndex,\n );\n\n if (localWallet.groups[localGroupId]) {\n if (rangeIndex !== undefined) {\n ranges.push([rangeIndex, payloadGroup.groupIndex - 1]);\n rangeIndex = undefined;\n }\n continue;\n }\n\n rangeIndex ??= payloadGroup.groupIndex;\n lastPayloadGroup = payloadGroup;\n }\n\n if (rangeIndex !== undefined && lastPayloadGroup !== undefined) {\n ranges.push([rangeIndex, lastPayloadGroup.groupIndex]);\n }\n\n return ranges;\n}\n\n/**\n * Applies a mnemonic wallet payload entry to the local state.\n *\n * If no local wallet with the same entropy source ID exists and a mnemonic is\n * present in the payload, a new HD wallet is created via\n * `MultichainAccountService:createMultichainAccountWallet`. Missing groups are\n * created in batches via `MultichainAccountService:createMultichainAccountGroups`.\n * Metadata (name, pinned, hidden) is applied to all groups afterward.\n *\n * @param context - Import context.\n * @param payloadWallet - The mnemonic wallet entry from the payload.\n */\nasync function importMnemonicWallet(\n context: ImportContext,\n payloadWallet: AccountWalletMnemonicPayload,\n): Promise<void> {\n // Find the local wallet with the same entropy source ID if it exists.\n let localWallet = await findLocalWalletMnemonicFromPayloadId(\n context,\n payloadWallet.id,\n );\n\n if (!localWallet) {\n if (!payloadWallet.value) {\n // No mnemonic in payload and wallet doesn't exist locally -- nothing to do.\n return;\n }\n\n // Import the mnemonic as a new HD wallet.\n const mnemonic = decodeMnemonicWords(payloadWallet.value);\n const { id } = await context.messenger.call(\n 'MultichainAccountService:createMultichainAccountWallet',\n { type: 'import', mnemonic },\n );\n\n // Event handlers fire synchronously, so the wallet is in the tree now.\n localWallet = findLocalWalletMnemonicFromId(context, id);\n }\n\n context.setWalletName(localWallet.id, payloadWallet.metadata.name);\n\n for (const range of getRangesFromPayloadGroups(\n localWallet,\n payloadWallet.groups,\n )) {\n await context.messenger.call(\n 'MultichainAccountService:createMultichainAccountGroups',\n {\n entropySource: localWallet.metadata.entropy.id,\n fromGroupIndex: range[0],\n toGroupIndex: range[1],\n },\n );\n }\n\n // Re-read wallet after groups creation.\n localWallet = findLocalWalletMnemonicFromId(context, localWallet.id);\n\n for (const payloadGroup of payloadWallet.groups) {\n const localGroupId = toMultichainAccountGroupId(\n localWallet.id,\n payloadGroup.groupIndex,\n );\n\n setGroupMetadata(context, localGroupId, payloadGroup.metadata);\n }\n}\n\n/**\n * Applies private-key wallet group entries from the payload to the local state.\n *\n * For each group the account address is derived from the payload group ID. If the\n * account does not yet exist locally and a private key is provided, it is imported\n * via `KeyringController:withKeyringV2` using the `'private-key:import'` constructor.\n * Metadata (name, pinned, hidden) is then applied to the local group.\n *\n * @param context - Import context.\n * @param payloadGroups - Private-key group entries from the payload.\n */\nasync function importPrivateKeyWallet(\n context: ImportContext,\n payloadGroups: AccountWalletPrivateKeyGroupEntry[],\n): Promise<void> {\n for (const payloadGroup of payloadGroups) {\n // Only EVM EOA accounts are supported for now. Non-EVM private keys require\n // Snap-based import routing (ADR-0007), which is not yet implemented. Skip the\n // entire entry so payloads from future clients are accepted without crashing.\n const privateKeyType = payloadGroup.value?.type;\n if (privateKeyType !== undefined && privateKeyType !== EthAccountType.Eoa) {\n continue;\n }\n\n // Payload group ID format: \"wallet:private-key/<address>\"\n const payloadAccountAddress = parsePayloadGroupId(payloadGroup.id).subId;\n const payloadAccountId = getUUIDFromAddressOfNormalAccount(\n payloadAccountAddress,\n );\n\n const localWalletId = toAccountWalletId(\n AccountWalletType.Keyring,\n KeyringTypes.simple,\n );\n const localGroupId = toAccountGroupId(localWalletId, payloadAccountAddress);\n\n let localWallets = context.getState().accountTree.wallets;\n let localWallet = localWallets[localWalletId];\n let localGroup = localWallet?.groups[localGroupId];\n\n // EVM accounts have deterministic IDs, so we can re-use this to find the local group if it exists.\n const hasAccount =\n localGroup?.accounts.some((id) => id === payloadAccountId) ?? false;\n\n // If it doesn't exist, we need to import the private key.\n if (!hasAccount) {\n if (!payloadGroup.value) {\n // No importable secret -- skip this account.\n continue;\n }\n\n const { privateKey, encoding } = payloadGroup.value;\n const accounts = await context.messenger.call(\n 'KeyringController:withController',\n async (controller) => {\n // Find the existing simple keyring or create one if this is the\n // first private-key import (e.g. during onboarding).\n const existing = controller.keyrings.find(\n ({ keyring }) => keyring.type === KeyringTypes.simple,\n );\n const { keyringV2 } =\n existing ?? (await controller.addNewKeyring(KeyringTypes.simple));\n\n if (!keyringV2) {\n throw new Error('Simple keyring has no v2 interface');\n }\n\n return keyringV2.createAccounts({\n type: 'private-key:import',\n accountType: EthAccountType.Eoa,\n privateKey,\n encoding,\n });\n },\n );\n\n // There should only be 1 account in the keyring after import.\n const [account] = accounts as KeyringAccount[];\n if (!account) {\n throw new Error('Failed to import private key for account');\n }\n }\n\n // Find the local group that contains this account.\n localWallets = context.getState().accountTree.wallets;\n localWallet = localWallets[localWalletId];\n localGroup = localWallet?.groups[localGroupId];\n if (!localGroup) {\n continue;\n }\n\n setGroupMetadata(context, localGroup.id, payloadGroup.metadata);\n }\n}\n\n/**\n * Applies an {@link AccountTreeSnapshot} to the current controller state.\n *\n * The snapshot must already have been validated — typically via\n * {@link AccountTreeSnapshot.deserialize}. For each retained wallet:\n *\n * - `'mnemonic'`: imports the mnemonic when provided and not already present,\n * then applies metadata to all groups.\n * - `'private-key'`: imports each retained group's key when provided and not\n * already present, then applies metadata.\n *\n * @param context - Import context providing state, messenger, and setters.\n * @param snapshot - The validated snapshot to import.\n */\nexport async function importState(\n context: ImportContext,\n snapshot: AccountTreeSnapshot,\n): Promise<void> {\n const payload = snapshot.serialize();\n\n for (const wallet of payload.data.wallets) {\n if (wallet.type === 'mnemonic') {\n await importMnemonicWallet(context, wallet);\n } else {\n await importPrivateKeyWallet(context, wallet.groups);\n }\n }\n}\n"]}
@@ -1,29 +0,0 @@
1
- import type { AccountGroupId, AccountWalletId } from "@metamask/account-api";
2
- import type { AccountTreeControllerMessenger, AccountTreeControllerState } from "../types.cjs";
3
- import type { AccountTreeSnapshot } from "./snapshot.cjs";
4
- /** Context required by {@link importState}. */
5
- export type ImportContext = {
6
- getState: () => AccountTreeControllerState;
7
- messenger: AccountTreeControllerMessenger;
8
- setWalletName: (walletId: AccountWalletId, name: string) => void;
9
- /** Sets a group name. Implementations must resolve name conflicts automatically. */
10
- setGroupName: (groupId: AccountGroupId, name: string) => void;
11
- setGroupPinned: (groupId: AccountGroupId, pinned: boolean) => void;
12
- setGroupHidden: (groupId: AccountGroupId, hidden: boolean) => void;
13
- };
14
- /**
15
- * Applies an {@link AccountTreeSnapshot} to the current controller state.
16
- *
17
- * The snapshot must already have been validated — typically via
18
- * {@link AccountTreeSnapshot.deserialize}. For each retained wallet:
19
- *
20
- * - `'mnemonic'`: imports the mnemonic when provided and not already present,
21
- * then applies metadata to all groups.
22
- * - `'private-key'`: imports each retained group's key when provided and not
23
- * already present, then applies metadata.
24
- *
25
- * @param context - Import context providing state, messenger, and setters.
26
- * @param snapshot - The validated snapshot to import.
27
- */
28
- export declare function importState(context: ImportContext, snapshot: AccountTreeSnapshot): Promise<void>;
29
- //# sourceMappingURL=import.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"import.d.cts","sourceRoot":"","sources":["../../src/state/import.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,8BAA8B;AAO7E,OAAO,KAAK,EACV,8BAA8B,EAC9B,0BAA0B,EAC3B,qBAAoB;AAUrB,OAAO,KAAK,EAAE,mBAAmB,EAAE,uBAAsB;AAEzD,+CAA+C;AAC/C,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,EAAE,MAAM,0BAA0B,CAAC;IAC3C,SAAS,EAAE,8BAA8B,CAAC;IAC1C,aAAa,EAAE,CAAC,QAAQ,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACjE,oFAAoF;IACpF,YAAY,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9D,cAAc,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;IACnE,cAAc,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;CACpE,CAAC;AAiSF;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAC/B,OAAO,EAAE,aAAa,EACtB,QAAQ,EAAE,mBAAmB,GAC5B,OAAO,CAAC,IAAI,CAAC,CAUf"}
@@ -1,29 +0,0 @@
1
- import type { AccountGroupId, AccountWalletId } from "@metamask/account-api";
2
- import type { AccountTreeControllerMessenger, AccountTreeControllerState } from "../types.mjs";
3
- import type { AccountTreeSnapshot } from "./snapshot.mjs";
4
- /** Context required by {@link importState}. */
5
- export type ImportContext = {
6
- getState: () => AccountTreeControllerState;
7
- messenger: AccountTreeControllerMessenger;
8
- setWalletName: (walletId: AccountWalletId, name: string) => void;
9
- /** Sets a group name. Implementations must resolve name conflicts automatically. */
10
- setGroupName: (groupId: AccountGroupId, name: string) => void;
11
- setGroupPinned: (groupId: AccountGroupId, pinned: boolean) => void;
12
- setGroupHidden: (groupId: AccountGroupId, hidden: boolean) => void;
13
- };
14
- /**
15
- * Applies an {@link AccountTreeSnapshot} to the current controller state.
16
- *
17
- * The snapshot must already have been validated — typically via
18
- * {@link AccountTreeSnapshot.deserialize}. For each retained wallet:
19
- *
20
- * - `'mnemonic'`: imports the mnemonic when provided and not already present,
21
- * then applies metadata to all groups.
22
- * - `'private-key'`: imports each retained group's key when provided and not
23
- * already present, then applies metadata.
24
- *
25
- * @param context - Import context providing state, messenger, and setters.
26
- * @param snapshot - The validated snapshot to import.
27
- */
28
- export declare function importState(context: ImportContext, snapshot: AccountTreeSnapshot): Promise<void>;
29
- //# sourceMappingURL=import.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"import.d.mts","sourceRoot":"","sources":["../../src/state/import.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,8BAA8B;AAO7E,OAAO,KAAK,EACV,8BAA8B,EAC9B,0BAA0B,EAC3B,qBAAoB;AAUrB,OAAO,KAAK,EAAE,mBAAmB,EAAE,uBAAsB;AAEzD,+CAA+C;AAC/C,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,EAAE,MAAM,0BAA0B,CAAC;IAC3C,SAAS,EAAE,8BAA8B,CAAC;IAC1C,aAAa,EAAE,CAAC,QAAQ,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACjE,oFAAoF;IACpF,YAAY,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9D,cAAc,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;IACnE,cAAc,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;CACpE,CAAC;AAiSF;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAC/B,OAAO,EAAE,aAAa,EACtB,QAAQ,EAAE,mBAAmB,GAC5B,OAAO,CAAC,IAAI,CAAC,CAUf"}
@@ -1,229 +0,0 @@
1
- import { AccountWalletType, toAccountGroupId, toAccountWalletId, toMultichainAccountGroupId } from "@metamask/account-api";
2
- import { getUUIDFromAddressOfNormalAccount } from "@metamask/accounts-controller";
3
- import { HdKeyring } from "@metamask/eth-hd-keyring/v2";
4
- import { EthAccountType } from "@metamask/keyring-api";
5
- import { KeyringTypes } from "@metamask/keyring-controller";
6
- import { decodeMnemonicWords } from "@metamask/keyring-sdk";
7
- import { isMnemonicWalletObject } from "./export.mjs";
8
- import { parsePayloadGroupId, toWalletPayloadId } from "./payload.mjs";
9
- /**
10
- * Searches the local wallet tree for an entropy wallet whose stable payload ID
11
- * matches `payloadWalletId`. The entropy source ID is derived on-the-fly via
12
- * `KeyringController:withKeyringV2Unsafe` rather than relying on cached metadata.
13
- *
14
- * @param context - Import context.
15
- * @param payloadWalletId - Payload wallet ID to match against.
16
- * @returns The matching local entropy wallet, or `undefined` if not found.
17
- */
18
- async function findLocalWalletMnemonicFromPayloadId(context, payloadWalletId) {
19
- const wallets = Object.values(context.getState().accountTree.wallets);
20
- for (const wallet of wallets) {
21
- if (isMnemonicWalletObject(wallet)) {
22
- const result = await context.messenger.call('KeyringController:withKeyringV2Unsafe', { id: wallet.metadata.entropy.id }, async ({ keyring }) => {
23
- const hdKeyring = keyring;
24
- return toWalletPayloadId(await hdKeyring.toEntropySourceId());
25
- });
26
- const localPayloadId = result;
27
- if (localPayloadId === payloadWalletId) {
28
- return wallet;
29
- }
30
- }
31
- }
32
- return undefined;
33
- }
34
- /**
35
- * Returns the local entropy wallet for the given ID.
36
- *
37
- * @param context - Import context.
38
- * @param id - Local wallet ID.
39
- * @returns The entropy wallet object.
40
- * @throws If the wallet is not found or is not an entropy wallet.
41
- */
42
- function findLocalWalletMnemonicFromId(context, id) {
43
- const localWallets = context.getState().accountTree.wallets;
44
- const localWallet = localWallets[id];
45
- if (!localWallet) {
46
- throw new Error(`Failed to import mnemonic wallet: wallet not found after creation`);
47
- }
48
- if (!isMnemonicWalletObject(localWallet)) {
49
- throw new Error(`Failed to import mnemonic wallet: wallet is not of type 'mnemonic'`);
50
- }
51
- return localWallet;
52
- }
53
- /**
54
- * Applies name, pinned, and hidden metadata from a payload group entry to a local group.
55
- *
56
- * @param context - Import context providing the metadata setters.
57
- * @param localGroupId - Local group ID to update.
58
- * @param payloadGroupMetadata - Metadata from the payload group entry.
59
- */
60
- function setGroupMetadata(context, localGroupId, payloadGroupMetadata) {
61
- context.setGroupName(localGroupId, payloadGroupMetadata.name);
62
- context.setGroupPinned(localGroupId, payloadGroupMetadata.pinned);
63
- context.setGroupHidden(localGroupId, payloadGroupMetadata.hidden);
64
- }
65
- /**
66
- * Computes the contiguous ranges of group indices that are present in the payload
67
- * but absent from the local wallet, so they can be created in batches.
68
- *
69
- * @param localWallet - The local entropy wallet to check existing groups against.
70
- * @param payloadGroups - Ordered group entries from the payload.
71
- * @returns An array of `[fromGroupIndex, toGroupIndex]` ranges to create.
72
- */
73
- function getRangesFromPayloadGroups(localWallet, payloadGroups) {
74
- let rangeIndex;
75
- const ranges = [];
76
- // Keep track of the last payload group so we can close the final range if needed.
77
- let lastPayloadGroup;
78
- for (const payloadGroup of payloadGroups) {
79
- const localGroupId = toMultichainAccountGroupId(localWallet.id, payloadGroup.groupIndex);
80
- if (localWallet.groups[localGroupId]) {
81
- if (rangeIndex !== undefined) {
82
- ranges.push([rangeIndex, payloadGroup.groupIndex - 1]);
83
- rangeIndex = undefined;
84
- }
85
- continue;
86
- }
87
- rangeIndex ?? (rangeIndex = payloadGroup.groupIndex);
88
- lastPayloadGroup = payloadGroup;
89
- }
90
- if (rangeIndex !== undefined && lastPayloadGroup !== undefined) {
91
- ranges.push([rangeIndex, lastPayloadGroup.groupIndex]);
92
- }
93
- return ranges;
94
- }
95
- /**
96
- * Applies a mnemonic wallet payload entry to the local state.
97
- *
98
- * If no local wallet with the same entropy source ID exists and a mnemonic is
99
- * present in the payload, a new HD wallet is created via
100
- * `MultichainAccountService:createMultichainAccountWallet`. Missing groups are
101
- * created in batches via `MultichainAccountService:createMultichainAccountGroups`.
102
- * Metadata (name, pinned, hidden) is applied to all groups afterward.
103
- *
104
- * @param context - Import context.
105
- * @param payloadWallet - The mnemonic wallet entry from the payload.
106
- */
107
- async function importMnemonicWallet(context, payloadWallet) {
108
- // Find the local wallet with the same entropy source ID if it exists.
109
- let localWallet = await findLocalWalletMnemonicFromPayloadId(context, payloadWallet.id);
110
- if (!localWallet) {
111
- if (!payloadWallet.value) {
112
- // No mnemonic in payload and wallet doesn't exist locally -- nothing to do.
113
- return;
114
- }
115
- // Import the mnemonic as a new HD wallet.
116
- const mnemonic = decodeMnemonicWords(payloadWallet.value);
117
- const { id } = await context.messenger.call('MultichainAccountService:createMultichainAccountWallet', { type: 'import', mnemonic });
118
- // Event handlers fire synchronously, so the wallet is in the tree now.
119
- localWallet = findLocalWalletMnemonicFromId(context, id);
120
- }
121
- context.setWalletName(localWallet.id, payloadWallet.metadata.name);
122
- for (const range of getRangesFromPayloadGroups(localWallet, payloadWallet.groups)) {
123
- await context.messenger.call('MultichainAccountService:createMultichainAccountGroups', {
124
- entropySource: localWallet.metadata.entropy.id,
125
- fromGroupIndex: range[0],
126
- toGroupIndex: range[1],
127
- });
128
- }
129
- // Re-read wallet after groups creation.
130
- localWallet = findLocalWalletMnemonicFromId(context, localWallet.id);
131
- for (const payloadGroup of payloadWallet.groups) {
132
- const localGroupId = toMultichainAccountGroupId(localWallet.id, payloadGroup.groupIndex);
133
- setGroupMetadata(context, localGroupId, payloadGroup.metadata);
134
- }
135
- }
136
- /**
137
- * Applies private-key wallet group entries from the payload to the local state.
138
- *
139
- * For each group the account address is derived from the payload group ID. If the
140
- * account does not yet exist locally and a private key is provided, it is imported
141
- * via `KeyringController:withKeyringV2` using the `'private-key:import'` constructor.
142
- * Metadata (name, pinned, hidden) is then applied to the local group.
143
- *
144
- * @param context - Import context.
145
- * @param payloadGroups - Private-key group entries from the payload.
146
- */
147
- async function importPrivateKeyWallet(context, payloadGroups) {
148
- for (const payloadGroup of payloadGroups) {
149
- // Only EVM EOA accounts are supported for now. Non-EVM private keys require
150
- // Snap-based import routing (ADR-0007), which is not yet implemented. Skip the
151
- // entire entry so payloads from future clients are accepted without crashing.
152
- const privateKeyType = payloadGroup.value?.type;
153
- if (privateKeyType !== undefined && privateKeyType !== EthAccountType.Eoa) {
154
- continue;
155
- }
156
- // Payload group ID format: "wallet:private-key/<address>"
157
- const payloadAccountAddress = parsePayloadGroupId(payloadGroup.id).subId;
158
- const payloadAccountId = getUUIDFromAddressOfNormalAccount(payloadAccountAddress);
159
- const localWalletId = toAccountWalletId(AccountWalletType.Keyring, KeyringTypes.simple);
160
- const localGroupId = toAccountGroupId(localWalletId, payloadAccountAddress);
161
- let localWallets = context.getState().accountTree.wallets;
162
- let localWallet = localWallets[localWalletId];
163
- let localGroup = localWallet?.groups[localGroupId];
164
- // EVM accounts have deterministic IDs, so we can re-use this to find the local group if it exists.
165
- const hasAccount = localGroup?.accounts.some((id) => id === payloadAccountId) ?? false;
166
- // If it doesn't exist, we need to import the private key.
167
- if (!hasAccount) {
168
- if (!payloadGroup.value) {
169
- // No importable secret -- skip this account.
170
- continue;
171
- }
172
- const { privateKey, encoding } = payloadGroup.value;
173
- const accounts = await context.messenger.call('KeyringController:withController', async (controller) => {
174
- // Find the existing simple keyring or create one if this is the
175
- // first private-key import (e.g. during onboarding).
176
- const existing = controller.keyrings.find(({ keyring }) => keyring.type === KeyringTypes.simple);
177
- const { keyringV2 } = existing ?? (await controller.addNewKeyring(KeyringTypes.simple));
178
- if (!keyringV2) {
179
- throw new Error('Simple keyring has no v2 interface');
180
- }
181
- return keyringV2.createAccounts({
182
- type: 'private-key:import',
183
- accountType: EthAccountType.Eoa,
184
- privateKey,
185
- encoding,
186
- });
187
- });
188
- // There should only be 1 account in the keyring after import.
189
- const [account] = accounts;
190
- if (!account) {
191
- throw new Error('Failed to import private key for account');
192
- }
193
- }
194
- // Find the local group that contains this account.
195
- localWallets = context.getState().accountTree.wallets;
196
- localWallet = localWallets[localWalletId];
197
- localGroup = localWallet?.groups[localGroupId];
198
- if (!localGroup) {
199
- continue;
200
- }
201
- setGroupMetadata(context, localGroup.id, payloadGroup.metadata);
202
- }
203
- }
204
- /**
205
- * Applies an {@link AccountTreeSnapshot} to the current controller state.
206
- *
207
- * The snapshot must already have been validated — typically via
208
- * {@link AccountTreeSnapshot.deserialize}. For each retained wallet:
209
- *
210
- * - `'mnemonic'`: imports the mnemonic when provided and not already present,
211
- * then applies metadata to all groups.
212
- * - `'private-key'`: imports each retained group's key when provided and not
213
- * already present, then applies metadata.
214
- *
215
- * @param context - Import context providing state, messenger, and setters.
216
- * @param snapshot - The validated snapshot to import.
217
- */
218
- export async function importState(context, snapshot) {
219
- const payload = snapshot.serialize();
220
- for (const wallet of payload.data.wallets) {
221
- if (wallet.type === 'mnemonic') {
222
- await importMnemonicWallet(context, wallet);
223
- }
224
- else {
225
- await importPrivateKeyWallet(context, wallet.groups);
226
- }
227
- }
228
- }
229
- //# sourceMappingURL=import.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"import.mjs","sourceRoot":"","sources":["../../src/state/import.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,0BAA0B,EAC3B,8BAA8B;AAE/B,OAAO,EAAE,iCAAiC,EAAE,sCAAsC;AAClF,OAAO,EAAE,SAAS,EAAE,oCAAoC;AACxD,OAAO,EAAE,cAAc,EAAkB,8BAA8B;AACvE,OAAO,EAAE,YAAY,EAAE,qCAAqC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,8BAA8B;AAO5D,OAAO,EAAE,sBAAsB,EAAE,qBAAoB;AAOrD,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,sBAAqB;AActE;;;;;;;;GAQG;AACH,KAAK,UAAU,oCAAoC,CACjD,OAAsB,EACtB,eAAuC;IAEvC,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IAEtE,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IAA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,CAAC,SAAS,EAAE,CAAC;IAErC,KAAK,MAAM,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;QAC1C,IAAI,MAAM,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAC/B,MAAM,oBAAoB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC9C,CAAC;aAAM,CAAC;YACN,MAAM,sBAAsB,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import {\n AccountWalletType,\n toAccountGroupId,\n toAccountWalletId,\n toMultichainAccountGroupId,\n} from '@metamask/account-api';\nimport type { AccountGroupId, AccountWalletId } from '@metamask/account-api';\nimport { getUUIDFromAddressOfNormalAccount } from '@metamask/accounts-controller';\nimport { HdKeyring } from '@metamask/eth-hd-keyring/v2';\nimport { EthAccountType, KeyringAccount } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport { decodeMnemonicWords } from '@metamask/keyring-sdk';\n\nimport type {\n AccountTreeControllerMessenger,\n AccountTreeControllerState,\n} from '../types.js';\nimport type { AccountWalletEntropyObject } from '../wallet.js';\nimport { isMnemonicWalletObject } from './export.js';\nimport type {\n AccountWalletMnemonicGroupEntry,\n AccountWalletMnemonicPayload,\n AccountWalletPayloadId,\n AccountWalletPrivateKeyGroupEntry,\n} from './payload.js';\nimport { parsePayloadGroupId, toWalletPayloadId } from './payload.js';\nimport type { AccountTreeSnapshot } from './snapshot.js';\n\n/** Context required by {@link importState}. */\nexport type ImportContext = {\n getState: () => AccountTreeControllerState;\n messenger: AccountTreeControllerMessenger;\n setWalletName: (walletId: AccountWalletId, name: string) => void;\n /** Sets a group name. Implementations must resolve name conflicts automatically. */\n setGroupName: (groupId: AccountGroupId, name: string) => void;\n setGroupPinned: (groupId: AccountGroupId, pinned: boolean) => void;\n setGroupHidden: (groupId: AccountGroupId, hidden: boolean) => void;\n};\n\n/**\n * Searches the local wallet tree for an entropy wallet whose stable payload ID\n * matches `payloadWalletId`. The entropy source ID is derived on-the-fly via\n * `KeyringController:withKeyringV2Unsafe` rather than relying on cached metadata.\n *\n * @param context - Import context.\n * @param payloadWalletId - Payload wallet ID to match against.\n * @returns The matching local entropy wallet, or `undefined` if not found.\n */\nasync function findLocalWalletMnemonicFromPayloadId(\n context: ImportContext,\n payloadWalletId: AccountWalletPayloadId,\n): Promise<AccountWalletEntropyObject | undefined> {\n const wallets = Object.values(context.getState().accountTree.wallets);\n\n for (const wallet of wallets) {\n if (isMnemonicWalletObject(wallet)) {\n const result = await context.messenger.call(\n 'KeyringController:withKeyringV2Unsafe',\n { id: wallet.metadata.entropy.id },\n async ({ keyring }) => {\n const hdKeyring = keyring as HdKeyring;\n\n return toWalletPayloadId(await hdKeyring.toEntropySourceId());\n },\n );\n\n const localPayloadId = result as AccountWalletPayloadId;\n if (localPayloadId === payloadWalletId) {\n return wallet;\n }\n }\n }\n\n return undefined;\n}\n\n/**\n * Returns the local entropy wallet for the given ID.\n *\n * @param context - Import context.\n * @param id - Local wallet ID.\n * @returns The entropy wallet object.\n * @throws If the wallet is not found or is not an entropy wallet.\n */\nfunction findLocalWalletMnemonicFromId(\n context: ImportContext,\n id: AccountWalletId,\n): AccountWalletEntropyObject {\n const localWallets = context.getState().accountTree.wallets;\n const localWallet = localWallets[id];\n\n if (!localWallet) {\n throw new Error(\n `Failed to import mnemonic wallet: wallet not found after creation`,\n );\n }\n if (!isMnemonicWalletObject(localWallet)) {\n throw new Error(\n `Failed to import mnemonic wallet: wallet is not of type 'mnemonic'`,\n );\n }\n return localWallet;\n}\n\n/**\n * Applies name, pinned, and hidden metadata from a payload group entry to a local group.\n *\n * @param context - Import context providing the metadata setters.\n * @param localGroupId - Local group ID to update.\n * @param payloadGroupMetadata - Metadata from the payload group entry.\n */\nfunction setGroupMetadata(\n context: ImportContext,\n localGroupId: AccountGroupId,\n payloadGroupMetadata: AccountWalletMnemonicGroupEntry['metadata'],\n): void {\n context.setGroupName(localGroupId, payloadGroupMetadata.name);\n context.setGroupPinned(localGroupId, payloadGroupMetadata.pinned);\n context.setGroupHidden(localGroupId, payloadGroupMetadata.hidden);\n}\n\n/**\n * Computes the contiguous ranges of group indices that are present in the payload\n * but absent from the local wallet, so they can be created in batches.\n *\n * @param localWallet - The local entropy wallet to check existing groups against.\n * @param payloadGroups - Ordered group entries from the payload.\n * @returns An array of `[fromGroupIndex, toGroupIndex]` ranges to create.\n */\nfunction getRangesFromPayloadGroups(\n localWallet: AccountWalletEntropyObject,\n payloadGroups: AccountWalletMnemonicGroupEntry[],\n): [number, number][] {\n let rangeIndex: number | undefined;\n const ranges: [number, number][] = [];\n\n // Keep track of the last payload group so we can close the final range if needed.\n let lastPayloadGroup: AccountWalletMnemonicGroupEntry | undefined;\n for (const payloadGroup of payloadGroups) {\n const localGroupId = toMultichainAccountGroupId(\n localWallet.id,\n payloadGroup.groupIndex,\n );\n\n if (localWallet.groups[localGroupId]) {\n if (rangeIndex !== undefined) {\n ranges.push([rangeIndex, payloadGroup.groupIndex - 1]);\n rangeIndex = undefined;\n }\n continue;\n }\n\n rangeIndex ??= payloadGroup.groupIndex;\n lastPayloadGroup = payloadGroup;\n }\n\n if (rangeIndex !== undefined && lastPayloadGroup !== undefined) {\n ranges.push([rangeIndex, lastPayloadGroup.groupIndex]);\n }\n\n return ranges;\n}\n\n/**\n * Applies a mnemonic wallet payload entry to the local state.\n *\n * If no local wallet with the same entropy source ID exists and a mnemonic is\n * present in the payload, a new HD wallet is created via\n * `MultichainAccountService:createMultichainAccountWallet`. Missing groups are\n * created in batches via `MultichainAccountService:createMultichainAccountGroups`.\n * Metadata (name, pinned, hidden) is applied to all groups afterward.\n *\n * @param context - Import context.\n * @param payloadWallet - The mnemonic wallet entry from the payload.\n */\nasync function importMnemonicWallet(\n context: ImportContext,\n payloadWallet: AccountWalletMnemonicPayload,\n): Promise<void> {\n // Find the local wallet with the same entropy source ID if it exists.\n let localWallet = await findLocalWalletMnemonicFromPayloadId(\n context,\n payloadWallet.id,\n );\n\n if (!localWallet) {\n if (!payloadWallet.value) {\n // No mnemonic in payload and wallet doesn't exist locally -- nothing to do.\n return;\n }\n\n // Import the mnemonic as a new HD wallet.\n const mnemonic = decodeMnemonicWords(payloadWallet.value);\n const { id } = await context.messenger.call(\n 'MultichainAccountService:createMultichainAccountWallet',\n { type: 'import', mnemonic },\n );\n\n // Event handlers fire synchronously, so the wallet is in the tree now.\n localWallet = findLocalWalletMnemonicFromId(context, id);\n }\n\n context.setWalletName(localWallet.id, payloadWallet.metadata.name);\n\n for (const range of getRangesFromPayloadGroups(\n localWallet,\n payloadWallet.groups,\n )) {\n await context.messenger.call(\n 'MultichainAccountService:createMultichainAccountGroups',\n {\n entropySource: localWallet.metadata.entropy.id,\n fromGroupIndex: range[0],\n toGroupIndex: range[1],\n },\n );\n }\n\n // Re-read wallet after groups creation.\n localWallet = findLocalWalletMnemonicFromId(context, localWallet.id);\n\n for (const payloadGroup of payloadWallet.groups) {\n const localGroupId = toMultichainAccountGroupId(\n localWallet.id,\n payloadGroup.groupIndex,\n );\n\n setGroupMetadata(context, localGroupId, payloadGroup.metadata);\n }\n}\n\n/**\n * Applies private-key wallet group entries from the payload to the local state.\n *\n * For each group the account address is derived from the payload group ID. If the\n * account does not yet exist locally and a private key is provided, it is imported\n * via `KeyringController:withKeyringV2` using the `'private-key:import'` constructor.\n * Metadata (name, pinned, hidden) is then applied to the local group.\n *\n * @param context - Import context.\n * @param payloadGroups - Private-key group entries from the payload.\n */\nasync function importPrivateKeyWallet(\n context: ImportContext,\n payloadGroups: AccountWalletPrivateKeyGroupEntry[],\n): Promise<void> {\n for (const payloadGroup of payloadGroups) {\n // Only EVM EOA accounts are supported for now. Non-EVM private keys require\n // Snap-based import routing (ADR-0007), which is not yet implemented. Skip the\n // entire entry so payloads from future clients are accepted without crashing.\n const privateKeyType = payloadGroup.value?.type;\n if (privateKeyType !== undefined && privateKeyType !== EthAccountType.Eoa) {\n continue;\n }\n\n // Payload group ID format: \"wallet:private-key/<address>\"\n const payloadAccountAddress = parsePayloadGroupId(payloadGroup.id).subId;\n const payloadAccountId = getUUIDFromAddressOfNormalAccount(\n payloadAccountAddress,\n );\n\n const localWalletId = toAccountWalletId(\n AccountWalletType.Keyring,\n KeyringTypes.simple,\n );\n const localGroupId = toAccountGroupId(localWalletId, payloadAccountAddress);\n\n let localWallets = context.getState().accountTree.wallets;\n let localWallet = localWallets[localWalletId];\n let localGroup = localWallet?.groups[localGroupId];\n\n // EVM accounts have deterministic IDs, so we can re-use this to find the local group if it exists.\n const hasAccount =\n localGroup?.accounts.some((id) => id === payloadAccountId) ?? false;\n\n // If it doesn't exist, we need to import the private key.\n if (!hasAccount) {\n if (!payloadGroup.value) {\n // No importable secret -- skip this account.\n continue;\n }\n\n const { privateKey, encoding } = payloadGroup.value;\n const accounts = await context.messenger.call(\n 'KeyringController:withController',\n async (controller) => {\n // Find the existing simple keyring or create one if this is the\n // first private-key import (e.g. during onboarding).\n const existing = controller.keyrings.find(\n ({ keyring }) => keyring.type === KeyringTypes.simple,\n );\n const { keyringV2 } =\n existing ?? (await controller.addNewKeyring(KeyringTypes.simple));\n\n if (!keyringV2) {\n throw new Error('Simple keyring has no v2 interface');\n }\n\n return keyringV2.createAccounts({\n type: 'private-key:import',\n accountType: EthAccountType.Eoa,\n privateKey,\n encoding,\n });\n },\n );\n\n // There should only be 1 account in the keyring after import.\n const [account] = accounts as KeyringAccount[];\n if (!account) {\n throw new Error('Failed to import private key for account');\n }\n }\n\n // Find the local group that contains this account.\n localWallets = context.getState().accountTree.wallets;\n localWallet = localWallets[localWalletId];\n localGroup = localWallet?.groups[localGroupId];\n if (!localGroup) {\n continue;\n }\n\n setGroupMetadata(context, localGroup.id, payloadGroup.metadata);\n }\n}\n\n/**\n * Applies an {@link AccountTreeSnapshot} to the current controller state.\n *\n * The snapshot must already have been validated — typically via\n * {@link AccountTreeSnapshot.deserialize}. For each retained wallet:\n *\n * - `'mnemonic'`: imports the mnemonic when provided and not already present,\n * then applies metadata to all groups.\n * - `'private-key'`: imports each retained group's key when provided and not\n * already present, then applies metadata.\n *\n * @param context - Import context providing state, messenger, and setters.\n * @param snapshot - The validated snapshot to import.\n */\nexport async function importState(\n context: ImportContext,\n snapshot: AccountTreeSnapshot,\n): Promise<void> {\n const payload = snapshot.serialize();\n\n for (const wallet of payload.data.wallets) {\n if (wallet.type === 'mnemonic') {\n await importMnemonicWallet(context, wallet);\n } else {\n await importPrivateKeyWallet(context, wallet.groups);\n }\n }\n}\n"]}