@metamask/accounts-controller 11.0.0 → 12.0.1
Sign up to get free protection for your applications and to get access to all the features.
- package/CHANGELOG.md +32 -1
- package/dist/AccountsController.js +7 -449
- package/dist/AccountsController.js.map +1 -1
- package/dist/AccountsController.mjs +8 -0
- package/dist/AccountsController.mjs.map +1 -0
- package/dist/chunk-7FX4HSTV.js +561 -0
- package/dist/chunk-7FX4HSTV.js.map +1 -0
- package/dist/chunk-GATPL76V.mjs +561 -0
- package/dist/chunk-GATPL76V.mjs.map +1 -0
- package/dist/chunk-HD5HN6GK.mjs +64 -0
- package/dist/chunk-HD5HN6GK.mjs.map +1 -0
- package/dist/chunk-MF4BFCSU.js +64 -0
- package/dist/chunk-MF4BFCSU.js.map +1 -0
- package/dist/index.js +12 -18
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +13 -0
- package/dist/index.mjs.map +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/dist/{AccountsController.d.ts → types/AccountsController.d.ts} +7 -5
- package/dist/types/AccountsController.d.ts.map +1 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/utils.d.ts.map +1 -0
- package/dist/utils.js +8 -59
- package/dist/utils.js.map +1 -1
- package/dist/utils.mjs +9 -0
- package/dist/utils.mjs.map +1 -0
- package/package.json +15 -5
- package/dist/AccountsController.d.ts.map +0 -1
- package/dist/index.d.ts +0 -3
- package/dist/index.d.ts.map +0 -1
- package/dist/utils.d.ts.map +0 -1
- /package/dist/{utils.d.ts → types/utils.d.ts} +0 -0
package/CHANGELOG.md
CHANGED
@@ -7,6 +7,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
7
7
|
|
8
8
|
## [Unreleased]
|
9
9
|
|
10
|
+
## [12.0.1]
|
11
|
+
|
12
|
+
### Fixed
|
13
|
+
|
14
|
+
- Fix `types` field in `package.json` ([#4047](https://github.com/MetaMask/core/pull/4047))
|
15
|
+
|
16
|
+
## [12.0.0]
|
17
|
+
|
18
|
+
### Added
|
19
|
+
|
20
|
+
- **BREAKING**: Add ESM build ([#3998](https://github.com/MetaMask/core/pull/3998))
|
21
|
+
- It's no longer possible to import files from `./dist` directly.
|
22
|
+
|
23
|
+
### Changed
|
24
|
+
|
25
|
+
- **BREAKING:** Bump `@metamask/base-controller` to `^5.0.0` ([#4039](https://github.com/MetaMask/core/pull/4039))
|
26
|
+
- This version has a number of breaking changes. See the changelog for more.
|
27
|
+
- **BREAKING:** Bump peer dependency on `@metamask/keyring-controller` to `^14.0.0` ([#4039](https://github.com/MetaMask/core/pull/4039))
|
28
|
+
|
29
|
+
### Removed
|
30
|
+
|
31
|
+
- **BREAKING:** Remove action and event types unrelated to `AccountsController` from `AccountsControllerActions` and `AccountsControllerEvents` ([#4031](https://github.com/MetaMask/core/pull/4031))
|
32
|
+
|
33
|
+
### Fixed
|
34
|
+
|
35
|
+
- **BREAKING:** Narrow allowed actions and event type for `AccountsController` messenger ([#4021](https://github.com/MetaMask/core/pull/4021), [#4031](https://github.com/MetaMask/core/pull/4031))
|
36
|
+
- Narrow type parameter `AllowedAction` from `string` to `(KeyringControllerGetKeyringForAccountAction | KeyringControllerGetKeyringsByTypeAction | KeyringControllerGetAccountsAction)['type']`.
|
37
|
+
- Narrow type parameter `AllowedEvent` from `string` to `(SnapStateChange | KeyringControllerStateChangeEvent)['type']`, removing other events from `SnapController` and `KeyringController`.
|
38
|
+
|
10
39
|
## [11.0.0]
|
11
40
|
|
12
41
|
### Changed
|
@@ -126,7 +155,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
126
155
|
|
127
156
|
- Initial release ([#1637](https://github.com/MetaMask/core/pull/1637))
|
128
157
|
|
129
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/accounts-controller@
|
158
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/accounts-controller@12.0.1...HEAD
|
159
|
+
[12.0.1]: https://github.com/MetaMask/core/compare/@metamask/accounts-controller@12.0.0...@metamask/accounts-controller@12.0.1
|
160
|
+
[12.0.0]: https://github.com/MetaMask/core/compare/@metamask/accounts-controller@11.0.0...@metamask/accounts-controller@12.0.0
|
130
161
|
[11.0.0]: https://github.com/MetaMask/core/compare/@metamask/accounts-controller@10.0.0...@metamask/accounts-controller@11.0.0
|
131
162
|
[10.0.0]: https://github.com/MetaMask/core/compare/@metamask/accounts-controller@9.0.0...@metamask/accounts-controller@10.0.0
|
132
163
|
[9.0.0]: https://github.com/MetaMask/core/compare/@metamask/accounts-controller@8.0.0...@metamask/accounts-controller@9.0.0
|
@@ -1,450 +1,8 @@
|
|
1
|
-
"use strict";
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
9
|
-
});
|
10
|
-
};
|
11
|
-
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
12
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
13
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
14
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
15
|
-
};
|
16
|
-
var _AccountsController_instances, _AccountsController_generateInternalAccountForNonSnapAccount, _AccountsController_listSnapAccounts, _AccountsController_listNormalAccounts, _AccountsController_handleOnKeyringStateChange, _AccountsController_handleOnSnapStateChange, _AccountsController_getNextAccountNumber, _AccountsController_handleNewAccountAdded, _AccountsController_handleAccountRemoved, _AccountsController_registerMessageHandlers;
|
17
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
18
|
-
exports.AccountsController = void 0;
|
19
|
-
const util_1 = require("@ethereumjs/util");
|
20
|
-
const base_controller_1 = require("@metamask/base-controller");
|
21
|
-
const eth_snap_keyring_1 = require("@metamask/eth-snap-keyring");
|
22
|
-
const keyring_api_1 = require("@metamask/keyring-api");
|
23
|
-
const keyring_controller_1 = require("@metamask/keyring-controller");
|
24
|
-
const sha256_1 = require("ethereum-cryptography/sha256");
|
25
|
-
const uuid_1 = require("uuid");
|
26
|
-
const utils_1 = require("./utils");
|
27
|
-
const controllerName = 'AccountsController';
|
28
|
-
const accountsControllerMetadata = {
|
29
|
-
internalAccounts: {
|
30
|
-
persist: true,
|
31
|
-
anonymous: false,
|
32
|
-
},
|
33
|
-
};
|
34
|
-
const defaultState = {
|
35
|
-
internalAccounts: {
|
36
|
-
accounts: {},
|
37
|
-
selectedAccount: '',
|
38
|
-
},
|
39
|
-
};
|
40
|
-
/**
|
41
|
-
* Controller that manages internal accounts.
|
42
|
-
* The accounts controller is responsible for creating and managing internal accounts.
|
43
|
-
* It also provides convenience methods for accessing and updating the internal accounts.
|
44
|
-
* The accounts controller also listens for keyring state changes and updates the internal accounts accordingly.
|
45
|
-
* The accounts controller also listens for snap state changes and updates the internal accounts accordingly.
|
46
|
-
*
|
47
|
-
*/
|
48
|
-
class AccountsController extends base_controller_1.BaseController {
|
49
|
-
/**
|
50
|
-
* Constructor for AccountsController.
|
51
|
-
*
|
52
|
-
* @param options - The controller options.
|
53
|
-
* @param options.messenger - The messenger object.
|
54
|
-
* @param options.state - Initial state to set on this controller
|
55
|
-
*/
|
56
|
-
constructor({ messenger, state, }) {
|
57
|
-
super({
|
58
|
-
messenger,
|
59
|
-
name: controllerName,
|
60
|
-
metadata: accountsControllerMetadata,
|
61
|
-
state: Object.assign(Object.assign({}, defaultState), state),
|
62
|
-
});
|
63
|
-
_AccountsController_instances.add(this);
|
64
|
-
this.messagingSystem.subscribe('SnapController:stateChange', (snapStateState) => __classPrivateFieldGet(this, _AccountsController_instances, "m", _AccountsController_handleOnSnapStateChange).call(this, snapStateState));
|
65
|
-
this.messagingSystem.subscribe('KeyringController:stateChange', (keyringState) => __classPrivateFieldGet(this, _AccountsController_instances, "m", _AccountsController_handleOnKeyringStateChange).call(this, keyringState));
|
66
|
-
__classPrivateFieldGet(this, _AccountsController_instances, "m", _AccountsController_registerMessageHandlers).call(this);
|
67
|
-
}
|
68
|
-
/**
|
69
|
-
* Returns the internal account object for the given account ID, if it exists.
|
70
|
-
*
|
71
|
-
* @param accountId - The ID of the account to retrieve.
|
72
|
-
* @returns The internal account object, or undefined if the account does not exist.
|
73
|
-
*/
|
74
|
-
getAccount(accountId) {
|
75
|
-
return this.state.internalAccounts.accounts[accountId];
|
76
|
-
}
|
77
|
-
/**
|
78
|
-
* Returns an array of all internal accounts.
|
79
|
-
*
|
80
|
-
* @returns An array of InternalAccount objects.
|
81
|
-
*/
|
82
|
-
listAccounts() {
|
83
|
-
return Object.values(this.state.internalAccounts.accounts);
|
84
|
-
}
|
85
|
-
/**
|
86
|
-
* Returns the internal account object for the given account ID.
|
87
|
-
*
|
88
|
-
* @param accountId - The ID of the account to retrieve.
|
89
|
-
* @returns The internal account object.
|
90
|
-
* @throws An error if the account ID is not found.
|
91
|
-
*/
|
92
|
-
getAccountExpect(accountId) {
|
93
|
-
// Edge case where the extension is setup but the srp is not yet created
|
94
|
-
// certain ui elements will query the selected address before any accounts are created.
|
95
|
-
if (!accountId) {
|
96
|
-
return {
|
97
|
-
id: '',
|
98
|
-
address: '',
|
99
|
-
options: {},
|
100
|
-
methods: [],
|
101
|
-
type: keyring_api_1.EthAccountType.Eoa,
|
102
|
-
metadata: {
|
103
|
-
name: '',
|
104
|
-
keyring: {
|
105
|
-
type: '',
|
106
|
-
},
|
107
|
-
},
|
108
|
-
};
|
109
|
-
}
|
110
|
-
const account = this.getAccount(accountId);
|
111
|
-
if (account === undefined) {
|
112
|
-
throw new Error(`Account Id ${accountId} not found`);
|
113
|
-
}
|
114
|
-
return account;
|
115
|
-
}
|
116
|
-
/**
|
117
|
-
* Returns the selected internal account.
|
118
|
-
*
|
119
|
-
* @returns The selected internal account.
|
120
|
-
*/
|
121
|
-
getSelectedAccount() {
|
122
|
-
return this.getAccountExpect(this.state.internalAccounts.selectedAccount);
|
123
|
-
}
|
124
|
-
/**
|
125
|
-
* Returns the account with the specified address.
|
126
|
-
* ! This method will only return the first account that matches the address
|
127
|
-
* @param address - The address of the account to retrieve.
|
128
|
-
* @returns The account with the specified address, or undefined if not found.
|
129
|
-
*/
|
130
|
-
getAccountByAddress(address) {
|
131
|
-
return this.listAccounts().find((account) => account.address.toLowerCase() === address.toLowerCase());
|
132
|
-
}
|
133
|
-
/**
|
134
|
-
* Sets the selected account by its ID.
|
135
|
-
*
|
136
|
-
* @param accountId - The ID of the account to be selected.
|
137
|
-
*/
|
138
|
-
setSelectedAccount(accountId) {
|
139
|
-
const account = this.getAccount(accountId);
|
140
|
-
this.update((currentState) => {
|
141
|
-
if (account) {
|
142
|
-
currentState.internalAccounts.accounts[account.id].metadata.lastSelected = Date.now();
|
143
|
-
currentState.internalAccounts.selectedAccount = account.id;
|
144
|
-
}
|
145
|
-
else {
|
146
|
-
currentState.internalAccounts.selectedAccount = '';
|
147
|
-
}
|
148
|
-
});
|
149
|
-
if (account) {
|
150
|
-
this.messagingSystem.publish('AccountsController:selectedAccountChange', account);
|
151
|
-
}
|
152
|
-
}
|
153
|
-
/**
|
154
|
-
* Sets the name of the account with the given ID.
|
155
|
-
*
|
156
|
-
* @param accountId - The ID of the account to set the name for.
|
157
|
-
* @param accountName - The new name for the account.
|
158
|
-
* @throws An error if an account with the same name already exists.
|
159
|
-
*/
|
160
|
-
setAccountName(accountId, accountName) {
|
161
|
-
const account = this.getAccountExpect(accountId);
|
162
|
-
if (this.listAccounts().find((internalAccount) => internalAccount.metadata.name === accountName &&
|
163
|
-
internalAccount.id !== accountId)) {
|
164
|
-
throw new Error('Account name already exists');
|
165
|
-
}
|
166
|
-
this.update((currentState) => {
|
167
|
-
const internalAccount = Object.assign(Object.assign({}, account), { metadata: Object.assign(Object.assign({}, account.metadata), { name: accountName }) });
|
168
|
-
currentState.internalAccounts.accounts[accountId] =
|
169
|
-
// @ts-expect-error Assigning a complex type `T` to `Draft<T>` causes an excessive type instantiation depth error.
|
170
|
-
internalAccount;
|
171
|
-
});
|
172
|
-
}
|
173
|
-
/**
|
174
|
-
* Updates the internal accounts list by retrieving normal and snap accounts,
|
175
|
-
* removing duplicates, and updating the metadata of each account.
|
176
|
-
*
|
177
|
-
* @returns A Promise that resolves when the accounts have been updated.
|
178
|
-
*/
|
179
|
-
updateAccounts() {
|
180
|
-
return __awaiter(this, void 0, void 0, function* () {
|
181
|
-
const snapAccounts = yield __classPrivateFieldGet(this, _AccountsController_instances, "m", _AccountsController_listSnapAccounts).call(this);
|
182
|
-
const normalAccounts = (yield __classPrivateFieldGet(this, _AccountsController_instances, "m", _AccountsController_listNormalAccounts).call(this)).filter((account) => !snapAccounts.find((snapAccount) => snapAccount.address === account.address));
|
183
|
-
// keyring type map.
|
184
|
-
const keyringTypes = new Map();
|
185
|
-
const previousAccounts = this.state.internalAccounts.accounts;
|
186
|
-
const accounts = [
|
187
|
-
...normalAccounts,
|
188
|
-
...snapAccounts,
|
189
|
-
].reduce((internalAccountMap, internalAccount) => {
|
190
|
-
var _a, _b;
|
191
|
-
const keyringTypeName = (0, utils_1.keyringTypeToName)(internalAccount.metadata.keyring.type);
|
192
|
-
const keyringAccountIndex = (_a = keyringTypes.get(keyringTypeName)) !== null && _a !== void 0 ? _a : 0;
|
193
|
-
if (keyringAccountIndex) {
|
194
|
-
keyringTypes.set(keyringTypeName, keyringAccountIndex + 1);
|
195
|
-
}
|
196
|
-
else {
|
197
|
-
keyringTypes.set(keyringTypeName, 1);
|
198
|
-
}
|
199
|
-
const existingAccount = previousAccounts[internalAccount.id];
|
200
|
-
internalAccountMap[internalAccount.id] = Object.assign(Object.assign({}, internalAccount), { metadata: Object.assign(Object.assign({}, internalAccount.metadata), { name: existingAccount && existingAccount.metadata.name !== ''
|
201
|
-
? existingAccount.metadata.name
|
202
|
-
: `${keyringTypeName} ${keyringAccountIndex + 1}`, lastSelected: (_b = existingAccount === null || existingAccount === void 0 ? void 0 : existingAccount.metadata) === null || _b === void 0 ? void 0 : _b.lastSelected }) });
|
203
|
-
return internalAccountMap;
|
204
|
-
}, {});
|
205
|
-
this.update((currentState) => {
|
206
|
-
currentState.internalAccounts.accounts =
|
207
|
-
accounts;
|
208
|
-
});
|
209
|
-
});
|
210
|
-
}
|
211
|
-
/**
|
212
|
-
* Loads the backup state of the accounts controller.
|
213
|
-
*
|
214
|
-
* @param backup - The backup state to load.
|
215
|
-
*/
|
216
|
-
loadBackup(backup) {
|
217
|
-
if (backup.internalAccounts) {
|
218
|
-
this.update((currentState) => {
|
219
|
-
currentState.internalAccounts =
|
220
|
-
backup.internalAccounts;
|
221
|
-
});
|
222
|
-
}
|
223
|
-
}
|
224
|
-
}
|
225
|
-
exports.AccountsController = AccountsController;
|
226
|
-
_AccountsController_instances = new WeakSet(), _AccountsController_generateInternalAccountForNonSnapAccount = function _AccountsController_generateInternalAccountForNonSnapAccount(address, type) {
|
227
|
-
return {
|
228
|
-
id: (0, utils_1.getUUIDFromAddressOfNormalAccount)(address),
|
229
|
-
address,
|
230
|
-
options: {},
|
231
|
-
methods: [
|
232
|
-
keyring_api_1.EthMethod.PersonalSign,
|
233
|
-
keyring_api_1.EthMethod.Sign,
|
234
|
-
keyring_api_1.EthMethod.SignTransaction,
|
235
|
-
keyring_api_1.EthMethod.SignTypedDataV1,
|
236
|
-
keyring_api_1.EthMethod.SignTypedDataV3,
|
237
|
-
keyring_api_1.EthMethod.SignTypedDataV4,
|
238
|
-
],
|
239
|
-
type: keyring_api_1.EthAccountType.Eoa,
|
240
|
-
metadata: {
|
241
|
-
name: '',
|
242
|
-
keyring: {
|
243
|
-
type,
|
244
|
-
},
|
245
|
-
},
|
246
|
-
};
|
247
|
-
}, _AccountsController_listSnapAccounts = function _AccountsController_listSnapAccounts() {
|
248
|
-
return __awaiter(this, void 0, void 0, function* () {
|
249
|
-
const [snapKeyring] = this.messagingSystem.call('KeyringController:getKeyringsByType', eth_snap_keyring_1.SnapKeyring.type);
|
250
|
-
// snap keyring is not available until the first account is created in the keyring controller
|
251
|
-
if (!snapKeyring) {
|
252
|
-
return [];
|
253
|
-
}
|
254
|
-
const snapAccounts = snapKeyring.listAccounts();
|
255
|
-
return snapAccounts;
|
256
|
-
});
|
257
|
-
}, _AccountsController_listNormalAccounts = function _AccountsController_listNormalAccounts() {
|
258
|
-
return __awaiter(this, void 0, void 0, function* () {
|
259
|
-
const addresses = yield this.messagingSystem.call('KeyringController:getAccounts');
|
260
|
-
const internalAccounts = [];
|
261
|
-
for (const address of addresses) {
|
262
|
-
const keyring = yield this.messagingSystem.call('KeyringController:getKeyringForAccount', address);
|
263
|
-
const v4options = {
|
264
|
-
random: (0, sha256_1.sha256)((0, util_1.toBuffer)(address)).slice(0, 16),
|
265
|
-
};
|
266
|
-
internalAccounts.push({
|
267
|
-
id: (0, uuid_1.v4)(v4options),
|
268
|
-
address,
|
269
|
-
options: {},
|
270
|
-
methods: [
|
271
|
-
keyring_api_1.EthMethod.PersonalSign,
|
272
|
-
keyring_api_1.EthMethod.Sign,
|
273
|
-
keyring_api_1.EthMethod.SignTransaction,
|
274
|
-
keyring_api_1.EthMethod.SignTypedDataV1,
|
275
|
-
keyring_api_1.EthMethod.SignTypedDataV3,
|
276
|
-
keyring_api_1.EthMethod.SignTypedDataV4,
|
277
|
-
],
|
278
|
-
type: keyring_api_1.EthAccountType.Eoa,
|
279
|
-
metadata: {
|
280
|
-
name: '',
|
281
|
-
keyring: {
|
282
|
-
type: keyring.type,
|
283
|
-
},
|
284
|
-
},
|
285
|
-
});
|
286
|
-
}
|
287
|
-
return internalAccounts.filter((account) => account.metadata.keyring.type !== keyring_controller_1.KeyringTypes.snap);
|
288
|
-
});
|
289
|
-
}, _AccountsController_handleOnKeyringStateChange = function _AccountsController_handleOnKeyringStateChange(keyringState) {
|
290
|
-
// check if there are any new accounts added
|
291
|
-
// TODO: change when accountAdded event is added to the keyring controller
|
292
|
-
// We check for keyrings length to be greater than 0 because the extension client may try execute
|
293
|
-
// submit password twice and clear the keyring state.
|
294
|
-
// https://github.com/MetaMask/KeyringController/blob/2d73a4deed8d013913f6ef0c9f5c0bb7c614f7d3/src/KeyringController.ts#L910
|
295
|
-
if (keyringState.isUnlocked && keyringState.keyrings.length > 0) {
|
296
|
-
const updatedNormalKeyringAddresses = [];
|
297
|
-
const updatedSnapKeyringAddresses = [];
|
298
|
-
for (const keyring of keyringState.keyrings) {
|
299
|
-
if (keyring.type === keyring_controller_1.KeyringTypes.snap) {
|
300
|
-
updatedSnapKeyringAddresses.push(...keyring.accounts.map((address) => {
|
301
|
-
return {
|
302
|
-
address,
|
303
|
-
type: keyring.type,
|
304
|
-
};
|
305
|
-
}));
|
306
|
-
}
|
307
|
-
else {
|
308
|
-
updatedNormalKeyringAddresses.push(...keyring.accounts.map((address) => {
|
309
|
-
return {
|
310
|
-
address,
|
311
|
-
type: keyring.type,
|
312
|
-
};
|
313
|
-
}));
|
314
|
-
}
|
315
|
-
}
|
316
|
-
const { previousNormalInternalAccounts, previousSnapInternalAccounts } = this.listAccounts().reduce((accumulator, account) => {
|
317
|
-
if (account.metadata.keyring.type === keyring_controller_1.KeyringTypes.snap) {
|
318
|
-
accumulator.previousSnapInternalAccounts.push(account);
|
319
|
-
}
|
320
|
-
else {
|
321
|
-
accumulator.previousNormalInternalAccounts.push(account);
|
322
|
-
}
|
323
|
-
return accumulator;
|
324
|
-
}, {
|
325
|
-
previousNormalInternalAccounts: [],
|
326
|
-
previousSnapInternalAccounts: [],
|
327
|
-
});
|
328
|
-
const addedAccounts = [];
|
329
|
-
const deletedAccounts = [];
|
330
|
-
// snap account ids are random uuid while normal accounts
|
331
|
-
// are determininistic based on the address
|
332
|
-
// ^NOTE: This will be removed when normal accounts also implement internal accounts
|
333
|
-
// finding all the normal accounts that were added
|
334
|
-
for (const account of updatedNormalKeyringAddresses) {
|
335
|
-
if (!this.state.internalAccounts.accounts[(0, utils_1.getUUIDFromAddressOfNormalAccount)(account.address)]) {
|
336
|
-
addedAccounts.push(account);
|
337
|
-
}
|
338
|
-
}
|
339
|
-
// finding all the snap accounts that were added
|
340
|
-
for (const account of updatedSnapKeyringAddresses) {
|
341
|
-
if (!previousSnapInternalAccounts.find((internalAccount) => internalAccount.address.toLowerCase() ===
|
342
|
-
account.address.toLowerCase())) {
|
343
|
-
addedAccounts.push(account);
|
344
|
-
}
|
345
|
-
}
|
346
|
-
// finding all the normal accounts that were deleted
|
347
|
-
for (const account of previousNormalInternalAccounts) {
|
348
|
-
if (!updatedNormalKeyringAddresses.find(({ address }) => address.toLowerCase() === account.address.toLowerCase())) {
|
349
|
-
deletedAccounts.push(account);
|
350
|
-
}
|
351
|
-
}
|
352
|
-
// finding all the snap accounts that were deleted
|
353
|
-
for (const account of previousSnapInternalAccounts) {
|
354
|
-
if (!updatedSnapKeyringAddresses.find(({ address }) => address.toLowerCase() === account.address.toLowerCase())) {
|
355
|
-
deletedAccounts.push(account);
|
356
|
-
}
|
357
|
-
}
|
358
|
-
if (deletedAccounts.length > 0) {
|
359
|
-
for (const account of deletedAccounts) {
|
360
|
-
__classPrivateFieldGet(this, _AccountsController_instances, "m", _AccountsController_handleAccountRemoved).call(this, account.id);
|
361
|
-
}
|
362
|
-
}
|
363
|
-
if (addedAccounts.length > 0) {
|
364
|
-
for (const account of addedAccounts) {
|
365
|
-
__classPrivateFieldGet(this, _AccountsController_instances, "m", _AccountsController_handleNewAccountAdded).call(this, account);
|
366
|
-
}
|
367
|
-
}
|
368
|
-
// handle if the selected account was deleted
|
369
|
-
if (!this.getAccount(this.state.internalAccounts.selectedAccount)) {
|
370
|
-
const [accountToSelect] = this.listAccounts().sort((accountA, accountB) => {
|
371
|
-
var _a, _b;
|
372
|
-
// sort by lastSelected descending
|
373
|
-
return (((_a = accountB.metadata.lastSelected) !== null && _a !== void 0 ? _a : 0) -
|
374
|
-
((_b = accountA.metadata.lastSelected) !== null && _b !== void 0 ? _b : 0));
|
375
|
-
});
|
376
|
-
// if the accountToSelect is undefined, then there are no accounts
|
377
|
-
// it mean the keyring was reinitialized.
|
378
|
-
this.setSelectedAccount(accountToSelect === null || accountToSelect === void 0 ? void 0 : accountToSelect.id);
|
379
|
-
}
|
380
|
-
}
|
381
|
-
}, _AccountsController_handleOnSnapStateChange = function _AccountsController_handleOnSnapStateChange(snapState) {
|
382
|
-
// only check if snaps changed in status
|
383
|
-
const { snaps } = snapState;
|
384
|
-
const accounts = this.listAccounts().filter((account) => account.metadata.snap);
|
385
|
-
this.update((currentState) => {
|
386
|
-
accounts.forEach((account) => {
|
387
|
-
const currentAccount = currentState.internalAccounts.accounts[account.id];
|
388
|
-
if (currentAccount.metadata.snap) {
|
389
|
-
const snapId = currentAccount.metadata.snap.id;
|
390
|
-
const storedSnap = snaps[snapId];
|
391
|
-
if (storedSnap) {
|
392
|
-
currentAccount.metadata.snap.enabled =
|
393
|
-
storedSnap.enabled && !storedSnap.blocked;
|
394
|
-
}
|
395
|
-
}
|
396
|
-
});
|
397
|
-
});
|
398
|
-
}, _AccountsController_getNextAccountNumber = function _AccountsController_getNextAccountNumber(keyringType) {
|
399
|
-
const keyringName = (0, utils_1.keyringTypeToName)(keyringType);
|
400
|
-
const previousKeyringAccounts = this.listAccounts().filter((internalAccount) => {
|
401
|
-
if (keyringType === keyring_controller_1.KeyringTypes.hd ||
|
402
|
-
keyringType === keyring_controller_1.KeyringTypes.simple) {
|
403
|
-
return (internalAccount.metadata.keyring.type === keyring_controller_1.KeyringTypes.hd ||
|
404
|
-
internalAccount.metadata.keyring.type === keyring_controller_1.KeyringTypes.simple);
|
405
|
-
}
|
406
|
-
return internalAccount.metadata.keyring.type === keyringType;
|
407
|
-
});
|
408
|
-
const lastDefaultIndexUsedForKeyringType = previousKeyringAccounts
|
409
|
-
.filter((internalAccount) => new RegExp(`${keyringName} \\d+$`, 'u').test(internalAccount.metadata.name))
|
410
|
-
.map((internalAccount) => {
|
411
|
-
const nameToWords = internalAccount.metadata.name.split(' '); // get the index of a default account name
|
412
|
-
return parseInt(nameToWords[nameToWords.length], 10);
|
413
|
-
})
|
414
|
-
.sort((a, b) => b - a)[0] || 0;
|
415
|
-
const indexToUse = Math.max(previousKeyringAccounts.length + 1, lastDefaultIndexUsedForKeyringType + 1);
|
416
|
-
return { accountPrefix: keyringName, indexToUse };
|
417
|
-
}, _AccountsController_handleNewAccountAdded = function _AccountsController_handleNewAccountAdded(account) {
|
418
|
-
let newAccount;
|
419
|
-
if (account.type !== keyring_controller_1.KeyringTypes.snap) {
|
420
|
-
newAccount = __classPrivateFieldGet(this, _AccountsController_instances, "m", _AccountsController_generateInternalAccountForNonSnapAccount).call(this, account.address, account.type);
|
421
|
-
}
|
422
|
-
else {
|
423
|
-
const [snapKeyring] = this.messagingSystem.call('KeyringController:getKeyringsByType', eth_snap_keyring_1.SnapKeyring.type);
|
424
|
-
newAccount = snapKeyring.getAccountByAddress(account.address);
|
425
|
-
// The snap deleted the account before the keyring controller could add it
|
426
|
-
if (!newAccount) {
|
427
|
-
return;
|
428
|
-
}
|
429
|
-
}
|
430
|
-
// get next index number for the keyring type
|
431
|
-
const { accountPrefix, indexToUse } = __classPrivateFieldGet(this, _AccountsController_instances, "m", _AccountsController_getNextAccountNumber).call(this, newAccount.metadata.keyring.type);
|
432
|
-
const accountName = `${accountPrefix} ${indexToUse}`;
|
433
|
-
this.update((currentState) => {
|
434
|
-
currentState.internalAccounts.accounts[newAccount.id] = Object.assign(Object.assign({}, newAccount), { metadata: Object.assign(Object.assign({}, newAccount.metadata), { name: accountName, lastSelected: Date.now() }) });
|
435
|
-
});
|
436
|
-
this.setSelectedAccount(newAccount.id);
|
437
|
-
}, _AccountsController_handleAccountRemoved = function _AccountsController_handleAccountRemoved(accountId) {
|
438
|
-
this.update((currentState) => {
|
439
|
-
delete currentState.internalAccounts.accounts[accountId];
|
440
|
-
});
|
441
|
-
}, _AccountsController_registerMessageHandlers = function _AccountsController_registerMessageHandlers() {
|
442
|
-
this.messagingSystem.registerActionHandler(`${controllerName}:setSelectedAccount`, this.setSelectedAccount.bind(this));
|
443
|
-
this.messagingSystem.registerActionHandler(`${controllerName}:listAccounts`, this.listAccounts.bind(this));
|
444
|
-
this.messagingSystem.registerActionHandler(`${controllerName}:setAccountName`, this.setAccountName.bind(this));
|
445
|
-
this.messagingSystem.registerActionHandler(`${controllerName}:updateAccounts`, this.updateAccounts.bind(this));
|
446
|
-
this.messagingSystem.registerActionHandler(`${controllerName}:getSelectedAccount`, this.getSelectedAccount.bind(this));
|
447
|
-
this.messagingSystem.registerActionHandler(`${controllerName}:getAccountByAddress`, this.getAccountByAddress.bind(this));
|
448
|
-
this.messagingSystem.registerActionHandler(`AccountsController:getAccount`, this.getAccount.bind(this));
|
449
|
-
};
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
2
|
+
|
3
|
+
var _chunk7FX4HSTVjs = require('./chunk-7FX4HSTV.js');
|
4
|
+
require('./chunk-MF4BFCSU.js');
|
5
|
+
|
6
|
+
|
7
|
+
exports.AccountsController = _chunk7FX4HSTVjs.AccountsController;
|
450
8
|
//# sourceMappingURL=AccountsController.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"AccountsController.js","sourceRoot":"","sources":["../src/AccountsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,2CAA4C;AAM5C,+DAA2D;AAC3D,iEAAyD;AAEzD,uDAAkE;AAClE,qEAA4D;AAe5D,yDAAsD;AAEtD,+BAAkC;AAElC,mCAA+E;AAE/E,MAAM,cAAc,GAAG,oBAAoB,CAAC;AA2F5C,MAAM,0BAA0B,GAAG;IACjC,gBAAgB,EAAE;QAChB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AAEF,MAAM,YAAY,GAA4B;IAC5C,gBAAgB,EAAE;QAChB,QAAQ,EAAE,EAAE;QACZ,eAAe,EAAE,EAAE;KACpB;CACF,CAAC;AAEF;;;;;;;GAOG;AACH,MAAa,kBAAmB,SAAQ,gCAIvC;IACC;;;;;;OAMG;IACH,YAAY,EACV,SAAS,EACT,KA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AAC,IAAI,CAAC,CACnC,CAAC;IAEF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,cAAc,eAAe,EAChC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAC7B,CAAC;IAEF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,cAAc,iBAAiB,EAClC,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAC/B,CAAC;IAEF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,cAAc,iBAAiB,EAClC,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAC/B,CAAC;IAEF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,cAAc,qBAAqB,EACtC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,CACnC,CAAC;IAEF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,cAAc,sBAAsB,EACvC,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,CACpC,CAAC;IAEF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,+BAA+B,EAC/B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAC3B,CAAC;AACJ,CAAC","sourcesContent":["import { toBuffer } from '@ethereumjs/util';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { SnapKeyring } from '@metamask/eth-snap-keyring';\nimport type { InternalAccount } from '@metamask/keyring-api';\nimport { EthAccountType, EthMethod } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type {\n KeyringControllerState,\n KeyringControllerEvents,\n KeyringControllerGetKeyringForAccountAction,\n KeyringControllerGetKeyringsByTypeAction,\n KeyringControllerGetAccountsAction,\n} from '@metamask/keyring-controller';\nimport type {\n SnapControllerEvents,\n SnapControllerState,\n} from '@metamask/snaps-controllers';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type { Snap } from '@metamask/snaps-utils';\nimport type { Keyring, Json } from '@metamask/utils';\nimport { sha256 } from 'ethereum-cryptography/sha256';\nimport type { Draft } from 'immer';\nimport { v4 as uuid } from 'uuid';\n\nimport { getUUIDFromAddressOfNormalAccount, keyringTypeToName } from './utils';\n\nconst controllerName = 'AccountsController';\n\nexport type AccountsControllerState = {\n internalAccounts: {\n accounts: Record<string, InternalAccount>;\n selectedAccount: string; // id of the selected account\n };\n};\n\nexport type AccountsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AccountsControllerState\n>;\n\nexport type AccountsControllerSetSelectedAccountAction = {\n type: `${typeof controllerName}:setSelectedAccount`;\n handler: AccountsController['setSelectedAccount'];\n};\n\nexport type AccountsControllerSetAccountNameAction = {\n type: `${typeof controllerName}:setAccountName`;\n handler: AccountsController['setAccountName'];\n};\n\nexport type AccountsControllerListAccountsAction = {\n type: `${typeof controllerName}:listAccounts`;\n handler: AccountsController['listAccounts'];\n};\n\nexport type AccountsControllerUpdateAccountsAction = {\n type: `${typeof controllerName}:updateAccounts`;\n handler: AccountsController['updateAccounts'];\n};\n\nexport type AccountsControllerGetSelectedAccountAction = {\n type: `${typeof controllerName}:getSelectedAccount`;\n handler: AccountsController['getSelectedAccount'];\n};\n\nexport type AccountsControllerGetAccountByAddressAction = {\n type: `${typeof controllerName}:getAccountByAddress`;\n handler: AccountsController['getAccountByAddress'];\n};\n\nexport type AccountsControllerGetAccountAction = {\n type: `${typeof controllerName}:getAccount`;\n handler: AccountsController['getAccount'];\n};\n\nexport type AccountsControllerActions =\n | AccountsControllerGetStateAction\n | AccountsControllerSetSelectedAccountAction\n | AccountsControllerListAccountsAction\n | AccountsControllerSetAccountNameAction\n | AccountsControllerUpdateAccountsAction\n | AccountsControllerGetAccountByAddressAction\n | AccountsControllerGetSelectedAccountAction\n | AccountsControllerGetAccountAction\n | KeyringControllerGetKeyringForAccountAction\n | KeyringControllerGetKeyringsByTypeAction\n | KeyringControllerGetAccountsAction;\n\nexport type AccountsControllerChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n AccountsControllerState\n>;\n\nexport type AccountsControllerSelectedAccountChangeEvent = {\n type: `${typeof controllerName}:selectedAccountChange`;\n payload: [InternalAccount];\n};\n\nexport type AccountsControllerEvents =\n | AccountsControllerChangeEvent\n | AccountsControllerSelectedAccountChangeEvent\n | SnapControllerEvents\n | KeyringControllerEvents;\n\nexport type AccountsControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AccountsControllerActions,\n AccountsControllerEvents,\n string,\n string\n>;\n\ntype AddressAndKeyringTypeObject = {\n address: string;\n type: string;\n};\n\nconst accountsControllerMetadata = {\n internalAccounts: {\n persist: true,\n anonymous: false,\n },\n};\n\nconst defaultState: AccountsControllerState = {\n internalAccounts: {\n accounts: {},\n selectedAccount: '',\n },\n};\n\n/**\n * Controller that manages internal accounts.\n * The accounts controller is responsible for creating and managing internal accounts.\n * It also provides convenience methods for accessing and updating the internal accounts.\n * The accounts controller also listens for keyring state changes and updates the internal accounts accordingly.\n * The accounts controller also listens for snap state changes and updates the internal accounts accordingly.\n *\n */\nexport class AccountsController extends BaseController<\n typeof controllerName,\n AccountsControllerState,\n AccountsControllerMessenger\n> {\n /**\n * Constructor for AccountsController.\n *\n * @param options - The controller options.\n * @param options.messenger - The messenger object.\n * @param options.state - Initial state to set on this controller\n */\n constructor({\n messenger,\n state,\n }: {\n messenger: AccountsControllerMessenger;\n state: AccountsControllerState;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: accountsControllerMetadata,\n state: {\n ...defaultState,\n ...state,\n },\n });\n\n this.messagingSystem.subscribe(\n 'SnapController:stateChange',\n (snapStateState) => this.#handleOnSnapStateChange(snapStateState),\n );\n\n this.messagingSystem.subscribe(\n 'KeyringController:stateChange',\n (keyringState) => this.#handleOnKeyringStateChange(keyringState),\n );\n\n this.#registerMessageHandlers();\n }\n\n /**\n * Returns the internal account object for the given account ID, if it exists.\n *\n * @param accountId - The ID of the account to retrieve.\n * @returns The internal account object, or undefined if the account does not exist.\n */\n getAccount(accountId: string): InternalAccount | undefined {\n return this.state.internalAccounts.accounts[accountId];\n }\n\n /**\n * Returns an array of all internal accounts.\n *\n * @returns An array of InternalAccount objects.\n */\n listAccounts(): InternalAccount[] {\n return Object.values(this.state.internalAccounts.accounts);\n }\n\n /**\n * Returns the internal account object for the given account ID.\n *\n * @param accountId - The ID of the account to retrieve.\n * @returns The internal account object.\n * @throws An error if the account ID is not found.\n */\n getAccountExpect(accountId: string): InternalAccount {\n // Edge case where the extension is setup but the srp is not yet created\n // certain ui elements will query the selected address before any accounts are created.\n if (!accountId) {\n return {\n id: '',\n address: '',\n options: {},\n methods: [],\n type: EthAccountType.Eoa,\n metadata: {\n name: '',\n keyring: {\n type: '',\n },\n },\n };\n }\n\n const account = this.getAccount(accountId);\n if (account === undefined) {\n throw new Error(`Account Id ${accountId} not found`);\n }\n return account;\n }\n\n /**\n * Returns the selected internal account.\n *\n * @returns The selected internal account.\n */\n getSelectedAccount(): InternalAccount {\n return this.getAccountExpect(this.state.internalAccounts.selectedAccount);\n }\n\n /**\n * Returns the account with the specified address.\n * ! This method will only return the first account that matches the address\n * @param address - The address of the account to retrieve.\n * @returns The account with the specified address, or undefined if not found.\n */\n getAccountByAddress(address: string): InternalAccount | undefined {\n return this.listAccounts().find(\n (account) => account.address.toLowerCase() === address.toLowerCase(),\n );\n }\n\n /**\n * Sets the selected account by its ID.\n *\n * @param accountId - The ID of the account to be selected.\n */\n setSelectedAccount(accountId: string): void {\n const account = this.getAccount(accountId);\n\n this.update((currentState: Draft<AccountsControllerState>) => {\n if (account) {\n currentState.internalAccounts.accounts[\n account.id\n ].metadata.lastSelected = Date.now();\n currentState.internalAccounts.selectedAccount = account.id;\n } else {\n currentState.internalAccounts.selectedAccount = '';\n }\n });\n\n if (account) {\n this.messagingSystem.publish(\n 'AccountsController:selectedAccountChange',\n account,\n );\n }\n }\n\n /**\n * Sets the name of the account with the given ID.\n *\n * @param accountId - The ID of the account to set the name for.\n * @param accountName - The new name for the account.\n * @throws An error if an account with the same name already exists.\n */\n setAccountName(accountId: string, accountName: string): void {\n const account = this.getAccountExpect(accountId);\n\n if (\n this.listAccounts().find(\n (internalAccount) =>\n internalAccount.metadata.name === accountName &&\n internalAccount.id !== accountId,\n )\n ) {\n throw new Error('Account name already exists');\n }\n\n this.update((currentState: Draft<AccountsControllerState>) => {\n const internalAccount = {\n ...account,\n metadata: { ...account.metadata, name: accountName },\n };\n currentState.internalAccounts.accounts[accountId] =\n // @ts-expect-error Assigning a complex type `T` to `Draft<T>` causes an excessive type instantiation depth error.\n internalAccount as Draft<InternalAccount>;\n });\n }\n\n /**\n * Updates the internal accounts list by retrieving normal and snap accounts,\n * removing duplicates, and updating the metadata of each account.\n *\n * @returns A Promise that resolves when the accounts have been updated.\n */\n async updateAccounts(): Promise<void> {\n const snapAccounts: InternalAccount[] = await this.#listSnapAccounts();\n const normalAccounts = (await this.#listNormalAccounts()).filter(\n (account) =>\n !snapAccounts.find(\n (snapAccount) => snapAccount.address === account.address,\n ),\n );\n\n // keyring type map.\n const keyringTypes = new Map<string, number>();\n const previousAccounts = this.state.internalAccounts.accounts;\n\n const accounts: Record<string, InternalAccount> = [\n ...normalAccounts,\n ...snapAccounts,\n ].reduce((internalAccountMap, internalAccount) => {\n const keyringTypeName = keyringTypeToName(\n internalAccount.metadata.keyring.type,\n );\n const keyringAccountIndex = keyringTypes.get(keyringTypeName) ?? 0;\n if (keyringAccountIndex) {\n keyringTypes.set(keyringTypeName, keyringAccountIndex + 1);\n } else {\n keyringTypes.set(keyringTypeName, 1);\n }\n\n const existingAccount = previousAccounts[internalAccount.id];\n\n internalAccountMap[internalAccount.id] = {\n ...internalAccount,\n\n metadata: {\n ...internalAccount.metadata,\n name:\n existingAccount && existingAccount.metadata.name !== ''\n ? existingAccount.metadata.name\n : `${keyringTypeName} ${keyringAccountIndex + 1}`,\n lastSelected: existingAccount?.metadata?.lastSelected,\n },\n };\n\n return internalAccountMap;\n }, {} as Record<string, InternalAccount>);\n\n this.update((currentState: Draft<AccountsControllerState>) => {\n (currentState as AccountsControllerState).internalAccounts.accounts =\n accounts;\n });\n }\n\n /**\n * Loads the backup state of the accounts controller.\n *\n * @param backup - The backup state to load.\n */\n loadBackup(backup: AccountsControllerState): void {\n if (backup.internalAccounts) {\n this.update((currentState: Draft<AccountsControllerState>) => {\n (currentState as AccountsControllerState).internalAccounts =\n backup.internalAccounts;\n });\n }\n }\n\n /**\n * Generates an internal account for a non-Snap account.\n * @param address - The address of the account.\n * @param type - The type of the account.\n * @returns The generated internal account.\n */\n #generateInternalAccountForNonSnapAccount(\n address: string,\n type: string,\n ): InternalAccount {\n return {\n id: getUUIDFromAddressOfNormalAccount(address),\n address,\n options: {},\n methods: [\n EthMethod.PersonalSign,\n EthMethod.Sign,\n EthMethod.SignTransaction,\n EthMethod.SignTypedDataV1,\n EthMethod.SignTypedDataV3,\n EthMethod.SignTypedDataV4,\n ],\n type: EthAccountType.Eoa,\n metadata: {\n name: '',\n keyring: {\n type,\n },\n },\n };\n }\n\n /**\n * Returns a list of internal accounts created using the SnapKeyring.\n *\n * @returns A promise that resolves to an array of InternalAccount objects.\n */\n async #listSnapAccounts(): Promise<InternalAccount[]> {\n const [snapKeyring] = this.messagingSystem.call(\n 'KeyringController:getKeyringsByType',\n SnapKeyring.type,\n );\n // snap keyring is not available until the first account is created in the keyring controller\n if (!snapKeyring) {\n return [];\n }\n\n const snapAccounts = (snapKeyring as SnapKeyring).listAccounts();\n\n return snapAccounts;\n }\n\n /**\n * Returns a list of normal accounts.\n * Note: listNormalAccounts is a temporary method until the keyrings all implement the InternalAccount interface.\n * Once all keyrings implement the InternalAccount interface, this method can be removed and getAccounts can be used instead.\n *\n * @returns A Promise that resolves to an array of InternalAccount objects.\n */\n async #listNormalAccounts(): Promise<InternalAccount[]> {\n const addresses = await this.messagingSystem.call(\n 'KeyringController:getAccounts',\n );\n const internalAccounts: InternalAccount[] = [];\n for (const address of addresses) {\n const keyring = await this.messagingSystem.call(\n 'KeyringController:getKeyringForAccount',\n address,\n );\n const v4options = {\n random: sha256(toBuffer(address)).slice(0, 16),\n };\n\n internalAccounts.push({\n id: uuid(v4options),\n address,\n options: {},\n methods: [\n EthMethod.PersonalSign,\n EthMethod.Sign,\n EthMethod.SignTransaction,\n EthMethod.SignTypedDataV1,\n EthMethod.SignTypedDataV3,\n EthMethod.SignTypedDataV4,\n ],\n type: EthAccountType.Eoa,\n metadata: {\n name: '',\n keyring: {\n type: (keyring as Keyring<Json>).type,\n },\n },\n });\n }\n\n return internalAccounts.filter(\n (account) => account.metadata.keyring.type !== KeyringTypes.snap,\n );\n }\n\n /**\n * Handles changes in the keyring state, specifically when new accounts are added or removed.\n *\n * @param keyringState - The new state of the keyring controller.\n */\n #handleOnKeyringStateChange(keyringState: KeyringControllerState): void {\n // check if there are any new accounts added\n // TODO: change when accountAdded event is added to the keyring controller\n\n // We check for keyrings length to be greater than 0 because the extension client may try execute\n // submit password twice and clear the keyring state.\n // https://github.com/MetaMask/KeyringController/blob/2d73a4deed8d013913f6ef0c9f5c0bb7c614f7d3/src/KeyringController.ts#L910\n if (keyringState.isUnlocked && keyringState.keyrings.length > 0) {\n const updatedNormalKeyringAddresses: AddressAndKeyringTypeObject[] = [];\n const updatedSnapKeyringAddresses: AddressAndKeyringTypeObject[] = [];\n\n for (const keyring of keyringState.keyrings) {\n if (keyring.type === KeyringTypes.snap) {\n updatedSnapKeyringAddresses.push(\n ...keyring.accounts.map((address) => {\n return {\n address,\n type: keyring.type,\n };\n }),\n );\n } else {\n updatedNormalKeyringAddresses.push(\n ...keyring.accounts.map((address) => {\n return {\n address,\n type: keyring.type,\n };\n }),\n );\n }\n }\n\n const { previousNormalInternalAccounts, previousSnapInternalAccounts } =\n this.listAccounts().reduce(\n (accumulator, account) => {\n if (account.metadata.keyring.type === KeyringTypes.snap) {\n accumulator.previousSnapInternalAccounts.push(account);\n } else {\n accumulator.previousNormalInternalAccounts.push(account);\n }\n return accumulator;\n },\n {\n previousNormalInternalAccounts: [] as InternalAccount[],\n previousSnapInternalAccounts: [] as InternalAccount[],\n },\n );\n\n const addedAccounts: AddressAndKeyringTypeObject[] = [];\n const deletedAccounts: InternalAccount[] = [];\n\n // snap account ids are random uuid while normal accounts\n // are determininistic based on the address\n\n // ^NOTE: This will be removed when normal accounts also implement internal accounts\n // finding all the normal accounts that were added\n for (const account of updatedNormalKeyringAddresses) {\n if (\n !this.state.internalAccounts.accounts[\n getUUIDFromAddressOfNormalAccount(account.address)\n ]\n ) {\n addedAccounts.push(account);\n }\n }\n\n // finding all the snap accounts that were added\n for (const account of updatedSnapKeyringAddresses) {\n if (\n !previousSnapInternalAccounts.find(\n (internalAccount) =>\n internalAccount.address.toLowerCase() ===\n account.address.toLowerCase(),\n )\n ) {\n addedAccounts.push(account);\n }\n }\n\n // finding all the normal accounts that were deleted\n for (const account of previousNormalInternalAccounts) {\n if (\n !updatedNormalKeyringAddresses.find(\n ({ address }) =>\n address.toLowerCase() === account.address.toLowerCase(),\n )\n ) {\n deletedAccounts.push(account);\n }\n }\n\n // finding all the snap accounts that were deleted\n for (const account of previousSnapInternalAccounts) {\n if (\n !updatedSnapKeyringAddresses.find(\n ({ address }) =>\n address.toLowerCase() === account.address.toLowerCase(),\n )\n ) {\n deletedAccounts.push(account);\n }\n }\n\n if (deletedAccounts.length > 0) {\n for (const account of deletedAccounts) {\n this.#handleAccountRemoved(account.id);\n }\n }\n\n if (addedAccounts.length > 0) {\n for (const account of addedAccounts) {\n this.#handleNewAccountAdded(account);\n }\n }\n\n // handle if the selected account was deleted\n if (!this.getAccount(this.state.internalAccounts.selectedAccount)) {\n const [accountToSelect] = this.listAccounts().sort(\n (accountA, accountB) => {\n // sort by lastSelected descending\n return (\n (accountB.metadata.lastSelected ?? 0) -\n (accountA.metadata.lastSelected ?? 0)\n );\n },\n );\n\n // if the accountToSelect is undefined, then there are no accounts\n // it mean the keyring was reinitialized.\n this.setSelectedAccount(accountToSelect?.id);\n }\n }\n }\n\n /**\n * Handles the change in SnapControllerState by updating the metadata of accounts that have a snap enabled.\n *\n * @param snapState - The new SnapControllerState.\n */\n #handleOnSnapStateChange(snapState: SnapControllerState) {\n // only check if snaps changed in status\n const { snaps } = snapState;\n const accounts = this.listAccounts().filter(\n (account) => account.metadata.snap,\n );\n\n this.update((currentState: Draft<AccountsControllerState>) => {\n accounts.forEach((account) => {\n const currentAccount =\n currentState.internalAccounts.accounts[account.id];\n if (currentAccount.metadata.snap) {\n const snapId = currentAccount.metadata.snap.id;\n const storedSnap: Snap = snaps[snapId as SnapId];\n if (storedSnap) {\n currentAccount.metadata.snap.enabled =\n storedSnap.enabled && !storedSnap.blocked;\n }\n }\n });\n });\n }\n\n /**\n * Returns the next account number for a given keyring type.\n * @param keyringType - The type of keyring.\n * @returns An object containing the account prefix and index to use.\n */\n #getNextAccountNumber(keyringType: string): {\n accountPrefix: string;\n indexToUse: number;\n } {\n const keyringName = keyringTypeToName(keyringType);\n const previousKeyringAccounts = this.listAccounts().filter(\n (internalAccount) => {\n if (\n keyringType === KeyringTypes.hd ||\n keyringType === KeyringTypes.simple\n ) {\n return (\n internalAccount.metadata.keyring.type === KeyringTypes.hd ||\n internalAccount.metadata.keyring.type === KeyringTypes.simple\n );\n }\n return internalAccount.metadata.keyring.type === keyringType;\n },\n );\n const lastDefaultIndexUsedForKeyringType =\n previousKeyringAccounts\n .filter((internalAccount) =>\n new RegExp(`${keyringName} \\\\d+$`, 'u').test(\n internalAccount.metadata.name,\n ),\n )\n .map((internalAccount) => {\n const nameToWords = internalAccount.metadata.name.split(' '); // get the index of a default account name\n return parseInt(nameToWords[nameToWords.length], 10);\n })\n .sort((a, b) => b - a)[0] || 0;\n\n const indexToUse = Math.max(\n previousKeyringAccounts.length + 1,\n lastDefaultIndexUsedForKeyringType + 1,\n );\n\n return { accountPrefix: keyringName, indexToUse };\n }\n\n /**\n * Handles the addition of a new account to the controller.\n * If the account is not a Snap Keyring account, generates an internal account for it and adds it to the controller.\n * If the account is a Snap Keyring account, retrieves the account from the keyring and adds it to the controller.\n * @param account - The address and keyring type object of the new account.\n */\n #handleNewAccountAdded(account: AddressAndKeyringTypeObject) {\n let newAccount: InternalAccount;\n if (account.type !== KeyringTypes.snap) {\n newAccount = this.#generateInternalAccountForNonSnapAccount(\n account.address,\n account.type,\n );\n } else {\n const [snapKeyring] = this.messagingSystem.call(\n 'KeyringController:getKeyringsByType',\n SnapKeyring.type,\n );\n\n newAccount = (snapKeyring as SnapKeyring).getAccountByAddress(\n account.address,\n ) as InternalAccount;\n\n // The snap deleted the account before the keyring controller could add it\n if (!newAccount) {\n return;\n }\n }\n\n // get next index number for the keyring type\n const { accountPrefix, indexToUse } = this.#getNextAccountNumber(\n newAccount.metadata.keyring.type,\n );\n\n const accountName = `${accountPrefix} ${indexToUse}`;\n\n this.update((currentState: Draft<AccountsControllerState>) => {\n (currentState as AccountsControllerState).internalAccounts.accounts[\n newAccount.id\n ] = {\n ...newAccount,\n metadata: {\n ...newAccount.metadata,\n name: accountName,\n lastSelected: Date.now(),\n },\n };\n });\n\n this.setSelectedAccount(newAccount.id);\n }\n\n /**\n * Handles the removal of an account from the internal accounts list.\n * @param accountId - The ID of the account to be removed.\n */\n #handleAccountRemoved(accountId: string) {\n this.update((currentState: Draft<AccountsControllerState>) => {\n delete currentState.internalAccounts.accounts[accountId];\n });\n }\n\n /**\n * Registers message handlers for the AccountsController.\n * @private\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:setSelectedAccount`,\n this.setSelectedAccount.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:listAccounts`,\n this.listAccounts.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:setAccountName`,\n this.setAccountName.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateAccounts`,\n this.updateAccounts.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getSelectedAccount`,\n this.getSelectedAccount.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getAccountByAddress`,\n this.getAccountByAddress.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `AccountsController:getAccount`,\n this.getAccount.bind(this),\n );\n }\n}\n"]}
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":""}
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|