@metamask-previews/multichain-account-service 0.8.0-preview-e85a6854 → 0.8.0-preview-c8856e2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/MultichainAccountService.cjs +35 -0
- package/dist/MultichainAccountService.cjs.map +1 -1
- package/dist/MultichainAccountService.d.cts +14 -0
- package/dist/MultichainAccountService.d.cts.map +1 -1
- package/dist/MultichainAccountService.d.mts +14 -0
- package/dist/MultichainAccountService.d.mts.map +1 -1
- package/dist/MultichainAccountService.mjs +35 -0
- package/dist/MultichainAccountService.mjs.map +1 -1
- package/dist/providers/EvmAccountProvider.cjs +60 -6
- package/dist/providers/EvmAccountProvider.cjs.map +1 -1
- package/dist/providers/EvmAccountProvider.d.cts.map +1 -1
- package/dist/providers/EvmAccountProvider.d.mts.map +1 -1
- package/dist/providers/EvmAccountProvider.mjs +60 -6
- package/dist/providers/EvmAccountProvider.mjs.map +1 -1
- package/dist/tests/accounts.cjs +2 -1
- package/dist/tests/accounts.cjs.map +1 -1
- package/dist/tests/accounts.d.cts +1 -0
- package/dist/tests/accounts.d.cts.map +1 -1
- package/dist/tests/accounts.d.mts +1 -0
- package/dist/tests/accounts.d.mts.map +1 -1
- package/dist/tests/accounts.mjs +1 -0
- package/dist/tests/accounts.mjs.map +1 -1
- package/dist/tests/messenger.cjs +2 -0
- package/dist/tests/messenger.cjs.map +1 -1
- package/dist/tests/messenger.d.cts.map +1 -1
- package/dist/tests/messenger.d.mts.map +1 -1
- package/dist/tests/messenger.mjs +2 -0
- package/dist/tests/messenger.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +7 -3
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +7 -3
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/package.json +4 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,11 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Add `createMultichainAccountWallet` method to create a new multichain account wallet from a mnemonic ([#6478](https://github.com/MetaMask/core/pull/6478))
|
|
13
|
+
- An action handler was also registered for this method so that it can be called from the clients.
|
|
14
|
+
- **BREAKING** Add additional allowed actions to the `MultichainAccountService` messenger
|
|
15
|
+
- `KeyringController:getKeyringsByType` and `KeyringController:addNewKeyring` actions were added.
|
|
16
|
+
|
|
10
17
|
### Changed
|
|
11
18
|
|
|
12
19
|
- **BREAKING:** Rename `MultichainAccountWallet.alignGroup` to `alignAccountsOf` ([#6595](https://github.com/MetaMask/core/pull/6595))
|
|
13
20
|
- **BREAKING:** Rename `MultichainAccountGroup.align` to `alignAccounts` ([#6595](https://github.com/MetaMask/core/pull/6595))
|
|
14
21
|
- Bump `@metamask/utils` from `^11.4.2` to `^11.8.0` ([#6588](https://github.com/MetaMask/core/pull/6588))
|
|
22
|
+
- Add timeout & retry mechanism to EVM discovery ([#6609](https://github.com/MetaMask/core/pull/6609)), ([#6621](https://github.com/MetaMask/core/pull/6621))
|
|
23
|
+
- Bump `@metamask/base-controller` from `^8.3.0` to `^8.4.0` ([#6632](https://github.com/MetaMask/core/pull/6632))
|
|
15
24
|
|
|
16
25
|
## [0.8.0]
|
|
17
26
|
|
|
@@ -14,7 +14,9 @@ var _MultichainAccountService_instances, _MultichainAccountService_messenger, _M
|
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.MultichainAccountService = exports.serviceName = void 0;
|
|
16
16
|
const account_api_1 = require("@metamask/account-api");
|
|
17
|
+
const key_tree_1 = require("@metamask/key-tree");
|
|
17
18
|
const keyring_controller_1 = require("@metamask/keyring-controller");
|
|
19
|
+
const utils_1 = require("@metamask/utils");
|
|
18
20
|
const MultichainAccountWallet_1 = require("./MultichainAccountWallet.cjs");
|
|
19
21
|
const AccountProviderWrapper_1 = require("./providers/AccountProviderWrapper.cjs");
|
|
20
22
|
const EvmAccountProvider_1 = require("./providers/EvmAccountProvider.cjs");
|
|
@@ -62,6 +64,7 @@ class MultichainAccountService {
|
|
|
62
64
|
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").registerActionHandler('MultichainAccountService:setBasicFunctionality', (...args) => this.setBasicFunctionality(...args));
|
|
63
65
|
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").registerActionHandler('MultichainAccountService:alignWallets', (...args) => this.alignWallets(...args));
|
|
64
66
|
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").registerActionHandler('MultichainAccountService:alignWallet', (...args) => this.alignWallet(...args));
|
|
67
|
+
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").registerActionHandler('MultichainAccountService:createMultichainAccountWallet', (...args) => this.createMultichainAccountWallet(...args));
|
|
65
68
|
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").subscribe('AccountsController:accountAdded', (account) => __classPrivateFieldGet(this, _MultichainAccountService_instances, "m", _MultichainAccountService_handleOnAccountAdded).call(this, account));
|
|
66
69
|
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").subscribe('AccountsController:accountRemoved', (id) => __classPrivateFieldGet(this, _MultichainAccountService_instances, "m", _MultichainAccountService_handleOnAccountRemoved).call(this, id));
|
|
67
70
|
}
|
|
@@ -127,6 +130,38 @@ class MultichainAccountService {
|
|
|
127
130
|
getMultichainAccountWallets() {
|
|
128
131
|
return Array.from(__classPrivateFieldGet(this, _MultichainAccountService_wallets, "f").values());
|
|
129
132
|
}
|
|
133
|
+
/**
|
|
134
|
+
* Creates a new multichain account wallet with the given mnemonic.
|
|
135
|
+
*
|
|
136
|
+
* NOTE: This method should only be called in client code where a mutex lock is acquired.
|
|
137
|
+
* `discoverAndCreateAccounts` should be called after this method to discover and create accounts.
|
|
138
|
+
*
|
|
139
|
+
* @param options - Options.
|
|
140
|
+
* @param options.mnemonic - The mnemonic to use to create the new wallet.
|
|
141
|
+
* @throws If the mnemonic has already been imported.
|
|
142
|
+
* @returns The new multichain account wallet.
|
|
143
|
+
*/
|
|
144
|
+
async createMultichainAccountWallet({ mnemonic, }) {
|
|
145
|
+
const existingKeyrings = __classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").call('KeyringController:getKeyringsByType', keyring_controller_1.KeyringTypes.hd);
|
|
146
|
+
const mnemonicAsBytes = (0, key_tree_1.mnemonicPhraseToBytes)(mnemonic);
|
|
147
|
+
const alreadyHasImportedSrp = existingKeyrings.some((keyring) => {
|
|
148
|
+
if (!keyring.mnemonic) {
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
return (0, utils_1.areUint8ArraysEqual)(keyring.mnemonic, mnemonicAsBytes);
|
|
152
|
+
});
|
|
153
|
+
if (alreadyHasImportedSrp) {
|
|
154
|
+
throw new Error('This Secret Recovery Phrase has already been imported.');
|
|
155
|
+
}
|
|
156
|
+
const result = await __classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").call('KeyringController:addNewKeyring', keyring_controller_1.KeyringTypes.hd, { mnemonic });
|
|
157
|
+
const wallet = new MultichainAccountWallet_1.MultichainAccountWallet({
|
|
158
|
+
providers: __classPrivateFieldGet(this, _MultichainAccountService_providers, "f"),
|
|
159
|
+
entropySource: result.id,
|
|
160
|
+
messenger: __classPrivateFieldGet(this, _MultichainAccountService_messenger, "f"),
|
|
161
|
+
});
|
|
162
|
+
__classPrivateFieldGet(this, _MultichainAccountService_wallets, "f").set(wallet.id, wallet);
|
|
163
|
+
return wallet;
|
|
164
|
+
}
|
|
130
165
|
/**
|
|
131
166
|
* Gets a reference to the multichain account group matching this entropy source
|
|
132
167
|
* and a group index.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultichainAccountService.cjs","sourceRoot":"","sources":["../src/MultichainAccountService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,uDAG+B;AAM/B,qEAA4D;A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OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,CACnC,CAAC;IACF,IAAI,CAAC,KAAK,EAAE;QACV,oEAAoE;QACpE,wCAAwC;QACxC,IAAI,IAAI,EAAE;YACR,MAAM,CAAC,IAAI,EAAE,CAAC;SACf;QAED,KAAK,GAAG,MAAM,CAAC,yBAAyB,CACtC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,CACnC,CAAC;QAEF,uEAAuE;QACvE,IAAI,GAAG,KAAK,CAAC;KACd;IAED,yEAAyE;IACzE,6EAA6E;IAC7E,IAAI,KAAK,EAAE;QACT,IAAI,IAAI,EAAE;YACR,KAAK,CAAC,IAAI,EAAE,CAAC;SACd;QAED,mEAAmE;QACnE,sBAAsB;QACtB,uBAAA,IAAI,oDAAoB,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,EAAE;YACvC,MAAM;YACN,KAAK;SACN,CAAC,CAAC;KACJ;AACH,CAAC,+GAEuB,EAAwB;IAC9C,kEAAkE;IAClE,MAAM,KAAK,GAAG,uBAAA,IAAI,oDAAoB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAC/C,IAAI,KAAK,EAAE;QACT,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;QAEzB,MAAM,CAAC,IAAI,EAAE,CAAC;KACf;IAED,6EAA6E;IAC7E,uBAAA,IAAI,oDAAoB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AACtC,CAAC,qFAGC,aAA8B;IAE9B,MAAM,MAAM,GAAG,uBAAA,IAAI,yCAAS,CAAC,GAAG,CAC9B,IAAA,yCAA2B,EAAC,aAAa,CAAC,CAC3C,CAAC;IAEF,IAAI,CAAC,MAAM,EAAE;QACX,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;KAC3E;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n isBip44Account,\n toMultichainAccountWalletId,\n} from '@metamask/account-api';\nimport type {\n MultichainAccountWalletId,\n Bip44Account,\n} from '@metamask/account-api';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\n\nimport type { MultichainAccountGroup } from './MultichainAccountGroup';\nimport { MultichainAccountWallet } from './MultichainAccountWallet';\nimport type { NamedAccountProvider } from './providers';\nimport {\n AccountProviderWrapper,\n isAccountProviderWrapper,\n} from './providers/AccountProviderWrapper';\nimport { EvmAccountProvider } from './providers/EvmAccountProvider';\nimport { SolAccountProvider } from './providers/SolAccountProvider';\nimport type { MultichainAccountServiceMessenger } from './types';\n\nexport const serviceName = 'MultichainAccountService';\n\n/**\n * The options that {@link MultichainAccountService} takes.\n */\ntype MultichainAccountServiceOptions = {\n messenger: MultichainAccountServiceMessenger;\n providers?: NamedAccountProvider[];\n};\n\n/** Reverse mapping object used to map account IDs and their wallet/multichain account. */\ntype AccountContext<Account extends Bip44Account<KeyringAccount>> = {\n wallet: MultichainAccountWallet<Account>;\n group: MultichainAccountGroup<Account>;\n};\n\n/**\n * Service to expose multichain accounts capabilities.\n */\nexport class MultichainAccountService {\n readonly #messenger: MultichainAccountServiceMessenger;\n\n readonly #providers: NamedAccountProvider[];\n\n readonly #wallets: Map<\n MultichainAccountWalletId,\n MultichainAccountWallet<Bip44Account<KeyringAccount>>\n >;\n\n readonly #accountIdToContext: Map<\n Bip44Account<KeyringAccount>['id'],\n AccountContext<Bip44Account<KeyringAccount>>\n >;\n\n /**\n * The name of the service.\n */\n name: typeof serviceName = serviceName;\n\n /**\n * Constructs a new MultichainAccountService.\n *\n * @param options - The options.\n * @param options.messenger - The messenger suited to this\n * MultichainAccountService.\n * @param options.providers - Optional list of account\n * providers.\n */\n constructor({ messenger, providers = [] }: MultichainAccountServiceOptions) {\n this.#messenger = messenger;\n this.#wallets = new Map();\n this.#accountIdToContext = new Map();\n\n // TODO: Rely on keyring capabilities once the keyring API is used by all keyrings.\n this.#providers = [\n new EvmAccountProvider(this.#messenger),\n new AccountProviderWrapper(\n this.#messenger,\n new SolAccountProvider(this.#messenger),\n ),\n // Custom account providers that can be provided by the MetaMask client.\n ...providers,\n ];\n\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountGroup',\n (...args) => this.getMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountGroups',\n (...args) => this.getMultichainAccountGroups(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountWallet',\n (...args) => this.getMultichainAccountWallet(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountWallets',\n (...args) => this.getMultichainAccountWallets(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:createNextMultichainAccountGroup',\n (...args) => this.createNextMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:createMultichainAccountGroup',\n (...args) => this.createMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:setBasicFunctionality',\n (...args) => this.setBasicFunctionality(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:alignWallets',\n (...args) => this.alignWallets(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:alignWallet',\n (...args) => this.alignWallet(...args),\n );\n this.#messenger.subscribe('AccountsController:accountAdded', (account) =>\n this.#handleOnAccountAdded(account),\n );\n this.#messenger.subscribe('AccountsController:accountRemoved', (id) =>\n this.#handleOnAccountRemoved(id),\n );\n }\n\n /**\n * Initialize the service and constructs the internal reprensentation of\n * multichain accounts and wallets.\n */\n init(): void {\n this.#wallets.clear();\n this.#accountIdToContext.clear();\n\n // Create initial wallets.\n const { keyrings } = this.#messenger.call('KeyringController:getState');\n for (const keyring of keyrings) {\n if (keyring.type === (KeyringTypes.hd as string)) {\n // Only HD keyrings have an entropy source/SRP.\n const entropySource = keyring.metadata.id;\n\n // This will automatically \"associate\" all multichain accounts for that wallet\n // (based on the accounts owned by each account providers).\n const wallet = new MultichainAccountWallet({\n entropySource,\n providers: this.#providers,\n messenger: this.#messenger,\n });\n this.#wallets.set(wallet.id, wallet);\n\n // Reverse mapping between account ID and their multichain wallet/account:\n for (const group of wallet.getMultichainAccountGroups()) {\n for (const account of group.getAccounts()) {\n this.#accountIdToContext.set(account.id, {\n wallet,\n group,\n });\n }\n }\n }\n }\n }\n\n #handleOnAccountAdded(account: KeyringAccount): void {\n // We completely omit non-BIP-44 accounts!\n if (!isBip44Account(account)) {\n return;\n }\n\n let sync = true;\n\n let wallet = this.#wallets.get(\n toMultichainAccountWalletId(account.options.entropy.id),\n );\n if (!wallet) {\n // That's a new wallet.\n wallet = new MultichainAccountWallet({\n entropySource: account.options.entropy.id,\n providers: this.#providers,\n messenger: this.#messenger,\n });\n this.#wallets.set(wallet.id, wallet);\n\n // If that's a new wallet wallet. There's nothing to \"force-sync\".\n sync = false;\n }\n\n let group = wallet.getMultichainAccountGroup(\n account.options.entropy.groupIndex,\n );\n if (!group) {\n // This new account is a new multichain account, let the wallet know\n // it has to re-sync with its providers.\n if (sync) {\n wallet.sync();\n }\n\n group = wallet.getMultichainAccountGroup(\n account.options.entropy.groupIndex,\n );\n\n // If that's a new multichain account. There's nothing to \"force-sync\".\n sync = false;\n }\n\n // We have to check against `undefined` in case `getMultichainAccount` is\n // not able to find this multichain account (which should not be possible...)\n if (group) {\n if (sync) {\n group.sync();\n }\n\n // Same here, this account should have been already grouped in that\n // multichain account.\n this.#accountIdToContext.set(account.id, {\n wallet,\n group,\n });\n }\n }\n\n #handleOnAccountRemoved(id: KeyringAccount['id']): void {\n // Force sync of the appropriate wallet if an account got removed.\n const found = this.#accountIdToContext.get(id);\n if (found) {\n const { wallet } = found;\n\n wallet.sync();\n }\n\n // Safe to call delete even if the `id` was not referencing a BIP-44 account.\n this.#accountIdToContext.delete(id);\n }\n\n #getWallet(\n entropySource: EntropySourceId,\n ): MultichainAccountWallet<Bip44Account<KeyringAccount>> {\n const wallet = this.#wallets.get(\n toMultichainAccountWalletId(entropySource),\n );\n\n if (!wallet) {\n throw new Error('Unknown wallet, no wallet matching this entropy source');\n }\n\n return wallet;\n }\n\n /**\n * Gets the account's context which contains its multichain wallet and\n * multichain account group references.\n *\n * @param id - Account ID.\n * @returns The account context if any, undefined otherwise.\n */\n getAccountContext(\n id: KeyringAccount['id'],\n ): AccountContext<Bip44Account<KeyringAccount>> | undefined {\n return this.#accountIdToContext.get(id);\n }\n\n /**\n * Gets a reference to the multichain account wallet matching this entropy source.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source of the multichain account.\n * @throws If none multichain account match this entropy.\n * @returns A reference to the multichain account wallet.\n */\n getMultichainAccountWallet({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): MultichainAccountWallet<Bip44Account<KeyringAccount>> {\n return this.#getWallet(entropySource);\n }\n\n /**\n * Gets an array of all multichain account wallets.\n *\n * @returns An array of all multichain account wallets.\n */\n getMultichainAccountWallets(): MultichainAccountWallet<\n Bip44Account<KeyringAccount>\n >[] {\n return Array.from(this.#wallets.values());\n }\n\n /**\n * Gets a reference to the multichain account group matching this entropy source\n * and a group index.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source of the multichain account.\n * @param options.groupIndex - The group index of the multichain account.\n * @throws If none multichain account match this entropy source and group index.\n * @returns A reference to the multichain account.\n */\n getMultichainAccountGroup({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): MultichainAccountGroup<Bip44Account<KeyringAccount>> {\n const multichainAccount =\n this.#getWallet(entropySource).getMultichainAccountGroup(groupIndex);\n\n if (!multichainAccount) {\n throw new Error(`No multichain account for index: ${groupIndex}`);\n }\n\n return multichainAccount;\n }\n\n /**\n * Gets all multichain account groups for a given entropy source.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source to query.\n * @throws If no multichain accounts match this entropy source.\n * @returns A list of all multichain accounts.\n */\n getMultichainAccountGroups({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): MultichainAccountGroup<Bip44Account<KeyringAccount>>[] {\n return this.#getWallet(entropySource).getMultichainAccountGroups();\n }\n\n /**\n * Creates the next multichain account group.\n *\n * @param options - Options.\n * @param options.entropySource - The wallet's entropy source.\n * @returns The next multichain account group.\n */\n async createNextMultichainAccountGroup({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): Promise<MultichainAccountGroup<Bip44Account<KeyringAccount>>> {\n return await this.#getWallet(\n entropySource,\n ).createNextMultichainAccountGroup();\n }\n\n /**\n * Creates a multichain account group.\n *\n * @param options - Options.\n * @param options.groupIndex - The group index to use.\n * @param options.entropySource - The wallet's entropy source.\n * @returns The multichain account group for this group index.\n */\n async createMultichainAccountGroup({\n groupIndex,\n entropySource,\n }: {\n groupIndex: number;\n entropySource: EntropySourceId;\n }): Promise<MultichainAccountGroup<Bip44Account<KeyringAccount>>> {\n return await this.#getWallet(entropySource).createMultichainAccountGroup(\n groupIndex,\n );\n }\n\n /**\n * Set basic functionality state and trigger alignment if enabled.\n * When basic functionality is disabled, snap-based providers are disabled.\n * When enabled, all snap providers are enabled and wallet alignment is triggered.\n * EVM providers are never disabled as they're required for basic wallet functionality.\n *\n * @param enabled - Whether basic functionality is enabled.\n */\n async setBasicFunctionality(enabled: boolean): Promise<void> {\n // Loop through providers and enable/disable only wrapped ones when basic functionality changes\n for (const provider of this.#providers) {\n if (isAccountProviderWrapper(provider)) {\n provider.setEnabled(enabled);\n }\n // Regular providers (like EVM) are never disabled for basic functionality\n }\n\n // Trigger alignment only when basic functionality is enabled\n if (enabled) {\n await this.alignWallets();\n }\n }\n\n /**\n * Align all multichain account wallets.\n */\n async alignWallets(): Promise<void> {\n const wallets = this.getMultichainAccountWallets();\n await Promise.all(wallets.map((w) => w.alignAccounts()));\n }\n\n /**\n * Align a specific multichain account wallet.\n *\n * @param entropySource - The entropy source of the multichain account wallet.\n */\n async alignWallet(entropySource: EntropySourceId): Promise<void> {\n const wallet = this.getMultichainAccountWallet({ entropySource });\n await wallet.alignAccounts();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"MultichainAccountService.cjs","sourceRoot":"","sources":["../src/MultichainAccountService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,uDAG+B;AAM/B,iDAA2D;AAE3D,qEAA4D;AAC5D,2CAAsD;AAGtD,2EAAoE;AAEpE,mFAG4C;AAC5C,2EAAoE;AACpE,2EAAoE;AAGvD,QAAA,WAAW,GAAG,0BAA0B,CAAC;AAgBtD;;GAEG;AACH,MAAa,wBAAwB;IAoBnC;;;;;;;;OAQG;IACH,YAAY,EAAE,SAAS,EAAE,SAAS,GAAG,EAAE,EAAmC;;QA5BjE,sDAA8C;QAE9C,sDAAmC;QAEnC,oDAGP;QAEO,+DAGP;QAEF;;WAEG;QACH,SAAI,GAAuB,mBAAW,CAAC;QAYrC,uBAAA,IAAI,uCAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,qCAAY,IAAI,GAAG,EAAE,MAAA,CAAC;QAC1B,uBAAA,IAAI,gDAAuB,IAAI,GAAG,EAAE,MAAA,CAAC;QAErC,mFAAmF;QACnF,uBAAA,IAAI,uCAAc;YAChB,IAAI,uCAAkB,CAAC,uBAAA,IAAI,2CAAW,CAAC;YACvC,IAAI,+CAAsB,CACxB,uBAAA,IAAI,2CAAW,EACf,IAAI,uCAAkB,CAAC,uBAAA,IAAI,2CAAW,CAAC,CACxC;YACD,wEAAwE;YACxE,GAAG,SAAS;SACb,MAAA,CAAC;QAEF,uBAAA,IAAI,2CAAW,CAAC,qBAAqB,CACnC,oDAAoD,EACpD,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,yBAAyB,CAAC,GAAG,IAAI,CAAC,CACrD,CAAC;QACF,uBAAA,IAAI,2CAAW,CAAC,qBAAqB,CACnC,qDAAqD,EACrD,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,0BAA0B,CAAC,GAAG,IAAI,CAAC,CACtD,CAAC;QACF,uBAAA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AC,CAAC;KAC3E;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n isBip44Account,\n toMultichainAccountWalletId,\n} from '@metamask/account-api';\nimport type {\n MultichainAccountWalletId,\n Bip44Account,\n} from '@metamask/account-api';\nimport type { HdKeyring } from '@metamask/eth-hd-keyring';\nimport { mnemonicPhraseToBytes } from '@metamask/key-tree';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport { areUint8ArraysEqual } from '@metamask/utils';\n\nimport type { MultichainAccountGroup } from './MultichainAccountGroup';\nimport { MultichainAccountWallet } from './MultichainAccountWallet';\nimport type { NamedAccountProvider } from './providers';\nimport {\n AccountProviderWrapper,\n isAccountProviderWrapper,\n} from './providers/AccountProviderWrapper';\nimport { EvmAccountProvider } from './providers/EvmAccountProvider';\nimport { SolAccountProvider } from './providers/SolAccountProvider';\nimport type { MultichainAccountServiceMessenger } from './types';\n\nexport const serviceName = 'MultichainAccountService';\n\n/**\n * The options that {@link MultichainAccountService} takes.\n */\ntype MultichainAccountServiceOptions = {\n messenger: MultichainAccountServiceMessenger;\n providers?: NamedAccountProvider[];\n};\n\n/** Reverse mapping object used to map account IDs and their wallet/multichain account. */\ntype AccountContext<Account extends Bip44Account<KeyringAccount>> = {\n wallet: MultichainAccountWallet<Account>;\n group: MultichainAccountGroup<Account>;\n};\n\n/**\n * Service to expose multichain accounts capabilities.\n */\nexport class MultichainAccountService {\n readonly #messenger: MultichainAccountServiceMessenger;\n\n readonly #providers: NamedAccountProvider[];\n\n readonly #wallets: Map<\n MultichainAccountWalletId,\n MultichainAccountWallet<Bip44Account<KeyringAccount>>\n >;\n\n readonly #accountIdToContext: Map<\n Bip44Account<KeyringAccount>['id'],\n AccountContext<Bip44Account<KeyringAccount>>\n >;\n\n /**\n * The name of the service.\n */\n name: typeof serviceName = serviceName;\n\n /**\n * Constructs a new MultichainAccountService.\n *\n * @param options - The options.\n * @param options.messenger - The messenger suited to this\n * MultichainAccountService.\n * @param options.providers - Optional list of account\n * providers.\n */\n constructor({ messenger, providers = [] }: MultichainAccountServiceOptions) {\n this.#messenger = messenger;\n this.#wallets = new Map();\n this.#accountIdToContext = new Map();\n\n // TODO: Rely on keyring capabilities once the keyring API is used by all keyrings.\n this.#providers = [\n new EvmAccountProvider(this.#messenger),\n new AccountProviderWrapper(\n this.#messenger,\n new SolAccountProvider(this.#messenger),\n ),\n // Custom account providers that can be provided by the MetaMask client.\n ...providers,\n ];\n\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountGroup',\n (...args) => this.getMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountGroups',\n (...args) => this.getMultichainAccountGroups(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountWallet',\n (...args) => this.getMultichainAccountWallet(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountWallets',\n (...args) => this.getMultichainAccountWallets(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:createNextMultichainAccountGroup',\n (...args) => this.createNextMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:createMultichainAccountGroup',\n (...args) => this.createMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:setBasicFunctionality',\n (...args) => this.setBasicFunctionality(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:alignWallets',\n (...args) => this.alignWallets(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:alignWallet',\n (...args) => this.alignWallet(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:createMultichainAccountWallet',\n (...args) => this.createMultichainAccountWallet(...args),\n );\n\n this.#messenger.subscribe('AccountsController:accountAdded', (account) =>\n this.#handleOnAccountAdded(account),\n );\n this.#messenger.subscribe('AccountsController:accountRemoved', (id) =>\n this.#handleOnAccountRemoved(id),\n );\n }\n\n /**\n * Initialize the service and constructs the internal reprensentation of\n * multichain accounts and wallets.\n */\n init(): void {\n this.#wallets.clear();\n this.#accountIdToContext.clear();\n\n // Create initial wallets.\n const { keyrings } = this.#messenger.call('KeyringController:getState');\n for (const keyring of keyrings) {\n if (keyring.type === (KeyringTypes.hd as string)) {\n // Only HD keyrings have an entropy source/SRP.\n const entropySource = keyring.metadata.id;\n\n // This will automatically \"associate\" all multichain accounts for that wallet\n // (based on the accounts owned by each account providers).\n const wallet = new MultichainAccountWallet({\n entropySource,\n providers: this.#providers,\n messenger: this.#messenger,\n });\n this.#wallets.set(wallet.id, wallet);\n\n // Reverse mapping between account ID and their multichain wallet/account:\n for (const group of wallet.getMultichainAccountGroups()) {\n for (const account of group.getAccounts()) {\n this.#accountIdToContext.set(account.id, {\n wallet,\n group,\n });\n }\n }\n }\n }\n }\n\n #handleOnAccountAdded(account: KeyringAccount): void {\n // We completely omit non-BIP-44 accounts!\n if (!isBip44Account(account)) {\n return;\n }\n\n let sync = true;\n\n let wallet = this.#wallets.get(\n toMultichainAccountWalletId(account.options.entropy.id),\n );\n if (!wallet) {\n // That's a new wallet.\n wallet = new MultichainAccountWallet({\n entropySource: account.options.entropy.id,\n providers: this.#providers,\n messenger: this.#messenger,\n });\n this.#wallets.set(wallet.id, wallet);\n\n // If that's a new wallet wallet. There's nothing to \"force-sync\".\n sync = false;\n }\n\n let group = wallet.getMultichainAccountGroup(\n account.options.entropy.groupIndex,\n );\n if (!group) {\n // This new account is a new multichain account, let the wallet know\n // it has to re-sync with its providers.\n if (sync) {\n wallet.sync();\n }\n\n group = wallet.getMultichainAccountGroup(\n account.options.entropy.groupIndex,\n );\n\n // If that's a new multichain account. There's nothing to \"force-sync\".\n sync = false;\n }\n\n // We have to check against `undefined` in case `getMultichainAccount` is\n // not able to find this multichain account (which should not be possible...)\n if (group) {\n if (sync) {\n group.sync();\n }\n\n // Same here, this account should have been already grouped in that\n // multichain account.\n this.#accountIdToContext.set(account.id, {\n wallet,\n group,\n });\n }\n }\n\n #handleOnAccountRemoved(id: KeyringAccount['id']): void {\n // Force sync of the appropriate wallet if an account got removed.\n const found = this.#accountIdToContext.get(id);\n if (found) {\n const { wallet } = found;\n\n wallet.sync();\n }\n\n // Safe to call delete even if the `id` was not referencing a BIP-44 account.\n this.#accountIdToContext.delete(id);\n }\n\n #getWallet(\n entropySource: EntropySourceId,\n ): MultichainAccountWallet<Bip44Account<KeyringAccount>> {\n const wallet = this.#wallets.get(\n toMultichainAccountWalletId(entropySource),\n );\n\n if (!wallet) {\n throw new Error('Unknown wallet, no wallet matching this entropy source');\n }\n\n return wallet;\n }\n\n /**\n * Gets the account's context which contains its multichain wallet and\n * multichain account group references.\n *\n * @param id - Account ID.\n * @returns The account context if any, undefined otherwise.\n */\n getAccountContext(\n id: KeyringAccount['id'],\n ): AccountContext<Bip44Account<KeyringAccount>> | undefined {\n return this.#accountIdToContext.get(id);\n }\n\n /**\n * Gets a reference to the multichain account wallet matching this entropy source.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source of the multichain account.\n * @throws If none multichain account match this entropy.\n * @returns A reference to the multichain account wallet.\n */\n getMultichainAccountWallet({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): MultichainAccountWallet<Bip44Account<KeyringAccount>> {\n return this.#getWallet(entropySource);\n }\n\n /**\n * Gets an array of all multichain account wallets.\n *\n * @returns An array of all multichain account wallets.\n */\n getMultichainAccountWallets(): MultichainAccountWallet<\n Bip44Account<KeyringAccount>\n >[] {\n return Array.from(this.#wallets.values());\n }\n\n /**\n * Creates a new multichain account wallet with the given mnemonic.\n *\n * NOTE: This method should only be called in client code where a mutex lock is acquired.\n * `discoverAndCreateAccounts` should be called after this method to discover and create accounts.\n *\n * @param options - Options.\n * @param options.mnemonic - The mnemonic to use to create the new wallet.\n * @throws If the mnemonic has already been imported.\n * @returns The new multichain account wallet.\n */\n async createMultichainAccountWallet({\n mnemonic,\n }: {\n mnemonic: string;\n }): Promise<MultichainAccountWallet<Bip44Account<KeyringAccount>>> {\n const existingKeyrings = this.#messenger.call(\n 'KeyringController:getKeyringsByType',\n KeyringTypes.hd,\n ) as HdKeyring[];\n\n const mnemonicAsBytes = mnemonicPhraseToBytes(mnemonic);\n\n const alreadyHasImportedSrp = existingKeyrings.some((keyring) => {\n if (!keyring.mnemonic) {\n return false;\n }\n return areUint8ArraysEqual(keyring.mnemonic, mnemonicAsBytes);\n });\n\n if (alreadyHasImportedSrp) {\n throw new Error('This Secret Recovery Phrase has already been imported.');\n }\n\n const result = await this.#messenger.call(\n 'KeyringController:addNewKeyring',\n KeyringTypes.hd,\n { mnemonic },\n );\n\n const wallet = new MultichainAccountWallet({\n providers: this.#providers,\n entropySource: result.id,\n messenger: this.#messenger,\n });\n\n this.#wallets.set(wallet.id, wallet);\n\n return wallet;\n }\n\n /**\n * Gets a reference to the multichain account group matching this entropy source\n * and a group index.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source of the multichain account.\n * @param options.groupIndex - The group index of the multichain account.\n * @throws If none multichain account match this entropy source and group index.\n * @returns A reference to the multichain account.\n */\n getMultichainAccountGroup({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): MultichainAccountGroup<Bip44Account<KeyringAccount>> {\n const multichainAccount =\n this.#getWallet(entropySource).getMultichainAccountGroup(groupIndex);\n\n if (!multichainAccount) {\n throw new Error(`No multichain account for index: ${groupIndex}`);\n }\n\n return multichainAccount;\n }\n\n /**\n * Gets all multichain account groups for a given entropy source.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source to query.\n * @throws If no multichain accounts match this entropy source.\n * @returns A list of all multichain accounts.\n */\n getMultichainAccountGroups({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): MultichainAccountGroup<Bip44Account<KeyringAccount>>[] {\n return this.#getWallet(entropySource).getMultichainAccountGroups();\n }\n\n /**\n * Creates the next multichain account group.\n *\n * @param options - Options.\n * @param options.entropySource - The wallet's entropy source.\n * @returns The next multichain account group.\n */\n async createNextMultichainAccountGroup({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): Promise<MultichainAccountGroup<Bip44Account<KeyringAccount>>> {\n return await this.#getWallet(\n entropySource,\n ).createNextMultichainAccountGroup();\n }\n\n /**\n * Creates a multichain account group.\n *\n * @param options - Options.\n * @param options.groupIndex - The group index to use.\n * @param options.entropySource - The wallet's entropy source.\n * @returns The multichain account group for this group index.\n */\n async createMultichainAccountGroup({\n groupIndex,\n entropySource,\n }: {\n groupIndex: number;\n entropySource: EntropySourceId;\n }): Promise<MultichainAccountGroup<Bip44Account<KeyringAccount>>> {\n return await this.#getWallet(entropySource).createMultichainAccountGroup(\n groupIndex,\n );\n }\n\n /**\n * Set basic functionality state and trigger alignment if enabled.\n * When basic functionality is disabled, snap-based providers are disabled.\n * When enabled, all snap providers are enabled and wallet alignment is triggered.\n * EVM providers are never disabled as they're required for basic wallet functionality.\n *\n * @param enabled - Whether basic functionality is enabled.\n */\n async setBasicFunctionality(enabled: boolean): Promise<void> {\n // Loop through providers and enable/disable only wrapped ones when basic functionality changes\n for (const provider of this.#providers) {\n if (isAccountProviderWrapper(provider)) {\n provider.setEnabled(enabled);\n }\n // Regular providers (like EVM) are never disabled for basic functionality\n }\n\n // Trigger alignment only when basic functionality is enabled\n if (enabled) {\n await this.alignWallets();\n }\n }\n\n /**\n * Align all multichain account wallets.\n */\n async alignWallets(): Promise<void> {\n const wallets = this.getMultichainAccountWallets();\n await Promise.all(wallets.map((w) => w.alignAccounts()));\n }\n\n /**\n * Align a specific multichain account wallet.\n *\n * @param entropySource - The entropy source of the multichain account wallet.\n */\n async alignWallet(entropySource: EntropySourceId): Promise<void> {\n const wallet = this.getMultichainAccountWallet({ entropySource });\n await wallet.alignAccounts();\n }\n}\n"]}
|
|
@@ -66,6 +66,20 @@ export declare class MultichainAccountService {
|
|
|
66
66
|
* @returns An array of all multichain account wallets.
|
|
67
67
|
*/
|
|
68
68
|
getMultichainAccountWallets(): MultichainAccountWallet<Bip44Account<KeyringAccount>>[];
|
|
69
|
+
/**
|
|
70
|
+
* Creates a new multichain account wallet with the given mnemonic.
|
|
71
|
+
*
|
|
72
|
+
* NOTE: This method should only be called in client code where a mutex lock is acquired.
|
|
73
|
+
* `discoverAndCreateAccounts` should be called after this method to discover and create accounts.
|
|
74
|
+
*
|
|
75
|
+
* @param options - Options.
|
|
76
|
+
* @param options.mnemonic - The mnemonic to use to create the new wallet.
|
|
77
|
+
* @throws If the mnemonic has already been imported.
|
|
78
|
+
* @returns The new multichain account wallet.
|
|
79
|
+
*/
|
|
80
|
+
createMultichainAccountWallet({ mnemonic, }: {
|
|
81
|
+
mnemonic: string;
|
|
82
|
+
}): Promise<MultichainAccountWallet<Bip44Account<KeyringAccount>>>;
|
|
69
83
|
/**
|
|
70
84
|
* Gets a reference to the multichain account group matching this entropy source
|
|
71
85
|
* and a group index.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultichainAccountService.d.cts","sourceRoot":"","sources":["../src/MultichainAccountService.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAEV,YAAY,EACb,8BAA8B;
|
|
1
|
+
{"version":3,"file":"MultichainAccountService.d.cts","sourceRoot":"","sources":["../src/MultichainAccountService.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAEV,YAAY,EACb,8BAA8B;AAG/B,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,8BAA8B;AAI7E,OAAO,KAAK,EAAE,sBAAsB,EAAE,qCAAiC;AACvE,OAAO,EAAE,uBAAuB,EAAE,sCAAkC;AACpE,OAAO,KAAK,EAAE,oBAAoB,EAAE,8BAAoB;AAOxD,OAAO,KAAK,EAAE,iCAAiC,EAAE,oBAAgB;AAEjE,eAAO,MAAM,WAAW,6BAA6B,CAAC;AAEtD;;GAEG;AACH,KAAK,+BAA+B,GAAG;IACrC,SAAS,EAAE,iCAAiC,CAAC;IAC7C,SAAS,CAAC,EAAE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AE,eAAe,CAAC;KAChC,GAAG,sBAAsB,CAAC,YAAY,CAAC,cAAc,CAAC,CAAC,EAAE;IAI1D;;;;;;OAMG;IACG,gCAAgC,CAAC,EACrC,aAAa,GACd,EAAE;QACD,aAAa,EAAE,eAAe,CAAC;KAChC,GAAG,OAAO,CAAC,sBAAsB,CAAC,YAAY,CAAC,cAAc,CAAC,CAAC,CAAC;IAMjE;;;;;;;OAOG;IACG,4BAA4B,CAAC,EACjC,UAAU,EACV,aAAa,GACd,EAAE;QACD,UAAU,EAAE,MAAM,CAAC;QACnB,aAAa,EAAE,eAAe,CAAC;KAChC,GAAG,OAAO,CAAC,sBAAsB,CAAC,YAAY,CAAC,cAAc,CAAC,CAAC,CAAC;IAMjE;;;;;;;OAOG;IACG,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAe5D;;OAEG;IACG,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;IAKnC;;;;OAIG;IACG,WAAW,CAAC,aAAa,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAIjE"}
|
|
@@ -66,6 +66,20 @@ export declare class MultichainAccountService {
|
|
|
66
66
|
* @returns An array of all multichain account wallets.
|
|
67
67
|
*/
|
|
68
68
|
getMultichainAccountWallets(): MultichainAccountWallet<Bip44Account<KeyringAccount>>[];
|
|
69
|
+
/**
|
|
70
|
+
* Creates a new multichain account wallet with the given mnemonic.
|
|
71
|
+
*
|
|
72
|
+
* NOTE: This method should only be called in client code where a mutex lock is acquired.
|
|
73
|
+
* `discoverAndCreateAccounts` should be called after this method to discover and create accounts.
|
|
74
|
+
*
|
|
75
|
+
* @param options - Options.
|
|
76
|
+
* @param options.mnemonic - The mnemonic to use to create the new wallet.
|
|
77
|
+
* @throws If the mnemonic has already been imported.
|
|
78
|
+
* @returns The new multichain account wallet.
|
|
79
|
+
*/
|
|
80
|
+
createMultichainAccountWallet({ mnemonic, }: {
|
|
81
|
+
mnemonic: string;
|
|
82
|
+
}): Promise<MultichainAccountWallet<Bip44Account<KeyringAccount>>>;
|
|
69
83
|
/**
|
|
70
84
|
* Gets a reference to the multichain account group matching this entropy source
|
|
71
85
|
* and a group index.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultichainAccountService.d.mts","sourceRoot":"","sources":["../src/MultichainAccountService.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAEV,YAAY,EACb,8BAA8B;
|
|
1
|
+
{"version":3,"file":"MultichainAccountService.d.mts","sourceRoot":"","sources":["../src/MultichainAccountService.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAEV,YAAY,EACb,8BAA8B;AAG/B,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,8BAA8B;AAI7E,OAAO,KAAK,EAAE,sBAAsB,EAAE,qCAAiC;AACvE,OAAO,EAAE,uBAAuB,EAAE,sCAAkC;AACpE,OAAO,KAAK,EAAE,oBAAoB,EAAE,8BAAoB;AAOxD,OAAO,KAAK,EAAE,iCAAiC,EAAE,oBAAgB;AAEjE,eAAO,MAAM,WAAW,6BAA6B,CAAC;AAEtD;;GAEG;AACH,KAAK,+BAA+B,GAAG;IACrC,SAAS,EAAE,iCAAiC,CAAC;IAC7C,SAAS,CAAC,EAAE,oBAAoB,EAAE,CAAC;CACpC,CAAC;AAEF,0FAA0F;AAC1F,KAAK,cAAc,CAAC,OAAO,SAAS,YAAY,CAAC,cAAc,CAAC,IAAI;IAClE,MAAM,EAAE,uBAAuB,CAAC,OAAO,CAAC,CAAC;IACzC,KAAK,EAAE,sBAAsB,CAAC,OAAO,CAAC,CAAC;CACxC,CAAC;AAEF;;GAEG;AACH,qBAAa,wBAAwB;;IAenC;;OAEG;IACH,IAAI,EAAE,OAAO,WAAW,CAAe;IAEvC;;;;;;;;OAQG;gBACS,EAAE,SAAS,EAAE,SAAc,EAAE,EAAE,+BAA+B;IAiE1E;;;OAGG;IACH,IAAI,IAAI,IAAI;IAsHZ;;;;;;O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AAC,CAAC;IAMjE;;;;;;;OAOG;IACG,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAe5D;;OAEG;IACG,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;IAKnC;;;;OAIG;IACG,WAAW,CAAC,aAAa,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;CAIjE"}
|
|
@@ -11,7 +11,9 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
11
11
|
};
|
|
12
12
|
var _MultichainAccountService_instances, _MultichainAccountService_messenger, _MultichainAccountService_providers, _MultichainAccountService_wallets, _MultichainAccountService_accountIdToContext, _MultichainAccountService_handleOnAccountAdded, _MultichainAccountService_handleOnAccountRemoved, _MultichainAccountService_getWallet;
|
|
13
13
|
import { isBip44Account, toMultichainAccountWalletId } from "@metamask/account-api";
|
|
14
|
+
import { mnemonicPhraseToBytes } from "@metamask/key-tree";
|
|
14
15
|
import { KeyringTypes } from "@metamask/keyring-controller";
|
|
16
|
+
import { areUint8ArraysEqual } from "@metamask/utils";
|
|
15
17
|
import { MultichainAccountWallet } from "./MultichainAccountWallet.mjs";
|
|
16
18
|
import { AccountProviderWrapper, isAccountProviderWrapper } from "./providers/AccountProviderWrapper.mjs";
|
|
17
19
|
import { EvmAccountProvider } from "./providers/EvmAccountProvider.mjs";
|
|
@@ -59,6 +61,7 @@ export class MultichainAccountService {
|
|
|
59
61
|
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").registerActionHandler('MultichainAccountService:setBasicFunctionality', (...args) => this.setBasicFunctionality(...args));
|
|
60
62
|
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").registerActionHandler('MultichainAccountService:alignWallets', (...args) => this.alignWallets(...args));
|
|
61
63
|
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").registerActionHandler('MultichainAccountService:alignWallet', (...args) => this.alignWallet(...args));
|
|
64
|
+
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").registerActionHandler('MultichainAccountService:createMultichainAccountWallet', (...args) => this.createMultichainAccountWallet(...args));
|
|
62
65
|
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").subscribe('AccountsController:accountAdded', (account) => __classPrivateFieldGet(this, _MultichainAccountService_instances, "m", _MultichainAccountService_handleOnAccountAdded).call(this, account));
|
|
63
66
|
__classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").subscribe('AccountsController:accountRemoved', (id) => __classPrivateFieldGet(this, _MultichainAccountService_instances, "m", _MultichainAccountService_handleOnAccountRemoved).call(this, id));
|
|
64
67
|
}
|
|
@@ -124,6 +127,38 @@ export class MultichainAccountService {
|
|
|
124
127
|
getMultichainAccountWallets() {
|
|
125
128
|
return Array.from(__classPrivateFieldGet(this, _MultichainAccountService_wallets, "f").values());
|
|
126
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* Creates a new multichain account wallet with the given mnemonic.
|
|
132
|
+
*
|
|
133
|
+
* NOTE: This method should only be called in client code where a mutex lock is acquired.
|
|
134
|
+
* `discoverAndCreateAccounts` should be called after this method to discover and create accounts.
|
|
135
|
+
*
|
|
136
|
+
* @param options - Options.
|
|
137
|
+
* @param options.mnemonic - The mnemonic to use to create the new wallet.
|
|
138
|
+
* @throws If the mnemonic has already been imported.
|
|
139
|
+
* @returns The new multichain account wallet.
|
|
140
|
+
*/
|
|
141
|
+
async createMultichainAccountWallet({ mnemonic, }) {
|
|
142
|
+
const existingKeyrings = __classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").call('KeyringController:getKeyringsByType', KeyringTypes.hd);
|
|
143
|
+
const mnemonicAsBytes = mnemonicPhraseToBytes(mnemonic);
|
|
144
|
+
const alreadyHasImportedSrp = existingKeyrings.some((keyring) => {
|
|
145
|
+
if (!keyring.mnemonic) {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
return areUint8ArraysEqual(keyring.mnemonic, mnemonicAsBytes);
|
|
149
|
+
});
|
|
150
|
+
if (alreadyHasImportedSrp) {
|
|
151
|
+
throw new Error('This Secret Recovery Phrase has already been imported.');
|
|
152
|
+
}
|
|
153
|
+
const result = await __classPrivateFieldGet(this, _MultichainAccountService_messenger, "f").call('KeyringController:addNewKeyring', KeyringTypes.hd, { mnemonic });
|
|
154
|
+
const wallet = new MultichainAccountWallet({
|
|
155
|
+
providers: __classPrivateFieldGet(this, _MultichainAccountService_providers, "f"),
|
|
156
|
+
entropySource: result.id,
|
|
157
|
+
messenger: __classPrivateFieldGet(this, _MultichainAccountService_messenger, "f"),
|
|
158
|
+
});
|
|
159
|
+
__classPrivateFieldGet(this, _MultichainAccountService_wallets, "f").set(wallet.id, wallet);
|
|
160
|
+
return wallet;
|
|
161
|
+
}
|
|
127
162
|
/**
|
|
128
163
|
* Gets a reference to the multichain account group matching this entropy source
|
|
129
164
|
* and a group index.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MultichainAccountService.mjs","sourceRoot":"","sources":["../src/MultichainAccountService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,cAAc,EACd,2BAA2B,EAC5B,8BAA8B;AAM/B,OAAO,EAAE,YAAY,EAAE,qCAAqC;AAG5D,OAAO,EAAE,uBAAuB,EAAE,sCAAkC;AAEpE,OAAO,EACL,sBAAsB,EACtB,wBAAwB,EACzB,+CAA2C;AAC5C,OAAO,EAAE,kBAAkB,EAAE,2CAAuC;AACpE,OAAO,EAAE,kBAAkB,EAAE,2CAAuC;AAGpE,MAAM,CAAC,MAAM,WAAW,GAAG,0BAA0B,CAAC;AAgBtD;;GAEG;AACH,MAAM,OAAO,wBAAwB;IAoBnC;;;;;;;;OAQG;IACH,YAAY,EAAE,SAAS,EAAE,SAAS,GAAG,EAAE,EAAmC;;QA5BjE,sDAA8C;QAE9C,sDAAmC;QAEnC,oDAGP;QAEO,+DAGP;QAEF;;WAEG;QACH,SAAI,GAAuB,WAAW,CAAC;QAYrC,uBAAA,IAAI,uCAAc,SAAS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AAI,EAAE;YACR,KAAK,CAAC,IAAI,EAAE,CAAC;SACd;QAED,mEAAmE;QACnE,sBAAsB;QACtB,uBAAA,IAAI,oDAAoB,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,EAAE;YACvC,MAAM;YACN,KAAK;SACN,CAAC,CAAC;KACJ;AACH,CAAC,+GAEuB,EAAwB;IAC9C,kEAAkE;IAClE,MAAM,KAAK,GAAG,uBAAA,IAAI,oDAAoB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAC/C,IAAI,KAAK,EAAE;QACT,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;QAEzB,MAAM,CAAC,IAAI,EAAE,CAAC;KACf;IAED,6EAA6E;IAC7E,uBAAA,IAAI,oDAAoB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AACtC,CAAC,qFAGC,aAA8B;IAE9B,MAAM,MAAM,GAAG,uBAAA,IAAI,yCAAS,CAAC,GAAG,CAC9B,2BAA2B,CAAC,aAAa,CAAC,CAC3C,CAAC;IAEF,IAAI,CAAC,MAAM,EAAE;QACX,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;KAC3E;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n isBip44Account,\n toMultichainAccountWalletId,\n} from '@metamask/account-api';\nimport type {\n MultichainAccountWalletId,\n Bip44Account,\n} from '@metamask/account-api';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\n\nimport type { MultichainAccountGroup } from './MultichainAccountGroup';\nimport { MultichainAccountWallet } from './MultichainAccountWallet';\nimport type { NamedAccountProvider } from './providers';\nimport {\n AccountProviderWrapper,\n isAccountProviderWrapper,\n} from './providers/AccountProviderWrapper';\nimport { EvmAccountProvider } from './providers/EvmAccountProvider';\nimport { SolAccountProvider } from './providers/SolAccountProvider';\nimport type { MultichainAccountServiceMessenger } from './types';\n\nexport const serviceName = 'MultichainAccountService';\n\n/**\n * The options that {@link MultichainAccountService} takes.\n */\ntype MultichainAccountServiceOptions = {\n messenger: MultichainAccountServiceMessenger;\n providers?: NamedAccountProvider[];\n};\n\n/** Reverse mapping object used to map account IDs and their wallet/multichain account. */\ntype AccountContext<Account extends Bip44Account<KeyringAccount>> = {\n wallet: MultichainAccountWallet<Account>;\n group: MultichainAccountGroup<Account>;\n};\n\n/**\n * Service to expose multichain accounts capabilities.\n */\nexport class MultichainAccountService {\n readonly #messenger: MultichainAccountServiceMessenger;\n\n readonly #providers: NamedAccountProvider[];\n\n readonly #wallets: Map<\n MultichainAccountWalletId,\n MultichainAccountWallet<Bip44Account<KeyringAccount>>\n >;\n\n readonly #accountIdToContext: Map<\n Bip44Account<KeyringAccount>['id'],\n AccountContext<Bip44Account<KeyringAccount>>\n >;\n\n /**\n * The name of the service.\n */\n name: typeof serviceName = serviceName;\n\n /**\n * Constructs a new MultichainAccountService.\n *\n * @param options - The options.\n * @param options.messenger - The messenger suited to this\n * MultichainAccountService.\n * @param options.providers - Optional list of account\n * providers.\n */\n constructor({ messenger, providers = [] }: MultichainAccountServiceOptions) {\n this.#messenger = messenger;\n this.#wallets = new Map();\n this.#accountIdToContext = new Map();\n\n // TODO: Rely on keyring capabilities once the keyring API is used by all keyrings.\n this.#providers = [\n new EvmAccountProvider(this.#messenger),\n new AccountProviderWrapper(\n this.#messenger,\n new SolAccountProvider(this.#messenger),\n ),\n // Custom account providers that can be provided by the MetaMask client.\n ...providers,\n ];\n\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountGroup',\n (...args) => this.getMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountGroups',\n (...args) => this.getMultichainAccountGroups(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountWallet',\n (...args) => this.getMultichainAccountWallet(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountWallets',\n (...args) => this.getMultichainAccountWallets(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:createNextMultichainAccountGroup',\n (...args) => this.createNextMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:createMultichainAccountGroup',\n (...args) => this.createMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:setBasicFunctionality',\n (...args) => this.setBasicFunctionality(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:alignWallets',\n (...args) => this.alignWallets(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:alignWallet',\n (...args) => this.alignWallet(...args),\n );\n this.#messenger.subscribe('AccountsController:accountAdded', (account) =>\n this.#handleOnAccountAdded(account),\n );\n this.#messenger.subscribe('AccountsController:accountRemoved', (id) =>\n this.#handleOnAccountRemoved(id),\n );\n }\n\n /**\n * Initialize the service and constructs the internal reprensentation of\n * multichain accounts and wallets.\n */\n init(): void {\n this.#wallets.clear();\n this.#accountIdToContext.clear();\n\n // Create initial wallets.\n const { keyrings } = this.#messenger.call('KeyringController:getState');\n for (const keyring of keyrings) {\n if (keyring.type === (KeyringTypes.hd as string)) {\n // Only HD keyrings have an entropy source/SRP.\n const entropySource = keyring.metadata.id;\n\n // This will automatically \"associate\" all multichain accounts for that wallet\n // (based on the accounts owned by each account providers).\n const wallet = new MultichainAccountWallet({\n entropySource,\n providers: this.#providers,\n messenger: this.#messenger,\n });\n this.#wallets.set(wallet.id, wallet);\n\n // Reverse mapping between account ID and their multichain wallet/account:\n for (const group of wallet.getMultichainAccountGroups()) {\n for (const account of group.getAccounts()) {\n this.#accountIdToContext.set(account.id, {\n wallet,\n group,\n });\n }\n }\n }\n }\n }\n\n #handleOnAccountAdded(account: KeyringAccount): void {\n // We completely omit non-BIP-44 accounts!\n if (!isBip44Account(account)) {\n return;\n }\n\n let sync = true;\n\n let wallet = this.#wallets.get(\n toMultichainAccountWalletId(account.options.entropy.id),\n );\n if (!wallet) {\n // That's a new wallet.\n wallet = new MultichainAccountWallet({\n entropySource: account.options.entropy.id,\n providers: this.#providers,\n messenger: this.#messenger,\n });\n this.#wallets.set(wallet.id, wallet);\n\n // If that's a new wallet wallet. There's nothing to \"force-sync\".\n sync = false;\n }\n\n let group = wallet.getMultichainAccountGroup(\n account.options.entropy.groupIndex,\n );\n if (!group) {\n // This new account is a new multichain account, let the wallet know\n // it has to re-sync with its providers.\n if (sync) {\n wallet.sync();\n }\n\n group = wallet.getMultichainAccountGroup(\n account.options.entropy.groupIndex,\n );\n\n // If that's a new multichain account. There's nothing to \"force-sync\".\n sync = false;\n }\n\n // We have to check against `undefined` in case `getMultichainAccount` is\n // not able to find this multichain account (which should not be possible...)\n if (group) {\n if (sync) {\n group.sync();\n }\n\n // Same here, this account should have been already grouped in that\n // multichain account.\n this.#accountIdToContext.set(account.id, {\n wallet,\n group,\n });\n }\n }\n\n #handleOnAccountRemoved(id: KeyringAccount['id']): void {\n // Force sync of the appropriate wallet if an account got removed.\n const found = this.#accountIdToContext.get(id);\n if (found) {\n const { wallet } = found;\n\n wallet.sync();\n }\n\n // Safe to call delete even if the `id` was not referencing a BIP-44 account.\n this.#accountIdToContext.delete(id);\n }\n\n #getWallet(\n entropySource: EntropySourceId,\n ): MultichainAccountWallet<Bip44Account<KeyringAccount>> {\n const wallet = this.#wallets.get(\n toMultichainAccountWalletId(entropySource),\n );\n\n if (!wallet) {\n throw new Error('Unknown wallet, no wallet matching this entropy source');\n }\n\n return wallet;\n }\n\n /**\n * Gets the account's context which contains its multichain wallet and\n * multichain account group references.\n *\n * @param id - Account ID.\n * @returns The account context if any, undefined otherwise.\n */\n getAccountContext(\n id: KeyringAccount['id'],\n ): AccountContext<Bip44Account<KeyringAccount>> | undefined {\n return this.#accountIdToContext.get(id);\n }\n\n /**\n * Gets a reference to the multichain account wallet matching this entropy source.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source of the multichain account.\n * @throws If none multichain account match this entropy.\n * @returns A reference to the multichain account wallet.\n */\n getMultichainAccountWallet({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): MultichainAccountWallet<Bip44Account<KeyringAccount>> {\n return this.#getWallet(entropySource);\n }\n\n /**\n * Gets an array of all multichain account wallets.\n *\n * @returns An array of all multichain account wallets.\n */\n getMultichainAccountWallets(): MultichainAccountWallet<\n Bip44Account<KeyringAccount>\n >[] {\n return Array.from(this.#wallets.values());\n }\n\n /**\n * Gets a reference to the multichain account group matching this entropy source\n * and a group index.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source of the multichain account.\n * @param options.groupIndex - The group index of the multichain account.\n * @throws If none multichain account match this entropy source and group index.\n * @returns A reference to the multichain account.\n */\n getMultichainAccountGroup({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): MultichainAccountGroup<Bip44Account<KeyringAccount>> {\n const multichainAccount =\n this.#getWallet(entropySource).getMultichainAccountGroup(groupIndex);\n\n if (!multichainAccount) {\n throw new Error(`No multichain account for index: ${groupIndex}`);\n }\n\n return multichainAccount;\n }\n\n /**\n * Gets all multichain account groups for a given entropy source.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source to query.\n * @throws If no multichain accounts match this entropy source.\n * @returns A list of all multichain accounts.\n */\n getMultichainAccountGroups({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): MultichainAccountGroup<Bip44Account<KeyringAccount>>[] {\n return this.#getWallet(entropySource).getMultichainAccountGroups();\n }\n\n /**\n * Creates the next multichain account group.\n *\n * @param options - Options.\n * @param options.entropySource - The wallet's entropy source.\n * @returns The next multichain account group.\n */\n async createNextMultichainAccountGroup({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): Promise<MultichainAccountGroup<Bip44Account<KeyringAccount>>> {\n return await this.#getWallet(\n entropySource,\n ).createNextMultichainAccountGroup();\n }\n\n /**\n * Creates a multichain account group.\n *\n * @param options - Options.\n * @param options.groupIndex - The group index to use.\n * @param options.entropySource - The wallet's entropy source.\n * @returns The multichain account group for this group index.\n */\n async createMultichainAccountGroup({\n groupIndex,\n entropySource,\n }: {\n groupIndex: number;\n entropySource: EntropySourceId;\n }): Promise<MultichainAccountGroup<Bip44Account<KeyringAccount>>> {\n return await this.#getWallet(entropySource).createMultichainAccountGroup(\n groupIndex,\n );\n }\n\n /**\n * Set basic functionality state and trigger alignment if enabled.\n * When basic functionality is disabled, snap-based providers are disabled.\n * When enabled, all snap providers are enabled and wallet alignment is triggered.\n * EVM providers are never disabled as they're required for basic wallet functionality.\n *\n * @param enabled - Whether basic functionality is enabled.\n */\n async setBasicFunctionality(enabled: boolean): Promise<void> {\n // Loop through providers and enable/disable only wrapped ones when basic functionality changes\n for (const provider of this.#providers) {\n if (isAccountProviderWrapper(provider)) {\n provider.setEnabled(enabled);\n }\n // Regular providers (like EVM) are never disabled for basic functionality\n }\n\n // Trigger alignment only when basic functionality is enabled\n if (enabled) {\n await this.alignWallets();\n }\n }\n\n /**\n * Align all multichain account wallets.\n */\n async alignWallets(): Promise<void> {\n const wallets = this.getMultichainAccountWallets();\n await Promise.all(wallets.map((w) => w.alignAccounts()));\n }\n\n /**\n * Align a specific multichain account wallet.\n *\n * @param entropySource - The entropy source of the multichain account wallet.\n */\n async alignWallet(entropySource: EntropySourceId): Promise<void> {\n const wallet = this.getMultichainAccountWallet({ entropySource });\n await wallet.alignAccounts();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"MultichainAccountService.mjs","sourceRoot":"","sources":["../src/MultichainAccountService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,cAAc,EACd,2BAA2B,EAC5B,8BAA8B;AAM/B,OAAO,EAAE,qBAAqB,EAAE,2BAA2B;AAE3D,OAAO,EAAE,YAAY,EAAE,qCAAqC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,wBAAwB;AAGtD,OAAO,EAAE,uBAAuB,EAAE,sCAAkC;AAEpE,OAAO,EACL,sBAAsB,EACtB,wBAAwB,EACzB,+CAA2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AC,KAAK,EAAE;QACV,oEAAoE;QACpE,wCAAwC;QACxC,IAAI,IAAI,EAAE;YACR,MAAM,CAAC,IAAI,EAAE,CAAC;SACf;QAED,KAAK,GAAG,MAAM,CAAC,yBAAyB,CACtC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,CACnC,CAAC;QAEF,uEAAuE;QACvE,IAAI,GAAG,KAAK,CAAC;KACd;IAED,yEAAyE;IACzE,6EAA6E;IAC7E,IAAI,KAAK,EAAE;QACT,IAAI,IAAI,EAAE;YACR,KAAK,CAAC,IAAI,EAAE,CAAC;SACd;QAED,mEAAmE;QACnE,sBAAsB;QACtB,uBAAA,IAAI,oDAAoB,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,EAAE;YACvC,MAAM;YACN,KAAK;SACN,CAAC,CAAC;KACJ;AACH,CAAC,+GAEuB,EAAwB;IAC9C,kEAAkE;IAClE,MAAM,KAAK,GAAG,uBAAA,IAAI,oDAAoB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAC/C,IAAI,KAAK,EAAE;QACT,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;QAEzB,MAAM,CAAC,IAAI,EAAE,CAAC;KACf;IAED,6EAA6E;IAC7E,uBAAA,IAAI,oDAAoB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AACtC,CAAC,qFAGC,aAA8B;IAE9B,MAAM,MAAM,GAAG,uBAAA,IAAI,yCAAS,CAAC,GAAG,CAC9B,2BAA2B,CAAC,aAAa,CAAC,CAC3C,CAAC;IAEF,IAAI,CAAC,MAAM,EAAE;QACX,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;KAC3E;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n isBip44Account,\n toMultichainAccountWalletId,\n} from '@metamask/account-api';\nimport type {\n MultichainAccountWalletId,\n Bip44Account,\n} from '@metamask/account-api';\nimport type { HdKeyring } from '@metamask/eth-hd-keyring';\nimport { mnemonicPhraseToBytes } from '@metamask/key-tree';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport { areUint8ArraysEqual } from '@metamask/utils';\n\nimport type { MultichainAccountGroup } from './MultichainAccountGroup';\nimport { MultichainAccountWallet } from './MultichainAccountWallet';\nimport type { NamedAccountProvider } from './providers';\nimport {\n AccountProviderWrapper,\n isAccountProviderWrapper,\n} from './providers/AccountProviderWrapper';\nimport { EvmAccountProvider } from './providers/EvmAccountProvider';\nimport { SolAccountProvider } from './providers/SolAccountProvider';\nimport type { MultichainAccountServiceMessenger } from './types';\n\nexport const serviceName = 'MultichainAccountService';\n\n/**\n * The options that {@link MultichainAccountService} takes.\n */\ntype MultichainAccountServiceOptions = {\n messenger: MultichainAccountServiceMessenger;\n providers?: NamedAccountProvider[];\n};\n\n/** Reverse mapping object used to map account IDs and their wallet/multichain account. */\ntype AccountContext<Account extends Bip44Account<KeyringAccount>> = {\n wallet: MultichainAccountWallet<Account>;\n group: MultichainAccountGroup<Account>;\n};\n\n/**\n * Service to expose multichain accounts capabilities.\n */\nexport class MultichainAccountService {\n readonly #messenger: MultichainAccountServiceMessenger;\n\n readonly #providers: NamedAccountProvider[];\n\n readonly #wallets: Map<\n MultichainAccountWalletId,\n MultichainAccountWallet<Bip44Account<KeyringAccount>>\n >;\n\n readonly #accountIdToContext: Map<\n Bip44Account<KeyringAccount>['id'],\n AccountContext<Bip44Account<KeyringAccount>>\n >;\n\n /**\n * The name of the service.\n */\n name: typeof serviceName = serviceName;\n\n /**\n * Constructs a new MultichainAccountService.\n *\n * @param options - The options.\n * @param options.messenger - The messenger suited to this\n * MultichainAccountService.\n * @param options.providers - Optional list of account\n * providers.\n */\n constructor({ messenger, providers = [] }: MultichainAccountServiceOptions) {\n this.#messenger = messenger;\n this.#wallets = new Map();\n this.#accountIdToContext = new Map();\n\n // TODO: Rely on keyring capabilities once the keyring API is used by all keyrings.\n this.#providers = [\n new EvmAccountProvider(this.#messenger),\n new AccountProviderWrapper(\n this.#messenger,\n new SolAccountProvider(this.#messenger),\n ),\n // Custom account providers that can be provided by the MetaMask client.\n ...providers,\n ];\n\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountGroup',\n (...args) => this.getMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountGroups',\n (...args) => this.getMultichainAccountGroups(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountWallet',\n (...args) => this.getMultichainAccountWallet(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:getMultichainAccountWallets',\n (...args) => this.getMultichainAccountWallets(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:createNextMultichainAccountGroup',\n (...args) => this.createNextMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:createMultichainAccountGroup',\n (...args) => this.createMultichainAccountGroup(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:setBasicFunctionality',\n (...args) => this.setBasicFunctionality(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:alignWallets',\n (...args) => this.alignWallets(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:alignWallet',\n (...args) => this.alignWallet(...args),\n );\n this.#messenger.registerActionHandler(\n 'MultichainAccountService:createMultichainAccountWallet',\n (...args) => this.createMultichainAccountWallet(...args),\n );\n\n this.#messenger.subscribe('AccountsController:accountAdded', (account) =>\n this.#handleOnAccountAdded(account),\n );\n this.#messenger.subscribe('AccountsController:accountRemoved', (id) =>\n this.#handleOnAccountRemoved(id),\n );\n }\n\n /**\n * Initialize the service and constructs the internal reprensentation of\n * multichain accounts and wallets.\n */\n init(): void {\n this.#wallets.clear();\n this.#accountIdToContext.clear();\n\n // Create initial wallets.\n const { keyrings } = this.#messenger.call('KeyringController:getState');\n for (const keyring of keyrings) {\n if (keyring.type === (KeyringTypes.hd as string)) {\n // Only HD keyrings have an entropy source/SRP.\n const entropySource = keyring.metadata.id;\n\n // This will automatically \"associate\" all multichain accounts for that wallet\n // (based on the accounts owned by each account providers).\n const wallet = new MultichainAccountWallet({\n entropySource,\n providers: this.#providers,\n messenger: this.#messenger,\n });\n this.#wallets.set(wallet.id, wallet);\n\n // Reverse mapping between account ID and their multichain wallet/account:\n for (const group of wallet.getMultichainAccountGroups()) {\n for (const account of group.getAccounts()) {\n this.#accountIdToContext.set(account.id, {\n wallet,\n group,\n });\n }\n }\n }\n }\n }\n\n #handleOnAccountAdded(account: KeyringAccount): void {\n // We completely omit non-BIP-44 accounts!\n if (!isBip44Account(account)) {\n return;\n }\n\n let sync = true;\n\n let wallet = this.#wallets.get(\n toMultichainAccountWalletId(account.options.entropy.id),\n );\n if (!wallet) {\n // That's a new wallet.\n wallet = new MultichainAccountWallet({\n entropySource: account.options.entropy.id,\n providers: this.#providers,\n messenger: this.#messenger,\n });\n this.#wallets.set(wallet.id, wallet);\n\n // If that's a new wallet wallet. There's nothing to \"force-sync\".\n sync = false;\n }\n\n let group = wallet.getMultichainAccountGroup(\n account.options.entropy.groupIndex,\n );\n if (!group) {\n // This new account is a new multichain account, let the wallet know\n // it has to re-sync with its providers.\n if (sync) {\n wallet.sync();\n }\n\n group = wallet.getMultichainAccountGroup(\n account.options.entropy.groupIndex,\n );\n\n // If that's a new multichain account. There's nothing to \"force-sync\".\n sync = false;\n }\n\n // We have to check against `undefined` in case `getMultichainAccount` is\n // not able to find this multichain account (which should not be possible...)\n if (group) {\n if (sync) {\n group.sync();\n }\n\n // Same here, this account should have been already grouped in that\n // multichain account.\n this.#accountIdToContext.set(account.id, {\n wallet,\n group,\n });\n }\n }\n\n #handleOnAccountRemoved(id: KeyringAccount['id']): void {\n // Force sync of the appropriate wallet if an account got removed.\n const found = this.#accountIdToContext.get(id);\n if (found) {\n const { wallet } = found;\n\n wallet.sync();\n }\n\n // Safe to call delete even if the `id` was not referencing a BIP-44 account.\n this.#accountIdToContext.delete(id);\n }\n\n #getWallet(\n entropySource: EntropySourceId,\n ): MultichainAccountWallet<Bip44Account<KeyringAccount>> {\n const wallet = this.#wallets.get(\n toMultichainAccountWalletId(entropySource),\n );\n\n if (!wallet) {\n throw new Error('Unknown wallet, no wallet matching this entropy source');\n }\n\n return wallet;\n }\n\n /**\n * Gets the account's context which contains its multichain wallet and\n * multichain account group references.\n *\n * @param id - Account ID.\n * @returns The account context if any, undefined otherwise.\n */\n getAccountContext(\n id: KeyringAccount['id'],\n ): AccountContext<Bip44Account<KeyringAccount>> | undefined {\n return this.#accountIdToContext.get(id);\n }\n\n /**\n * Gets a reference to the multichain account wallet matching this entropy source.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source of the multichain account.\n * @throws If none multichain account match this entropy.\n * @returns A reference to the multichain account wallet.\n */\n getMultichainAccountWallet({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): MultichainAccountWallet<Bip44Account<KeyringAccount>> {\n return this.#getWallet(entropySource);\n }\n\n /**\n * Gets an array of all multichain account wallets.\n *\n * @returns An array of all multichain account wallets.\n */\n getMultichainAccountWallets(): MultichainAccountWallet<\n Bip44Account<KeyringAccount>\n >[] {\n return Array.from(this.#wallets.values());\n }\n\n /**\n * Creates a new multichain account wallet with the given mnemonic.\n *\n * NOTE: This method should only be called in client code where a mutex lock is acquired.\n * `discoverAndCreateAccounts` should be called after this method to discover and create accounts.\n *\n * @param options - Options.\n * @param options.mnemonic - The mnemonic to use to create the new wallet.\n * @throws If the mnemonic has already been imported.\n * @returns The new multichain account wallet.\n */\n async createMultichainAccountWallet({\n mnemonic,\n }: {\n mnemonic: string;\n }): Promise<MultichainAccountWallet<Bip44Account<KeyringAccount>>> {\n const existingKeyrings = this.#messenger.call(\n 'KeyringController:getKeyringsByType',\n KeyringTypes.hd,\n ) as HdKeyring[];\n\n const mnemonicAsBytes = mnemonicPhraseToBytes(mnemonic);\n\n const alreadyHasImportedSrp = existingKeyrings.some((keyring) => {\n if (!keyring.mnemonic) {\n return false;\n }\n return areUint8ArraysEqual(keyring.mnemonic, mnemonicAsBytes);\n });\n\n if (alreadyHasImportedSrp) {\n throw new Error('This Secret Recovery Phrase has already been imported.');\n }\n\n const result = await this.#messenger.call(\n 'KeyringController:addNewKeyring',\n KeyringTypes.hd,\n { mnemonic },\n );\n\n const wallet = new MultichainAccountWallet({\n providers: this.#providers,\n entropySource: result.id,\n messenger: this.#messenger,\n });\n\n this.#wallets.set(wallet.id, wallet);\n\n return wallet;\n }\n\n /**\n * Gets a reference to the multichain account group matching this entropy source\n * and a group index.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source of the multichain account.\n * @param options.groupIndex - The group index of the multichain account.\n * @throws If none multichain account match this entropy source and group index.\n * @returns A reference to the multichain account.\n */\n getMultichainAccountGroup({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): MultichainAccountGroup<Bip44Account<KeyringAccount>> {\n const multichainAccount =\n this.#getWallet(entropySource).getMultichainAccountGroup(groupIndex);\n\n if (!multichainAccount) {\n throw new Error(`No multichain account for index: ${groupIndex}`);\n }\n\n return multichainAccount;\n }\n\n /**\n * Gets all multichain account groups for a given entropy source.\n *\n * @param options - Options.\n * @param options.entropySource - The entropy source to query.\n * @throws If no multichain accounts match this entropy source.\n * @returns A list of all multichain accounts.\n */\n getMultichainAccountGroups({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): MultichainAccountGroup<Bip44Account<KeyringAccount>>[] {\n return this.#getWallet(entropySource).getMultichainAccountGroups();\n }\n\n /**\n * Creates the next multichain account group.\n *\n * @param options - Options.\n * @param options.entropySource - The wallet's entropy source.\n * @returns The next multichain account group.\n */\n async createNextMultichainAccountGroup({\n entropySource,\n }: {\n entropySource: EntropySourceId;\n }): Promise<MultichainAccountGroup<Bip44Account<KeyringAccount>>> {\n return await this.#getWallet(\n entropySource,\n ).createNextMultichainAccountGroup();\n }\n\n /**\n * Creates a multichain account group.\n *\n * @param options - Options.\n * @param options.groupIndex - The group index to use.\n * @param options.entropySource - The wallet's entropy source.\n * @returns The multichain account group for this group index.\n */\n async createMultichainAccountGroup({\n groupIndex,\n entropySource,\n }: {\n groupIndex: number;\n entropySource: EntropySourceId;\n }): Promise<MultichainAccountGroup<Bip44Account<KeyringAccount>>> {\n return await this.#getWallet(entropySource).createMultichainAccountGroup(\n groupIndex,\n );\n }\n\n /**\n * Set basic functionality state and trigger alignment if enabled.\n * When basic functionality is disabled, snap-based providers are disabled.\n * When enabled, all snap providers are enabled and wallet alignment is triggered.\n * EVM providers are never disabled as they're required for basic wallet functionality.\n *\n * @param enabled - Whether basic functionality is enabled.\n */\n async setBasicFunctionality(enabled: boolean): Promise<void> {\n // Loop through providers and enable/disable only wrapped ones when basic functionality changes\n for (const provider of this.#providers) {\n if (isAccountProviderWrapper(provider)) {\n provider.setEnabled(enabled);\n }\n // Regular providers (like EVM) are never disabled for basic functionality\n }\n\n // Trigger alignment only when basic functionality is enabled\n if (enabled) {\n await this.alignWallets();\n }\n }\n\n /**\n * Align all multichain account wallets.\n */\n async alignWallets(): Promise<void> {\n const wallets = this.getMultichainAccountWallets();\n await Promise.all(wallets.map((w) => w.alignAccounts()));\n }\n\n /**\n * Align a specific multichain account wallet.\n *\n * @param entropySource - The entropy source of the multichain account wallet.\n */\n async alignWallet(entropySource: EntropySourceId): Promise<void> {\n const wallet = this.getMultichainAccountWallet({ entropySource });\n await wallet.alignAccounts();\n }\n}\n"]}
|
|
@@ -4,7 +4,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
4
4
|
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");
|
|
5
5
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
6
6
|
};
|
|
7
|
-
var _EvmAccountProvider_instances, _EvmAccountProvider_createAccount;
|
|
7
|
+
var _EvmAccountProvider_instances, _EvmAccountProvider_createAccount, _EvmAccountProvider_getTransactionCount, _EvmAccountProvider_withRetry, _EvmAccountProvider_withTimeout;
|
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
9
|
exports.EvmAccountProvider = void 0;
|
|
10
10
|
const keyring_api_1 = require("@metamask/keyring-api");
|
|
@@ -75,11 +75,7 @@ class EvmAccountProvider extends BaseBip44AccountProvider_1.BaseBip44AccountProv
|
|
|
75
75
|
// We don't want to remove the account if it's the first one.
|
|
76
76
|
const shouldCleanup = didCreate && groupIndex !== 0;
|
|
77
77
|
try {
|
|
78
|
-
const
|
|
79
|
-
method: 'eth_getTransactionCount',
|
|
80
|
-
params: [address, 'latest'],
|
|
81
|
-
}));
|
|
82
|
-
const count = parseInt(countHex, 16);
|
|
78
|
+
const count = await __classPrivateFieldGet(this, _EvmAccountProvider_instances, "m", _EvmAccountProvider_getTransactionCount).call(this, provider, address);
|
|
83
79
|
if (count === 0 && shouldCleanup) {
|
|
84
80
|
await this.withKeyring({ id: entropySource }, async ({ keyring }) => {
|
|
85
81
|
keyring.removeAccount?.(address);
|
|
@@ -118,5 +114,63 @@ _EvmAccountProvider_instances = new WeakSet(), _EvmAccountProvider_createAccount
|
|
|
118
114
|
return [added, true];
|
|
119
115
|
});
|
|
120
116
|
return result;
|
|
117
|
+
}, _EvmAccountProvider_getTransactionCount = async function _EvmAccountProvider_getTransactionCount(provider, address) {
|
|
118
|
+
const countHex = await __classPrivateFieldGet(this, _EvmAccountProvider_instances, "m", _EvmAccountProvider_withRetry).call(this, () => __classPrivateFieldGet(this, _EvmAccountProvider_instances, "m", _EvmAccountProvider_withTimeout).call(this, provider.request({
|
|
119
|
+
method: 'eth_getTransactionCount',
|
|
120
|
+
params: [address, 'latest'],
|
|
121
|
+
})));
|
|
122
|
+
return parseInt(countHex, 16);
|
|
123
|
+
}, _EvmAccountProvider_withRetry =
|
|
124
|
+
/**
|
|
125
|
+
* Execute a function with exponential backoff on transient failures.
|
|
126
|
+
*
|
|
127
|
+
* @param fnToExecute - The function to execute.
|
|
128
|
+
* @param options - The options for the retry.
|
|
129
|
+
* @param options.maxAttempts - The maximum number of attempts.
|
|
130
|
+
* @param options.backOffMs - The backoff in milliseconds.
|
|
131
|
+
* @throws An error if the transaction count cannot be retrieved.
|
|
132
|
+
* @returns The result of the function.
|
|
133
|
+
*/
|
|
134
|
+
async function _EvmAccountProvider_withRetry(fnToExecute, { maxAttempts = 3, backOffMs = 500, } = {}) {
|
|
135
|
+
let lastError;
|
|
136
|
+
let backOff = backOffMs;
|
|
137
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
138
|
+
try {
|
|
139
|
+
return await fnToExecute();
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
lastError = error;
|
|
143
|
+
if (attempt >= maxAttempts) {
|
|
144
|
+
break;
|
|
145
|
+
}
|
|
146
|
+
const delay = backOff;
|
|
147
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
148
|
+
backOff *= 2;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
throw lastError;
|
|
152
|
+
}, _EvmAccountProvider_withTimeout =
|
|
153
|
+
/**
|
|
154
|
+
* Execute a promise with a timeout.
|
|
155
|
+
*
|
|
156
|
+
* @param promise - The promise to execute.
|
|
157
|
+
* @param timeoutMs - The timeout in milliseconds.
|
|
158
|
+
* @returns The result of the promise.
|
|
159
|
+
*/
|
|
160
|
+
async function _EvmAccountProvider_withTimeout(promise, timeoutMs = 500) {
|
|
161
|
+
let timer;
|
|
162
|
+
try {
|
|
163
|
+
return await Promise.race([
|
|
164
|
+
promise,
|
|
165
|
+
new Promise((_resolve, reject) => {
|
|
166
|
+
timer = setTimeout(() => reject(new Error('RPC request timed out')), timeoutMs);
|
|
167
|
+
}),
|
|
168
|
+
]);
|
|
169
|
+
}
|
|
170
|
+
finally {
|
|
171
|
+
if (timer) {
|
|
172
|
+
clearTimeout(timer);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
121
175
|
};
|
|
122
176
|
//# sourceMappingURL=EvmAccountProvider.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EvmAccountProvider.cjs","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;AAEA,uDAAuD;AACvD,qEAA4D;AAQ5D,6EAIoC;AAEpC,MAAM,oBAAoB,GAAG,KAAK,CAAC;AAEnC;;;;;GAKG;AACH,SAAS,2BAA2B,CAClC,OAAoC;IAEpC,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;KACpD;AACH,CAAC;AAED,MAAa,kBAAmB,SAAQ,mDAAwB;IAAhE;;;IAkJA,CAAC;IAjJC,mBAAmB,CAAC,OAAsC;QACxD,OAAO,CACL,OAAO,CAAC,IAAI,KAAK,4BAAc,CAAC,GAAG;YACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,KAAM,iCAAY,CAAC,EAAa,CAC9D,CAAC;IACJ,CAAC;IAED,OAAO;QACL,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;OAIG;IACH,cAAc;QACZ,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACzC,gDAAgD,EAChD,oBAAoB,CACrB,CAAC;QACF,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACtC,wCAAwC,EACxC,eAAe,CAChB,CAAC;QACF,OAAO,QAAQ,CAAC;IAClB,CAAC;IAgCD,KAAK,CAAC,cAAc,CAAC,EACnB,aAAa,EACb,UAAU,GAIX;QACC,MAAM,CAAC,OAAO,CAAC,GAAG,MAAM,uBAAA,IAAI,wEAAe,MAAnB,IAAI,EAAgB;YAC1C,aAAa;YACb,UAAU;YACV,UAAU,EAAE,IAAI;SACjB,CAAC,CAAC;QAEH,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,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,WAAW,CACpB,EAAE,EAAE,EAAE,aAAa,EAAE,EACrB,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;oBACpB,OAAO,CAAC,aAAa,EAAE,CAAC,OAAO,CAAC,CAAC;gBACnC,CAAC,CACF,CAAC;aACH;YACD,MAAM,KAAK,CAAC;SACb;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CACjC,wCAAwC,EACxC,OAAO,CACR,CAAC;QACF,2BAA2B,CAAC,OAAO,CAAC,CAAC;QACrC,IAAA,+CAAoB,EAAC,OAAO,CAAC,CAAC;QAC9B,OAAO,CAAC,OAAO,CAAC,CAAC;IACnB,CAAC;CACF;AAlJD,gDAkJC;mFArHC,KAAK,4CAAgB,EACnB,aAAa,EACb,UAAU,EACV,UAAU,GAAG,KAAK,GAKnB;IACC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,WAAW,CACnC,EAAE,EAAE,EAAE,aAAa,EAAE,EACrB,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;QACpB,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,WAAW,EAAE,CAAC;QAC7C,IAAI,UAAU,GAAG,QAAQ,CAAC,MAAM,EAAE;YAChC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,KAAK,CAAC,CAAC;SACtC;QAED,0EAA0E;QAC1E,IAAI,UAAU,IAAI,UAAU,KAAK,QAAQ,CAAC,MAAM,EAAE;YAChD,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;SACvD;QAED,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;QAC7C,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACvB,CAAC,CACF,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { Bip44Account } from '@metamask/account-api';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport { EthAccountType } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type {\n EthKeyring,\n InternalAccount,\n} from '@metamask/keyring-internal-api';\nimport type { Provider } from '@metamask/network-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport {\n assertAreBip44Accounts,\n assertIsBip44Account,\n BaseBip44AccountProvider,\n} from './BaseBip44AccountProvider';\n\nconst ETH_MAINNET_CHAIN_ID = '0x1';\n\n/**\n * Asserts an internal account exists.\n *\n * @param account - The internal account to check.\n * @throws An error if the internal account does not exist.\n */\nfunction assertInternalAccountExists(\n account: InternalAccount | undefined,\n): asserts account is InternalAccount {\n if (!account) {\n throw new Error('Internal account does not exist');\n }\n}\n\nexport class EvmAccountProvider extends BaseBip44AccountProvider {\n isAccountCompatible(account: Bip44Account<InternalAccount>): boolean {\n return (\n account.type === EthAccountType.Eoa &&\n account.metadata.keyring.type === (KeyringTypes.hd as string)\n );\n }\n\n getName(): string {\n return 'EVM';\n }\n\n /**\n * Get the EVM provider.\n *\n * @returns The EVM provider.\n */\n getEvmProvider(): Provider {\n const networkClientId = this.messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n ETH_MAINNET_CHAIN_ID,\n );\n const { provider } = this.messenger.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n return provider;\n }\n\n async #createAccount({\n entropySource,\n groupIndex,\n throwOnGap = false,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n throwOnGap?: boolean;\n }): Promise<[Hex, boolean]> {\n const result = await this.withKeyring<EthKeyring, [Hex, boolean]>(\n { id: entropySource },\n async ({ keyring }) => {\n const existing = await keyring.getAccounts();\n if (groupIndex < existing.length) {\n return [existing[groupIndex], false];\n }\n\n // If the throwOnGap flag is set, we throw an error to prevent index gaps.\n if (throwOnGap && groupIndex !== existing.length) {\n throw new Error('Trying to create too many accounts');\n }\n\n const [added] = await keyring.addAccounts(1);\n return [added, true];\n },\n );\n\n return result;\n }\n\n async createAccounts({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]> {\n const [address] = await this.#createAccount({\n entropySource,\n groupIndex,\n throwOnGap: true,\n });\n\n const account = this.messenger.call(\n 'AccountsController:getAccountByAddress',\n address,\n );\n\n // We MUST have the associated internal account.\n assertInternalAccountExists(account);\n\n const accountsArray = [account];\n assertAreBip44Accounts(accountsArray);\n\n return accountsArray;\n }\n\n /**\n * Discover and create accounts for the EVM provider.\n *\n * @param opts - The options for the discovery and creation of accounts.\n * @param opts.entropySource - The entropy source to use for the discovery and creation of accounts.\n * @param opts.groupIndex - The index of the group to create the accounts for.\n * @returns The accounts for the EVM provider.\n */\n async discoverAccounts(opts: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]> {\n const provider = this.getEvmProvider();\n const { entropySource, groupIndex } = opts;\n\n const [address, didCreate] = await this.#createAccount({\n entropySource,\n groupIndex,\n });\n\n // We don't want to remove the account if it's the first one.\n const shouldCleanup = didCreate && groupIndex !== 0;\n try {\n const countHex = (await provider.request({\n method: 'eth_getTransactionCount',\n params: [address, 'latest'],\n })) as Hex;\n const count = parseInt(countHex, 16);\n\n if (count === 0 && shouldCleanup) {\n await this.withKeyring<EthKeyring>(\n { id: entropySource },\n async ({ keyring }) => {\n keyring.removeAccount?.(address);\n },\n );\n return [];\n }\n } catch (error) {\n // If the RPC request fails and we just created this account for discovery,\n // remove it to avoid leaving a dangling account.\n if (shouldCleanup) {\n await this.withKeyring<EthKeyring>(\n { id: entropySource },\n async ({ keyring }) => {\n keyring.removeAccount?.(address);\n },\n );\n }\n throw error;\n }\n\n const account = this.messenger.call(\n 'AccountsController:getAccountByAddress',\n address,\n );\n assertInternalAccountExists(account);\n assertIsBip44Account(account);\n return [account];\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"EvmAccountProvider.cjs","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"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AAC;AA2DD;;;;;;;;;GASG;AACH,KAAK,wCACH,WAA6B,EAC7B,EACE,WAAW,GAAG,CAAC,EACf,SAAS,GAAG,GAAG,MACiC,EAAE;IAEpD,IAAI,SAAS,CAAC;IACd,IAAI,OAAO,GAAG,SAAS,CAAC;IACxB,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,WAAW,EAAE,OAAO,EAAE,EAAE;QACvD,IAAI;YACF,OAAO,MAAM,WAAW,EAAE,CAAC;SAC5B;QAAC,OAAO,KAAK,EAAE;YACd,SAAS,GAAG,KAAK,CAAC;YAClB,IAAI,OAAO,IAAI,WAAW,EAAE;gBAC1B,MAAM;aACP;YACD,MAAM,KAAK,GAAG,OAAO,CAAC;YACtB,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;YAC3D,OAAO,IAAI,CAAC,CAAC;SACd;KACF;IACD,MAAM,SAAS,CAAC;AAClB,CAAC;AAED;;;;;;GAMG;AACH,KAAK,0CACH,OAAmB,EACnB,YAAoB,GAAG;IAEvB,IAAI,KAAK,CAAC;IACV,IAAI;QACF,OAAO,MAAM,OAAO,CAAC,IAAI,CAAI;YAC3B,OAAO;YACP,IAAI,OAAO,CAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE;gBAClC,KAAK,GAAG,UAAU,CAChB,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC,EAChD,SAAS,CACV,CAAC;YACJ,CAAC,CAAC;SACH,CAAC,CAAC;KACJ;YAAS;QACR,IAAI,KAAK,EAAE;YACT,YAAY,CAAC,KAAK,CAAC,CAAC;SACrB;KACF;AACH,CAAC","sourcesContent":["import type { Bip44Account } from '@metamask/account-api';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport { EthAccountType } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type {\n EthKeyring,\n InternalAccount,\n} from '@metamask/keyring-internal-api';\nimport type { Provider } from '@metamask/network-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport {\n assertAreBip44Accounts,\n assertIsBip44Account,\n BaseBip44AccountProvider,\n} from './BaseBip44AccountProvider';\n\nconst ETH_MAINNET_CHAIN_ID = '0x1';\n\n/**\n * Asserts an internal account exists.\n *\n * @param account - The internal account to check.\n * @throws An error if the internal account does not exist.\n */\nfunction assertInternalAccountExists(\n account: InternalAccount | undefined,\n): asserts account is InternalAccount {\n if (!account) {\n throw new Error('Internal account does not exist');\n }\n}\n\nexport class EvmAccountProvider extends BaseBip44AccountProvider {\n isAccountCompatible(account: Bip44Account<InternalAccount>): boolean {\n return (\n account.type === EthAccountType.Eoa &&\n account.metadata.keyring.type === (KeyringTypes.hd as string)\n );\n }\n\n getName(): string {\n return 'EVM';\n }\n\n /**\n * Get the EVM provider.\n *\n * @returns The EVM provider.\n */\n getEvmProvider(): Provider {\n const networkClientId = this.messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n ETH_MAINNET_CHAIN_ID,\n );\n const { provider } = this.messenger.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n return provider;\n }\n\n async #createAccount({\n entropySource,\n groupIndex,\n throwOnGap = false,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n throwOnGap?: boolean;\n }): Promise<[Hex, boolean]> {\n const result = await this.withKeyring<EthKeyring, [Hex, boolean]>(\n { id: entropySource },\n async ({ keyring }) => {\n const existing = await keyring.getAccounts();\n if (groupIndex < existing.length) {\n return [existing[groupIndex], false];\n }\n\n // If the throwOnGap flag is set, we throw an error to prevent index gaps.\n if (throwOnGap && groupIndex !== existing.length) {\n throw new Error('Trying to create too many accounts');\n }\n\n const [added] = await keyring.addAccounts(1);\n return [added, true];\n },\n );\n\n return result;\n }\n\n async createAccounts({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]> {\n const [address] = await this.#createAccount({\n entropySource,\n groupIndex,\n throwOnGap: true,\n });\n\n const account = this.messenger.call(\n 'AccountsController:getAccountByAddress',\n address,\n );\n\n // We MUST have the associated internal account.\n assertInternalAccountExists(account);\n\n const accountsArray = [account];\n assertAreBip44Accounts(accountsArray);\n\n return accountsArray;\n }\n\n async #getTransactionCount(\n provider: Provider,\n address: Hex,\n ): Promise<number> {\n const countHex = await this.#withRetry<Hex>(() =>\n this.#withTimeout(\n provider.request({\n method: 'eth_getTransactionCount',\n params: [address, 'latest'],\n }),\n ),\n );\n\n return parseInt(countHex, 16);\n }\n\n /**\n * Discover and create accounts for the EVM provider.\n *\n * @param opts - The options for the discovery and creation of accounts.\n * @param opts.entropySource - The entropy source to use for the discovery and creation of accounts.\n * @param opts.groupIndex - The index of the group to create the accounts for.\n * @returns The accounts for the EVM provider.\n */\n async discoverAccounts(opts: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]> {\n const provider = this.getEvmProvider();\n const { entropySource, groupIndex } = opts;\n\n const [address, didCreate] = await this.#createAccount({\n entropySource,\n groupIndex,\n });\n\n // We don't want to remove the account if it's the first one.\n const shouldCleanup = didCreate && groupIndex !== 0;\n try {\n const count = await this.#getTransactionCount(provider, address);\n\n if (count === 0 && shouldCleanup) {\n await this.withKeyring<EthKeyring>(\n { id: entropySource },\n async ({ keyring }) => {\n keyring.removeAccount?.(address);\n },\n );\n return [];\n }\n } catch (error) {\n // If the RPC request fails and we just created this account for discovery,\n // remove it to avoid leaving a dangling account.\n if (shouldCleanup) {\n await this.withKeyring<EthKeyring>(\n { id: entropySource },\n async ({ keyring }) => {\n keyring.removeAccount?.(address);\n },\n );\n }\n throw error;\n }\n\n const account = this.messenger.call(\n 'AccountsController:getAccountByAddress',\n address,\n );\n assertInternalAccountExists(account);\n assertIsBip44Account(account);\n return [account];\n }\n\n /**\n * Execute a function with exponential backoff on transient failures.\n *\n * @param fnToExecute - The function to execute.\n * @param options - The options for the retry.\n * @param options.maxAttempts - The maximum number of attempts.\n * @param options.backOffMs - The backoff in milliseconds.\n * @throws An error if the transaction count cannot be retrieved.\n * @returns The result of the function.\n */\n async #withRetry<T>(\n fnToExecute: () => Promise<T>,\n {\n maxAttempts = 3,\n backOffMs = 500,\n }: { maxAttempts?: number; backOffMs?: number } = {},\n ): Promise<T> {\n let lastError;\n let backOff = backOffMs;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fnToExecute();\n } catch (error) {\n lastError = error;\n if (attempt >= maxAttempts) {\n break;\n }\n const delay = backOff;\n await new Promise((resolve) => setTimeout(resolve, delay));\n backOff *= 2;\n }\n }\n throw lastError;\n }\n\n /**\n * Execute a promise with a timeout.\n *\n * @param promise - The promise to execute.\n * @param timeoutMs - The timeout in milliseconds.\n * @returns The result of the promise.\n */\n async #withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number = 500,\n ): Promise<T> {\n let timer;\n try {\n return await Promise.race<T>([\n promise,\n new Promise<T>((_resolve, reject) => {\n timer = setTimeout(\n () => reject(new Error('RPC request timed out')),\n timeoutMs,\n );\n }),\n ]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EvmAccountProvider.d.cts","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,8BAA8B;AAC1D,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,8BAA8B;AAG7E,OAAO,KAAK,EAEV,eAAe,EAChB,uCAAuC;AACxC,OAAO,KAAK,EAAE,QAAQ,EAAE,qCAAqC;AAG7D,OAAO,EAGL,wBAAwB,EACzB,uCAAmC;AAkBpC,qBAAa,kBAAmB,SAAQ,wBAAwB;;IAC9D,mBAAmB,CAAC,OAAO,EAAE,YAAY,CAAC,eAAe,CAAC,GAAG,OAAO;IAOpE,OAAO,IAAI,MAAM;IAIjB;;;;OAIG;IACH,cAAc,IAAI,QAAQ;IA0CpB,cAAc,CAAC,EACnB,aAAa,EACb,UAAU,GACX,EAAE;QACD,aAAa,EAAE,eAAe,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"EvmAccountProvider.d.cts","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,8BAA8B;AAC1D,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,8BAA8B;AAG7E,OAAO,KAAK,EAEV,eAAe,EAChB,uCAAuC;AACxC,OAAO,KAAK,EAAE,QAAQ,EAAE,qCAAqC;AAG7D,OAAO,EAGL,wBAAwB,EACzB,uCAAmC;AAkBpC,qBAAa,kBAAmB,SAAQ,wBAAwB;;IAC9D,mBAAmB,CAAC,OAAO,EAAE,YAAY,CAAC,eAAe,CAAC,GAAG,OAAO;IAOpE,OAAO,IAAI,MAAM;IAIjB;;;;OAIG;IACH,cAAc,IAAI,QAAQ;IA0CpB,cAAc,CAAC,EACnB,aAAa,EACb,UAAU,GACX,EAAE;QACD,aAAa,EAAE,eAAe,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;IAqC3C;;;;;;;OAOG;IACG,gBAAgB,CAAC,IAAI,EAAE;QAC3B,aAAa,EAAE,eAAe,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;CA6G5C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EvmAccountProvider.d.mts","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.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