@metamask/multichain-account-service 10.0.3 → 11.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +43 -2
  2. package/dist/MultichainAccountGroup.cjs +15 -0
  3. package/dist/MultichainAccountGroup.cjs.map +1 -1
  4. package/dist/MultichainAccountGroup.d.cts +10 -0
  5. package/dist/MultichainAccountGroup.d.cts.map +1 -1
  6. package/dist/MultichainAccountGroup.d.mts +10 -0
  7. package/dist/MultichainAccountGroup.d.mts.map +1 -1
  8. package/dist/MultichainAccountGroup.mjs +15 -0
  9. package/dist/MultichainAccountGroup.mjs.map +1 -1
  10. package/dist/MultichainAccountService-method-action-types.cjs.map +1 -1
  11. package/dist/MultichainAccountService-method-action-types.d.cts +10 -6
  12. package/dist/MultichainAccountService-method-action-types.d.cts.map +1 -1
  13. package/dist/MultichainAccountService-method-action-types.d.mts +10 -6
  14. package/dist/MultichainAccountService-method-action-types.d.mts.map +1 -1
  15. package/dist/MultichainAccountService-method-action-types.mjs.map +1 -1
  16. package/dist/MultichainAccountService.cjs +67 -8
  17. package/dist/MultichainAccountService.cjs.map +1 -1
  18. package/dist/MultichainAccountService.d.cts +31 -7
  19. package/dist/MultichainAccountService.d.cts.map +1 -1
  20. package/dist/MultichainAccountService.d.mts +31 -7
  21. package/dist/MultichainAccountService.d.mts.map +1 -1
  22. package/dist/MultichainAccountService.mjs +67 -8
  23. package/dist/MultichainAccountService.mjs.map +1 -1
  24. package/dist/MultichainAccountWallet.cjs +20 -0
  25. package/dist/MultichainAccountWallet.cjs.map +1 -1
  26. package/dist/MultichainAccountWallet.d.cts +10 -0
  27. package/dist/MultichainAccountWallet.d.cts.map +1 -1
  28. package/dist/MultichainAccountWallet.d.mts +10 -0
  29. package/dist/MultichainAccountWallet.d.mts.map +1 -1
  30. package/dist/MultichainAccountWallet.mjs +20 -0
  31. package/dist/MultichainAccountWallet.mjs.map +1 -1
  32. package/dist/index.cjs +3 -1
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +1 -1
  35. package/dist/index.d.cts.map +1 -1
  36. package/dist/index.d.mts +1 -1
  37. package/dist/index.d.mts.map +1 -1
  38. package/dist/index.mjs +1 -1
  39. package/dist/index.mjs.map +1 -1
  40. package/dist/providers/AccountProviderWrapper.cjs +43 -0
  41. package/dist/providers/AccountProviderWrapper.cjs.map +1 -1
  42. package/dist/providers/AccountProviderWrapper.d.cts +37 -0
  43. package/dist/providers/AccountProviderWrapper.d.cts.map +1 -1
  44. package/dist/providers/AccountProviderWrapper.d.mts +37 -0
  45. package/dist/providers/AccountProviderWrapper.d.mts.map +1 -1
  46. package/dist/providers/AccountProviderWrapper.mjs +43 -0
  47. package/dist/providers/AccountProviderWrapper.mjs.map +1 -1
  48. package/dist/providers/BaseBip44AccountProvider.cjs +3 -18
  49. package/dist/providers/BaseBip44AccountProvider.cjs.map +1 -1
  50. package/dist/providers/BaseBip44AccountProvider.d.cts +36 -16
  51. package/dist/providers/BaseBip44AccountProvider.d.cts.map +1 -1
  52. package/dist/providers/BaseBip44AccountProvider.d.mts +36 -16
  53. package/dist/providers/BaseBip44AccountProvider.d.mts.map +1 -1
  54. package/dist/providers/BaseBip44AccountProvider.mjs +3 -18
  55. package/dist/providers/BaseBip44AccountProvider.mjs.map +1 -1
  56. package/dist/providers/EvmAccountProvider.cjs +19 -0
  57. package/dist/providers/EvmAccountProvider.cjs.map +1 -1
  58. package/dist/providers/EvmAccountProvider.d.cts +12 -0
  59. package/dist/providers/EvmAccountProvider.d.cts.map +1 -1
  60. package/dist/providers/EvmAccountProvider.d.mts +12 -0
  61. package/dist/providers/EvmAccountProvider.d.mts.map +1 -1
  62. package/dist/providers/EvmAccountProvider.mjs +19 -0
  63. package/dist/providers/EvmAccountProvider.mjs.map +1 -1
  64. package/dist/providers/SnapAccountProvider.cjs +28 -11
  65. package/dist/providers/SnapAccountProvider.cjs.map +1 -1
  66. package/dist/providers/SnapAccountProvider.d.cts +16 -4
  67. package/dist/providers/SnapAccountProvider.d.cts.map +1 -1
  68. package/dist/providers/SnapAccountProvider.d.mts +16 -4
  69. package/dist/providers/SnapAccountProvider.d.mts.map +1 -1
  70. package/dist/providers/SnapAccountProvider.mjs +28 -11
  71. package/dist/providers/SnapAccountProvider.mjs.map +1 -1
  72. package/dist/providers/XlmAccountProvider.cjs +83 -0
  73. package/dist/providers/XlmAccountProvider.cjs.map +1 -0
  74. package/dist/providers/XlmAccountProvider.d.cts +29 -0
  75. package/dist/providers/XlmAccountProvider.d.cts.map +1 -0
  76. package/dist/providers/XlmAccountProvider.d.mts +29 -0
  77. package/dist/providers/XlmAccountProvider.d.mts.map +1 -0
  78. package/dist/providers/XlmAccountProvider.mjs +79 -0
  79. package/dist/providers/XlmAccountProvider.mjs.map +1 -0
  80. package/dist/providers/index.cjs +1 -0
  81. package/dist/providers/index.cjs.map +1 -1
  82. package/dist/providers/index.d.cts +1 -0
  83. package/dist/providers/index.d.cts.map +1 -1
  84. package/dist/providers/index.d.mts +1 -0
  85. package/dist/providers/index.d.mts.map +1 -1
  86. package/dist/providers/index.mjs +1 -0
  87. package/dist/providers/index.mjs.map +1 -1
  88. package/dist/tests/accounts.cjs +29 -1
  89. package/dist/tests/accounts.cjs.map +1 -1
  90. package/dist/tests/accounts.d.cts +2 -0
  91. package/dist/tests/accounts.d.cts.map +1 -1
  92. package/dist/tests/accounts.d.mts +2 -0
  93. package/dist/tests/accounts.d.mts.map +1 -1
  94. package/dist/tests/accounts.mjs +29 -1
  95. package/dist/tests/accounts.mjs.map +1 -1
  96. package/dist/tests/providers.cjs +5 -0
  97. package/dist/tests/providers.cjs.map +1 -1
  98. package/dist/tests/providers.d.cts +2 -0
  99. package/dist/tests/providers.d.cts.map +1 -1
  100. package/dist/tests/providers.d.mts +2 -0
  101. package/dist/tests/providers.d.mts.map +1 -1
  102. package/dist/tests/providers.mjs +6 -1
  103. package/dist/tests/providers.mjs.map +1 -1
  104. package/dist/utils.cjs.map +1 -1
  105. package/dist/utils.d.cts +14 -1
  106. package/dist/utils.d.cts.map +1 -1
  107. package/dist/utils.d.mts +14 -1
  108. package/dist/utils.d.mts.map +1 -1
  109. package/dist/utils.mjs.map +1 -1
  110. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"BaseBip44AccountProvider.d.cts","sourceRoot":"","sources":["../../src/providers/BaseBip44AccountProvider.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,8BAA8B;AAC3E,OAAO,KAAK,EACV,oBAAoB,EACpB,eAAe,EACf,cAAc,EACf,8BAA8B;AAC/B,OAAO,KAAK,EACV,OAAO,IAAI,SAAS,EACpB,mBAAmB,EACpB,iCAAiC;AAClC,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,iBAAiB,EAClB,qCAAqC;AACtC,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AAEtE,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAiB;AAElE;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,OAAO,IAAI,YAAY,CAAC,cAAc,CAAC,CAIjD;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,cAAc,EAAE,GACzB,OAAO,CAAC,QAAQ,IAAI,YAAY,CAAC,cAAc,CAAC,EAAE,CAEpD;AAED,MAAM,MAAM,oBAAoB,CAC9B,OAAO,SAAS,YAAY,CAAC,cAAc,CAAC,GAAG,YAAY,CAAC,cAAc,CAAC,IACzE,eAAe,CAAC,OAAO,CAAC,GAAG;IAC7B;;;;OAIG;IACH,IAAI,YAAY,IAAI,mBAAmB,CAAC;IACxC;;;;OAIG;IACH,OAAO,IAAI,MAAM,CAAC;IAClB;;;;OAIG;IACH,IAAI,CAAC,QAAQ,EAAE,YAAY,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,EAAE,GAAG,IAA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mB,CAAC,OAAO,EAAE,YAAY,CAAC,cAAc,CAAC,GAAG,OAAO;IAE5E,QAAQ,CAAC,cAAc,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;IAE1E,QAAQ,CAAC,aAAa,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAExD,QAAQ,CAAC,gBAAgB,CAAC,EACxB,aAAa,EACb,UAAU,GACX,EAAE;QACD,aAAa,EAAE,eAAe,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;CACvB"}
@@ -1,7 +1,7 @@
1
1
  import type { AccountProvider, Bip44Account } from "@metamask/account-api";
2
2
  import type { CreateAccountOptions, EntropySourceId, KeyringAccount } from "@metamask/keyring-api";
3
3
  import type { Keyring as KeyringV2, KeyringCapabilities } from "@metamask/keyring-api/v2";
4
- import type { KeyringMetadata, KeyringSelector, KeyringSelectorV2 } from "@metamask/keyring-controller";
4
+ import type { KeyringMetadata, KeyringSelectorV2 } from "@metamask/keyring-controller";
5
5
  import type { InternalAccount } from "@metamask/keyring-internal-api";
6
6
  import type { MultichainAccountServiceMessenger } from "../types.mjs";
7
7
  /**
@@ -51,6 +51,17 @@ export type Bip44AccountProvider<Account extends Bip44Account<KeyringAccount> =
51
51
  * @returns The created accounts.
52
52
  */
53
53
  createAccounts(options: CreateAccountOptions): Promise<Account[]>;
54
+ /**
55
+ * Delete an account managed by this provider.
56
+ *
57
+ * Mirrors the v2 keyring `deleteAccount(accountId)` contract. Each provider
58
+ * implementation is responsible for resolving any extra information it needs
59
+ * (e.g. address for snap-based providers) and for performing the underlying
60
+ * keyring removal.
61
+ *
62
+ * @param id - The id of the account to delete.
63
+ */
64
+ deleteAccount(id: Account['id']): Promise<void>;
54
65
  /**
55
66
  * Re-synchronize MetaMask accounts and the providers accounts if needed.
56
67
  *
@@ -59,6 +70,25 @@ export type Bip44AccountProvider<Account extends Bip44Account<KeyringAccount> =
59
70
  * in-sync and use the same accounts (and same IDs).
60
71
  */
61
72
  resyncAccounts(accounts: Bip44Account<InternalAccount>[]): Promise<void>;
73
+ /**
74
+ * Check if the provider has an aligned (i.e. present and owned) account for
75
+ * the given entropy source and group index.
76
+ *
77
+ * Callers pre-filter the relevant account IDs from the group and pass them
78
+ * in so the provider needs no messenger call.
79
+ *
80
+ * @param context - The entropy source and group index to check.
81
+ * @param context.entropySource - The entropy source to check against.
82
+ * @param context.groupIndex - The group index to check against.
83
+ * @param accountIds - Account IDs already associated with this provider for
84
+ * the given group (may be empty if no alignment has happened yet).
85
+ * @returns `true` when `accountIds` is non-empty and every ID is in the
86
+ * provider's internal accounts Set.
87
+ */
88
+ isAligned(context: {
89
+ entropySource: EntropySourceId;
90
+ groupIndex: number;
91
+ }, accountIds: Account['id'][]): boolean;
62
92
  };
63
93
  export declare abstract class BaseBip44AccountProvider<Account extends Bip44Account<KeyringAccount> = Bip44Account<KeyringAccount>> implements Bip44AccountProvider<Account> {
64
94
  #private;
@@ -87,21 +117,6 @@ export declare abstract class BaseBip44AccountProvider<Account extends Bip44Acco
87
117
  * @throws If the account is not found.
88
118
  */
89
119
  getAccount(id: Account['id']): Account;
90
- /**
91
- * Run an operation against a V1 keyring selected by `selector`.
92
- *
93
- * Forwards to `KeyringController:withKeyring`. Use this for keyrings that
94
- * have not yet migrated to the unified V2 `Keyring` interface (e.g. the
95
- * snap keyring).
96
- *
97
- * @param selector - The selector identifying the keyring.
98
- * @param operation - The operation to run with the selected keyring.
99
- * @returns The result of the operation.
100
- */
101
- protected withKeyring<SelectedKeyring, CallbackResult = void>(selector: KeyringSelector, operation: ({ keyring, metadata, }: {
102
- keyring: SelectedKeyring;
103
- metadata: KeyringMetadata;
104
- }) => Promise<CallbackResult>): Promise<CallbackResult>;
105
120
  /**
106
121
  * Run an operation against a V2 keyring selected by `selector`.
107
122
  *
@@ -117,11 +132,16 @@ export declare abstract class BaseBip44AccountProvider<Account extends Bip44Acco
117
132
  keyring: SelectedKeyring;
118
133
  metadata: KeyringMetadata;
119
134
  }) => Promise<CallbackResult>): Promise<CallbackResult>;
135
+ isAligned(_context: {
136
+ entropySource: EntropySourceId;
137
+ groupIndex: number;
138
+ }, accountIds: Account['id'][]): boolean;
120
139
  abstract get capabilities(): KeyringCapabilities;
121
140
  abstract getName(): string;
122
141
  abstract resyncAccounts(accounts: Bip44Account<InternalAccount>[]): Promise<void>;
123
142
  abstract isAccountCompatible(account: Bip44Account<KeyringAccount>): boolean;
124
143
  abstract createAccounts(options: CreateAccountOptions): Promise<Account[]>;
144
+ abstract deleteAccount(id: Account['id']): Promise<void>;
125
145
  abstract discoverAccounts({ entropySource, groupIndex, }: {
126
146
  entropySource: EntropySourceId;
127
147
  groupIndex: number;
@@ -1 +1 @@
1
- {"version":3,"file":"BaseBip44AccountProvider.d.mts","sourceRoot":"","sources":["../../src/providers/BaseBip44AccountProvider.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,8BAA8B;AAC3E,OAAO,KAAK,EACV,oBAAoB,EACpB,eAAe,EACf,cAAc,EACf,8BAA8B;AAC/B,OAAO,KAAK,EACV,OAAO,IAAI,SAAS,EACpB,mBAAmB,EACpB,iCAAiC;AAClC,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,iBAAiB,EAClB,qCAAqC;AACtC,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AAEtE,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAiB;AAElE;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,OAAO,IAAI,YAAY,CAAC,cAAc,CAAC,CAIjD;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,cAAc,EAAE,GACzB,OAAO,CAAC,QAAQ,IAAI,YAAY,CAAC,cAAc,CAAC,EAAE,CAEp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E,aAAa,EAAE,eAAe,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,EAChE,UAAU,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,GAC1B,OAAO;IAMV,QAAQ,KAAK,YAAY,IAAI,mBAAmB,CAAC;IAEjD,QAAQ,CAAC,OAAO,IAAI,MAAM;IAE1B,QAAQ,CAAC,cAAc,CACrB,QAAQ,EAAE,YAAY,CAAC,eAAe,CAAC,EAAE,GACxC,OAAO,CAAC,IAAI,CAAC;IAEhB,QAAQ,CAAC,mBAAmB,CAAC,OAAO,EAAE,YAAY,CAAC,cAAc,CAAC,GAAG,OAAO;IAE5E,QAAQ,CAAC,cAAc,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;IAE1E,QAAQ,CAAC,aAAa,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAExD,QAAQ,CAAC,gBAAgB,CAAC,EACxB,aAAa,EACb,UAAU,GACX,EAAE;QACD,aAAa,EAAE,eAAe,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;CACvB"}
@@ -70,24 +70,6 @@ export class BaseBip44AccountProvider {
70
70
  // but we know that the account is BIP-44 compatible here so it is safe to do so
71
71
  return this.messenger.call('AccountsController:getAccount', id);
72
72
  }
73
- /**
74
- * Run an operation against a V1 keyring selected by `selector`.
75
- *
76
- * Forwards to `KeyringController:withKeyring`. Use this for keyrings that
77
- * have not yet migrated to the unified V2 `Keyring` interface (e.g. the
78
- * snap keyring).
79
- *
80
- * @param selector - The selector identifying the keyring.
81
- * @param operation - The operation to run with the selected keyring.
82
- * @returns The result of the operation.
83
- */
84
- async withKeyring(selector, operation) {
85
- const result = await this.messenger.call('KeyringController:withKeyring', selector, ({ keyring, metadata }) => operation({
86
- keyring: keyring,
87
- metadata,
88
- }));
89
- return result;
90
- }
91
73
  /**
92
74
  * Run an operation against a V2 keyring selected by `selector`.
93
75
  *
@@ -106,6 +88,9 @@ export class BaseBip44AccountProvider {
106
88
  }));
107
89
  return result;
108
90
  }
91
+ isAligned(_context, accountIds) {
92
+ return (accountIds.length >= 1 && accountIds.every((id) => this.accounts.has(id)));
93
+ }
109
94
  }
110
95
  _BaseBip44AccountProvider_instances = new WeakSet(), _BaseBip44AccountProvider_getAccountIds = function _BaseBip44AccountProvider_getAccountIds() {
111
96
  return [...this.accounts];
@@ -1 +1 @@
1
- {"version":3,"file":"BaseBip44AccountProvider.mjs","sourceRoot":"","sources":["../../src/providers/BaseBip44AccountProvider.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,cAAc,EAAE,8BAA8B;AAoBvD;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAClC,OAAuB;IAEvB,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7B,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;IAC9D,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,QAA0B;IAE1B,QAAQ,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC;AACzC,CAAC;AA+CD,MAAM,OAAgB,wBAAwB;IAO5C,YAAY,SAA4C;;QAF9C,aAAQ,GAA4C,IAAI,GAAG,EAAE,CAAC;QAGtE,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;IAED;;;;;;OAMG;IACH,IAAI,CAAC,QAAyB;QAC5B,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;YAC/B,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;IAWD;;;;OAIG;IACH,WAAW;QACT,MAAM,WAAW,GAAG,uBAAA,IAAI,oFAAe,MAAnB,IAAI,CAAiB,CAAC;QAC1C,MAAM,gBAAgB,GAAG,IAAI,CA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metamask/account-api';\nimport type { AccountProvider, Bip44Account } from '@metamask/account-api';\nimport type {\n CreateAccountOptions,\n EntropySourceId,\n KeyringAccount,\n} from '@metamask/keyring-api';\nimport type {\n Keyring as KeyringV2,\n KeyringCapabilities,\n} from '@metamask/keyring-api/v2';\nimport type {\n KeyringMetadata,\n KeyringSelector,\n KeyringSelectorV2,\n} from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\n\nimport type { MultichainAccountServiceMessenger } from '../types';\n\n/**\n * Asserts a keyring account is BIP-44 compatible.\n *\n * @param account - Keyring account to check.\n * @throws If the keyring account is not compatible.\n */\nexport function assertIsBip44Account(\n account: KeyringAccount,\n): asserts account is Bip44Account<KeyringAccount> {\n if (!isBip44Account(account)) {\n throw new Error('Created account is not BIP-44 compatible');\n }\n}\n\n/**\n * Asserts that a list of keyring accounts are all BIP-44 compatible.\n *\n * @param accounts - Keyring accounts to check.\n * @throws If any of the keyring account is not compatible.\n */\nexport function assertAreBip44Accounts(\n accounts: KeyringAccount[],\n): asserts accounts is Bip44Account<KeyringAccount>[] {\n accounts.forEach(assertIsBip44Account);\n}\n\nexport type Bip44AccountProvider<\n Account extends Bip44Account<KeyringAccount> = Bip44Account<KeyringAccount>,\n> = AccountProvider<Account> & {\n /**\n * Provider capabilities, including supported scopes and BIP-44 options.\n *\n * @returns The provider capabilities.\n */\n get capabilities(): KeyringCapabilities;\n /**\n * Get the name of the provider.\n *\n * @returns The name of the provider.\n */\n getName(): string;\n /**\n * Initialize the provider with the given accounts.\n *\n * @param accounts - The accounts to initialize the provider with.\n */\n init(accounts: Bip44Account<KeyringAccount>['id'][]): void;\n /**\n * Check if the account is compatible with the provider.\n */\n isAccountCompatible(account: Bip44Account<KeyringAccount>): boolean;\n /**\n * Create accounts for the provider.\n *\n * @param options - The options for creating the accounts.\n * @param options.entropySource - The entropy source.\n * @param options.groupIndex - The group index.\n * @param options.type - The type of account creation.\n * @returns The created accounts.\n */\n createAccounts(options: CreateAccountOptions): Promise<Account[]>;\n /**\n * Re-synchronize MetaMask accounts and the providers accounts if needed.\n *\n * NOTE: This is mostly required if one of the providers (keyrings or Snaps)\n * have different sets of accounts. This method would ensure that both are\n * in-sync and use the same accounts (and same IDs).\n */\n resyncAccounts(accounts: Bip44Account<InternalAccount>[]): Promise<void>;\n};\n\nexport abstract class BaseBip44AccountProvider<\n Account extends Bip44Account<KeyringAccount> = Bip44Account<KeyringAccount>,\n> implements Bip44AccountProvider<Account> {\n protected readonly messenger: MultichainAccountServiceMessenger;\n\n protected accounts: Set<Bip44Account<KeyringAccount>['id']> = new Set();\n\n constructor(messenger: MultichainAccountServiceMessenger) {\n this.messenger = messenger;\n }\n\n /**\n * Add accounts to the provider.\n *\n * Note: There's an implicit assumption that the accounts are BIP-44 compatible.\n *\n * @param accounts - The accounts to add.\n */\n init(accounts: Account['id'][]): void {\n for (const account of accounts) {\n this.accounts.add(account);\n }\n }\n\n /**\n * Get the accounts list for the provider.\n *\n * @returns The accounts list.\n */\n #getAccountIds(): Account['id'][] {\n return [...this.accounts];\n }\n\n /**\n * Get the accounts list for the provider from the AccountsController.\n *\n * @returns The accounts list.\n */\n getAccounts(): Account[] {\n const accountsIds = this.#getAccountIds();\n const internalAccounts = this.messenger.call(\n 'AccountsController:getAccounts',\n accountsIds,\n );\n // we cast here because we know that the accounts are BIP-44 compatible\n return internalAccounts as unknown as Account[];\n }\n\n /**\n * Get the account for the provider.\n *\n * @param id - The account ID.\n * @returns The account.\n * @throws If the account is not found.\n */\n getAccount(id: Account['id']): Account {\n const hasAccount = this.accounts.has(id);\n\n if (!hasAccount) {\n throw new Error(`Unable to find account: ${id}`);\n }\n\n // We need to upcast here since InternalAccounts are not always BIP-44 compatible\n // but we know that the account is BIP-44 compatible here so it is safe to do so\n return this.messenger.call(\n 'AccountsController:getAccount',\n id,\n ) as unknown as Account;\n }\n\n /**\n * Run an operation against a V1 keyring selected by `selector`.\n *\n * Forwards to `KeyringController:withKeyring`. Use this for keyrings that\n * have not yet migrated to the unified V2 `Keyring` interface (e.g. the\n * snap keyring).\n *\n * @param selector - The selector identifying the keyring.\n * @param operation - The operation to run with the selected keyring.\n * @returns The result of the operation.\n */\n protected async withKeyring<SelectedKeyring, CallbackResult = void>(\n selector: KeyringSelector,\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SelectedKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n const result = await this.messenger.call(\n 'KeyringController:withKeyring',\n selector,\n ({ keyring, metadata }) =>\n operation({\n keyring: keyring as SelectedKeyring,\n metadata,\n }),\n );\n\n return result as CallbackResult;\n }\n\n /**\n * Run an operation against a V2 keyring selected by `selector`.\n *\n * Forwards to `KeyringController:withKeyringV2`. Use this for keyrings\n * that implement the unified V2 `Keyring` interface from\n * `@metamask/keyring-api/v2`.\n *\n * @param selector - The selector identifying the keyring.\n * @param operation - The operation to run with the selected keyring.\n * @returns The result of the operation.\n */\n protected async withKeyringV2<\n SelectedKeyring extends KeyringV2 = KeyringV2,\n CallbackResult = void,\n >(\n selector: KeyringSelectorV2<SelectedKeyring>,\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SelectedKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n const result = await this.messenger.call(\n 'KeyringController:withKeyringV2',\n selector,\n ({ keyring, metadata }) =>\n operation({\n keyring: keyring as SelectedKeyring,\n metadata,\n }),\n );\n\n return result as CallbackResult;\n }\n\n abstract get capabilities(): KeyringCapabilities;\n\n abstract getName(): string;\n\n abstract resyncAccounts(\n accounts: Bip44Account<InternalAccount>[],\n ): Promise<void>;\n\n abstract isAccountCompatible(account: Bip44Account<KeyringAccount>): boolean;\n\n abstract createAccounts(options: CreateAccountOptions): Promise<Account[]>;\n\n abstract discoverAccounts({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Account[]>;\n}\n"]}
1
+ {"version":3,"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QACnD,CAAC;QAED,iFAAiF;QACjF,gFAAgF;QAChF,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CACxB,+BAA+B,EAC/B,EAAE,CACmB,CAAC;IAC1B,CAAC;IAED;;;;;;;;;;OAUG;IACO,KAAK,CAAC,aAAa,CAI3B,QAA4C,EAC5C,SAM6B;QAE7B,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CACtC,iCAAiC,EACjC,QAAQ,EACR,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,CACxB,SAAS,CAAC;YACR,OAAO,EAAE,OAA0B;YACnC,QAAQ;SACT,CAAC,CACL,CAAC;QAEF,OAAO,MAAwB,CAAC;IAClC,CAAC;IAED,SAAS,CACP,QAAgE,EAChE,UAA2B;QAE3B,OAAO,CACL,UAAU,CAAC,MAAM,IAAI,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAC1E,CAAC;IACJ,CAAC;CAuBF;;IA3GG,OAAO,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC5B,CAAC","sourcesContent":["import { isBip44Account } from '@metamask/account-api';\nimport type { AccountProvider, Bip44Account } from '@metamask/account-api';\nimport type {\n CreateAccountOptions,\n EntropySourceId,\n KeyringAccount,\n} from '@metamask/keyring-api';\nimport type {\n Keyring as KeyringV2,\n KeyringCapabilities,\n} from '@metamask/keyring-api/v2';\nimport type {\n KeyringMetadata,\n KeyringSelectorV2,\n} from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\n\nimport type { MultichainAccountServiceMessenger } from '../types';\n\n/**\n * Asserts a keyring account is BIP-44 compatible.\n *\n * @param account - Keyring account to check.\n * @throws If the keyring account is not compatible.\n */\nexport function assertIsBip44Account(\n account: KeyringAccount,\n): asserts account is Bip44Account<KeyringAccount> {\n if (!isBip44Account(account)) {\n throw new Error('Created account is not BIP-44 compatible');\n }\n}\n\n/**\n * Asserts that a list of keyring accounts are all BIP-44 compatible.\n *\n * @param accounts - Keyring accounts to check.\n * @throws If any of the keyring account is not compatible.\n */\nexport function assertAreBip44Accounts(\n accounts: KeyringAccount[],\n): asserts accounts is Bip44Account<KeyringAccount>[] {\n accounts.forEach(assertIsBip44Account);\n}\n\nexport type Bip44AccountProvider<\n Account extends Bip44Account<KeyringAccount> = Bip44Account<KeyringAccount>,\n> = AccountProvider<Account> & {\n /**\n * Provider capabilities, including supported scopes and BIP-44 options.\n *\n * @returns The provider capabilities.\n */\n get capabilities(): KeyringCapabilities;\n /**\n * Get the name of the provider.\n *\n * @returns The name of the provider.\n */\n getName(): string;\n /**\n * Initialize the provider with the given accounts.\n *\n * @param accounts - The accounts to initialize the provider with.\n */\n init(accounts: Bip44Account<KeyringAccount>['id'][]): void;\n /**\n * Check if the account is compatible with the provider.\n */\n isAccountCompatible(account: Bip44Account<KeyringAccount>): boolean;\n /**\n * Create accounts for the provider.\n *\n * @param options - The options for creating the accounts.\n * @param options.entropySource - The entropy source.\n * @param options.groupIndex - The group index.\n * @param options.type - The type of account creation.\n * @returns The created accounts.\n */\n createAccounts(options: CreateAccountOptions): Promise<Account[]>;\n /**\n * Delete an account managed by this provider.\n *\n * Mirrors the v2 keyring `deleteAccount(accountId)` contract. Each provider\n * implementation is responsible for resolving any extra information it needs\n * (e.g. address for snap-based providers) and for performing the underlying\n * keyring removal.\n *\n * @param id - The id of the account to delete.\n */\n deleteAccount(id: Account['id']): Promise<void>;\n /**\n * Re-synchronize MetaMask accounts and the providers accounts if needed.\n *\n * NOTE: This is mostly required if one of the providers (keyrings or Snaps)\n * have different sets of accounts. This method would ensure that both are\n * in-sync and use the same accounts (and same IDs).\n */\n resyncAccounts(accounts: Bip44Account<InternalAccount>[]): Promise<void>;\n /**\n * Check if the provider has an aligned (i.e. present and owned) account for\n * the given entropy source and group index.\n *\n * Callers pre-filter the relevant account IDs from the group and pass them\n * in so the provider needs no messenger call.\n *\n * @param context - The entropy source and group index to check.\n * @param context.entropySource - The entropy source to check against.\n * @param context.groupIndex - The group index to check against.\n * @param accountIds - Account IDs already associated with this provider for\n * the given group (may be empty if no alignment has happened yet).\n * @returns `true` when `accountIds` is non-empty and every ID is in the\n * provider's internal accounts Set.\n */\n isAligned(\n context: { entropySource: EntropySourceId; groupIndex: number },\n accountIds: Account['id'][],\n ): boolean;\n};\n\nexport abstract class BaseBip44AccountProvider<\n Account extends Bip44Account<KeyringAccount> = Bip44Account<KeyringAccount>,\n> implements Bip44AccountProvider<Account> {\n protected readonly messenger: MultichainAccountServiceMessenger;\n\n protected accounts: Set<Bip44Account<KeyringAccount>['id']> = new Set();\n\n constructor(messenger: MultichainAccountServiceMessenger) {\n this.messenger = messenger;\n }\n\n /**\n * Add accounts to the provider.\n *\n * Note: There's an implicit assumption that the accounts are BIP-44 compatible.\n *\n * @param accounts - The accounts to add.\n */\n init(accounts: Account['id'][]): void {\n for (const account of accounts) {\n this.accounts.add(account);\n }\n }\n\n /**\n * Get the accounts list for the provider.\n *\n * @returns The accounts list.\n */\n #getAccountIds(): Account['id'][] {\n return [...this.accounts];\n }\n\n /**\n * Get the accounts list for the provider from the AccountsController.\n *\n * @returns The accounts list.\n */\n getAccounts(): Account[] {\n const accountsIds = this.#getAccountIds();\n const internalAccounts = this.messenger.call(\n 'AccountsController:getAccounts',\n accountsIds,\n );\n // we cast here because we know that the accounts are BIP-44 compatible\n return internalAccounts as unknown as Account[];\n }\n\n /**\n * Get the account for the provider.\n *\n * @param id - The account ID.\n * @returns The account.\n * @throws If the account is not found.\n */\n getAccount(id: Account['id']): Account {\n const hasAccount = this.accounts.has(id);\n\n if (!hasAccount) {\n throw new Error(`Unable to find account: ${id}`);\n }\n\n // We need to upcast here since InternalAccounts are not always BIP-44 compatible\n // but we know that the account is BIP-44 compatible here so it is safe to do so\n return this.messenger.call(\n 'AccountsController:getAccount',\n id,\n ) as unknown as Account;\n }\n\n /**\n * Run an operation against a V2 keyring selected by `selector`.\n *\n * Forwards to `KeyringController:withKeyringV2`. Use this for keyrings\n * that implement the unified V2 `Keyring` interface from\n * `@metamask/keyring-api/v2`.\n *\n * @param selector - The selector identifying the keyring.\n * @param operation - The operation to run with the selected keyring.\n * @returns The result of the operation.\n */\n protected async withKeyringV2<\n SelectedKeyring extends KeyringV2 = KeyringV2,\n CallbackResult = void,\n >(\n selector: KeyringSelectorV2<SelectedKeyring>,\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SelectedKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n const result = await this.messenger.call(\n 'KeyringController:withKeyringV2',\n selector,\n ({ keyring, metadata }) =>\n operation({\n keyring: keyring as SelectedKeyring,\n metadata,\n }),\n );\n\n return result as CallbackResult;\n }\n\n isAligned(\n _context: { entropySource: EntropySourceId; groupIndex: number },\n accountIds: Account['id'][],\n ): boolean {\n return (\n accountIds.length >= 1 && accountIds.every((id) => this.accounts.has(id))\n );\n }\n\n abstract get capabilities(): KeyringCapabilities;\n\n abstract getName(): string;\n\n abstract resyncAccounts(\n accounts: Bip44Account<InternalAccount>[],\n ): Promise<void>;\n\n abstract isAccountCompatible(account: Bip44Account<KeyringAccount>): boolean;\n\n abstract createAccounts(options: CreateAccountOptions): Promise<Account[]>;\n\n abstract deleteAccount(id: Account['id']): Promise<void>;\n\n abstract discoverAccounts({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Account[]>;\n}\n"]}
@@ -195,6 +195,25 @@ class EvmAccountProvider extends BaseBip44AccountProvider_1.BaseBip44AccountProv
195
195
  // No-op for the EVM account provider, since keyring accounts are already on
196
196
  // the MetaMask side.
197
197
  }
198
+ /**
199
+ * Delete an EVM account by id.
200
+ *
201
+ * Resolves the account's entropy source from the tracked account, then
202
+ * forwards to the v2 HD keyring's `deleteAccount(id)`. When this is the
203
+ * last account on a non-primary HD keyring, the keyring controller will
204
+ * automatically prune the empty keyring (see
205
+ * `KeyringController.#cleanUpEmptiedKeyringsAfter`).
206
+ *
207
+ * @param id - The id of the account to delete.
208
+ */
209
+ async deleteAccount(id) {
210
+ const account = this.getAccount(id);
211
+ const entropySource = account.options.entropy.id;
212
+ await this.withKeyringV2({ id: entropySource }, async ({ keyring }) => {
213
+ await keyring.deleteAccount(id);
214
+ });
215
+ this.accounts.delete(id);
216
+ }
198
217
  }
199
218
  exports.EvmAccountProvider = EvmAccountProvider;
200
219
  _EvmAccountProvider_config = new WeakMap(), _EvmAccountProvider_trace = new WeakMap(), _EvmAccountProvider_instances = new WeakSet(), _EvmAccountProvider_createAccount =
@@ -1 +1 @@
1
- {"version":3,"file":"EvmAccountProvider.cjs","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAmD;AASnD,uDAK+B;AAE/B,qEAA4D;AAI5D,2CAA+E;AAG/E,sDAA6C;AAC7C,oDAAgD;AAChD,0CAAiE;AAEjE,6EAIoC;AACpC,uCAAiD;AAEjD,MAAM,oBAAoB,GAAG,KAAK,CAAC;AAEnC;;;;;GAKG;AACH,SAAS,2BAA2B,CAClC,OAAoC;IAEpC,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;IACrD,CAAC;AACH,CAAC;AAWY,QAAA,yBAAyB,GAAG,KAAK,CAAC;AAElC,QAAA,mCAAmC,GAAG;IACjD,SAAS,EAAE;QACT,WAAW,EAAE,CAAC;QACd,SAAS,EAAE,GAAG;QACd,SAAS,EAAE,GAAG;KACf;CACF,CAAC;AAEF,MAAa,kBAAmB,SAAQ,mDAAwB;IAe9D,YACE,SAA4C,EAC5C,SAAmC,2CAAmC,EACtE,KAAqB;QAErB,KAAK,CAAC,SAAS,CAAC,CAAC;;QAjBV,6CAAkC;QAElC,4CAAsB;QAEtB,iB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,CAAC;QAEtB,OAAO,CAAC,CAAC;IACX,CAAC;IAED,OAAO,QAAQ,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AAChC,CAAC;AAjSM,uBAAI,GAAG,iCAAyB,AAA5B,CAA6B","sourcesContent":["import { publicToAddress } from '@ethereumjs/util';\nimport type { Bip44Account } from '@metamask/account-api';\nimport type { TraceCallback } from '@metamask/controller-utils';\nimport type { HdKeyring } from '@metamask/eth-hd-keyring/v2';\nimport type {\n CreateAccountOptions,\n EntropySourceId,\n KeyringAccount,\n} from '@metamask/keyring-api';\nimport {\n AccountCreationType,\n assertCreateAccountOptionIsSupported,\n EthAccountType,\n EthScope,\n} from '@metamask/keyring-api';\nimport type { KeyringCapabilities, Keyring } from '@metamask/keyring-api/v2';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { AccountId } from '@metamask/keyring-utils';\nimport type { Provider } from '@metamask/network-controller';\nimport { add0x, assert, bytesToHex, isStrictHexString } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { traceFallback } from '../analytics';\nimport { TraceName } from '../analytics/traces';\nimport { projectLogger as log, WARNING_PREFIX } from '../logger';\nimport type { MultichainAccountServiceMessenger } from '../types';\nimport {\n assertAreBip44Accounts,\n assertIsBip44Account,\n BaseBip44AccountProvider,\n} from './BaseBip44AccountProvider';\nimport { withRetry, withTimeout } from './utils';\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 type EvmAccountProviderConfig = {\n discovery: {\n enabled?: boolean;\n maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n};\n\nexport const EVM_ACCOUNT_PROVIDER_NAME = 'EVM';\n\nexport const EVM_ACCOUNT_PROVIDER_DEFAULT_CONFIG = {\n discovery: {\n maxAttempts: 3,\n timeoutMs: 500,\n backOffMs: 500,\n },\n};\n\nexport class EvmAccountProvider extends BaseBip44AccountProvider {\n static NAME = EVM_ACCOUNT_PROVIDER_NAME;\n\n readonly #config: EvmAccountProviderConfig;\n\n readonly #trace: TraceCallback;\n\n readonly capabilities: KeyringCapabilities = {\n scopes: [EthScope.Eoa],\n bip44: {\n deriveIndex: true,\n deriveIndexRange: true,\n },\n };\n\n constructor(\n messenger: MultichainAccountServiceMessenger,\n config: EvmAccountProviderConfig = EVM_ACCOUNT_PROVIDER_DEFAULT_CONFIG,\n trace?: TraceCallback,\n ) {\n super(messenger);\n this.#config = {\n ...config,\n discovery: {\n ...config.discovery,\n enabled: config.discovery.enabled ?? true,\n },\n };\n this.#trace = trace ?? traceFallback;\n }\n\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 EvmAccountProvider.NAME;\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 /**\n * Create an EVM account.\n *\n * @param opts - The options for the creation of the account.\n * @param opts.entropySource - The entropy source to use for the creation of the account.\n * @param opts.groupIndex - The index of the group to create the account for.\n * @param opts.throwOnGap - Whether to throw an error if the account index is not contiguous.\n * @returns The created or existing keyring account(s) at the requested group\n * index. Returns an empty array if the keyring did not create an account.\n */\n async #createAccount({\n entropySource,\n groupIndex,\n throwOnGap,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n throwOnGap: boolean;\n }): Promise<KeyringAccount[]> {\n return await this.withKeyringV2<Keyring, KeyringAccount[]>(\n { id: entropySource },\n async ({ keyring }) => {\n const existing = await keyring.getAccounts();\n if (groupIndex < existing.length) {\n return [existing[groupIndex]];\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 return await keyring.createAccounts({\n type: AccountCreationType.Bip44DeriveIndex,\n entropySource,\n groupIndex,\n });\n },\n );\n }\n\n /**\n * Create accounts for the EVM provider.\n *\n * @param options - The options for the creation of the accounts.\n * @returns The accounts for the EVM provider.\n */\n async createAccounts(\n options: CreateAccountOptions,\n ): Promise<Bip44Account<KeyringAccount>[]> {\n assertCreateAccountOptionIsSupported(options, [\n `${AccountCreationType.Bip44DeriveIndex}`,\n `${AccountCreationType.Bip44DeriveIndexRange}`,\n ]);\n\n const { entropySource } = options;\n\n if (options.type === AccountCreationType.Bip44DeriveIndexRange) {\n const { range } = options;\n\n // Use a single withKeyring call for the entire range.\n const accountIds = await this.withKeyringV2<Keyring, AccountId[]>(\n { id: entropySource },\n async ({ keyring }) => {\n const existing = await keyring.getAccounts();\n\n // Validate no gaps: we can only create accounts starting from existing.length.\n if (range.from > existing.length) {\n throw new Error(\n `Bad account creation request, group index range would create gaps (${range.from} (from) > ${existing.length} (next available index))`,\n );\n }\n\n const result: AccountId[] = [];\n\n // Collect existing accounts within the range.\n for (\n let groupIndex = range.from;\n groupIndex <= range.to;\n groupIndex++\n ) {\n if (groupIndex < existing.length) {\n // Account already exists.\n result.push(existing[groupIndex].id);\n }\n }\n\n // Create new accounts one-by-one since HdKeyringV2 only supports\n // bip44:derive-index (not bip44:derive-index-range).\n for (\n let groupIndex = Math.max(range.from, existing.length);\n groupIndex <= range.to;\n groupIndex++\n ) {\n const [created] = await keyring.createAccounts({\n type: AccountCreationType.Bip44DeriveIndex,\n entropySource,\n groupIndex,\n });\n assert(created, 'Account creation failed');\n result.push(created.id);\n }\n\n return result;\n },\n );\n\n const accounts: InternalAccount[] = [];\n for (const account of this.messenger.call(\n 'AccountsController:getAccounts',\n accountIds,\n )) {\n assertInternalAccountExists(account);\n this.accounts.add(account.id);\n accounts.push(account);\n }\n\n assertAreBip44Accounts(accounts);\n return accounts;\n }\n\n // Handle Bip44DeriveIndex (single account creation).\n const { groupIndex } = options;\n\n const [created] = await this.#createAccount({\n entropySource,\n groupIndex,\n throwOnGap: true,\n });\n\n assert(created, 'Account creation failed');\n\n const account = this.messenger.call(\n 'AccountsController:getAccount',\n created.id,\n );\n\n // We MUST have the associated internal account.\n assertInternalAccountExists(account);\n\n const accountsArray = [account];\n assertAreBip44Accounts(accountsArray);\n\n this.accounts.add(account.id);\n return accountsArray;\n }\n\n /**\n * Get the address that would be derived for a given group index without\n * persisting an account in the keyring.\n *\n * Peeks at the next address via the HD `root` so discovery can short-circuit\n * (and skip the vault write + `stateChange` event) when there is no on-chain\n * activity at this index.\n *\n * @param opts - The options for the address derivation.\n * @param opts.entropySource - The entropy source to derive from.\n * @param opts.groupIndex - The group index to derive at.\n * @returns The derived address for the given group index.\n */\n async #getAddressFromGroupIndex({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Hex> {\n // NOTE: To avoid exposing this function at keyring level, we just re-use its internal state\n // and compute the derivation here.\n return await this.withKeyringV2<HdKeyring, Hex>(\n { id: entropySource },\n async ({ keyring }) => {\n // If the account already exist, do not re-derive and just re-use that account.\n const existing = await keyring.getAccounts();\n if (groupIndex < existing.length) {\n return existing[groupIndex].address as Hex;\n }\n\n // If not, then we just \"peek\" the next address to avoid creating the account.\n assert(keyring.root, 'Expected HD keyring.root to be set');\n const hdKey = keyring.root.deriveChild(groupIndex);\n assert(hdKey.publicKey, 'Expected public key to be set');\n\n return add0x(\n bytesToHex(publicToAddress(hdKey.publicKey, true)).toLowerCase(),\n );\n },\n );\n }\n\n /**\n * Get the transaction count for an EVM account.\n * This method uses a retry and timeout mechanism to handle transient failures.\n *\n * @param provider - The provider to use for the transaction count.\n * @param address - The address of the account.\n * @returns The transaction count.\n */\n async #getTransactionCount(\n provider: Provider,\n address: string,\n ): Promise<number> {\n const method = 'eth_getTransactionCount';\n\n const response = await withRetry(\n () =>\n withTimeout(\n () =>\n provider.request({\n method,\n params: [address, 'latest'],\n }),\n this.#config.discovery.timeoutMs,\n ),\n {\n maxAttempts: this.#config.discovery.maxAttempts,\n backOffMs: this.#config.discovery.backOffMs,\n },\n );\n\n // Make sure we got the right response format, if not, we fallback to \"0x0\", to avoid having to deal with `NaN`.\n if (!isStrictHexString(response)) {\n const message = `Received invalid hex response from \"${method}\" request: ${JSON.stringify(response)}`;\n\n log(`${WARNING_PREFIX} ${message}`);\n console.warn(message);\n\n return 0;\n }\n\n return parseInt(response, 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 return this.#trace(\n {\n name: TraceName.EvmDiscoverAccounts,\n data: {\n provider: this.getName(),\n },\n },\n async () => {\n if (!this.#config.discovery.enabled) {\n return [];\n }\n\n const provider = this.getEvmProvider();\n const { entropySource, groupIndex } = opts;\n\n const addressFromGroupIndex = await this.#getAddressFromGroupIndex({\n entropySource,\n groupIndex,\n });\n\n const count = await this.#getTransactionCount(\n provider,\n addressFromGroupIndex,\n );\n if (count === 0) {\n return [];\n }\n\n // We have some activity on this address, we try to create the account.\n const [created] = await this.#createAccount({\n entropySource,\n groupIndex,\n throwOnGap: false,\n });\n\n assert(created, 'Account creation failed');\n assert(\n addressFromGroupIndex === created.address,\n 'Created account does not match address from group index.',\n );\n\n const account = this.messenger.call(\n 'AccountsController:getAccount',\n created.id,\n );\n assertInternalAccountExists(account);\n assertIsBip44Account(account);\n this.accounts.add(account.id);\n return [account];\n },\n );\n }\n\n async resyncAccounts(): Promise<void> {\n // No-op for the EVM account provider, since keyring accounts are already on\n // the MetaMask side.\n }\n}\n"]}
1
+ {"version":3,"file":"EvmAccountProvider.cjs","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAmD;AASnD,uDAK+B;AAE/B,qEAA4D;AAI5D,2CAA+E;AAG/E,sDAA6C;AAC7C,oDAAgD;AAChD,0CAAiE;AAEjE,6EAIoC;AACpC,uCAAiD;AAEjD,MAAM,oBAAoB,GAAG,KAAK,CAAC;AAEnC;;;;;GAKG;AACH,SAAS,2BAA2B,CAClC,OAAoC;IAEpC,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;IACrD,CAAC;AACH,CAAC;AAWY,QAAA,yBAAyB,GAAG,KAAK,CAAC;AAElC,QAAA,mCAAmC,GAAG;IACjD,SAAS,EAAE;QACT,WAAW,EAAE,CAAC;QACd,SAAS,EAAE,GAAG;QACd,SAAS,EAAE,GAAG;KACf;CACF,CAAC;AAEF,MAAa,kBAAmB,SAAQ,mDAAwB;IAe9D,YACE,SAA4C,EAC5C,SAAmC,2CAAmC,EACtE,KAAqB;QAErB,KAAK,CAAC,SAAS,CAAC,CAAC;;QAjBV,6CAAkC;QAElC,4CAAsB;QAEtB,iBAAY,GAAwB;YAC3C,MAAM,EAAE,CAAC,sBAAQ,CAAC,GAAG,CAAC;YACtB,KAAK,EAAE;gBACL,WAAW,EAAE,IAAI;gBACjB,gBAAgB,EAAE,IAAI;aACvB;SACF,CAAC;QAQA,uBAAA,IAAI,8BAAW;YACb,GAAG,MAAM;YACT,SAAS,EAAE;gBACT,GAAG,MAAM,CAAC,SAAS;gBACnB,OAAO,EAAE,MAAM,CAAC,SAAS,CAAC,OAAO,IAAI,IAAI;aAC1C;SACF,MAAA,CAAC;QACF,uBAAA,IAAI,6BAAU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C;QAEtG,IAAA,sBAAG,EAAC,GAAG,uBAAc,IAAI,OAAO,EAAE,CAAC,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAEtB,OAAO,CAAC,CAAC;IACX,CAAC;IAED,OAAO,QAAQ,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AAChC,CAAC;AAjSM,uBAAI,GAAG,iCAAyB,AAA5B,CAA6B","sourcesContent":["import { publicToAddress } from '@ethereumjs/util';\nimport type { Bip44Account } from '@metamask/account-api';\nimport type { TraceCallback } from '@metamask/controller-utils';\nimport type { HdKeyring } from '@metamask/eth-hd-keyring/v2';\nimport type {\n CreateAccountOptions,\n EntropySourceId,\n KeyringAccount,\n} from '@metamask/keyring-api';\nimport {\n AccountCreationType,\n assertCreateAccountOptionIsSupported,\n EthAccountType,\n EthScope,\n} from '@metamask/keyring-api';\nimport type { KeyringCapabilities, Keyring } from '@metamask/keyring-api/v2';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { AccountId } from '@metamask/keyring-utils';\nimport type { Provider } from '@metamask/network-controller';\nimport { add0x, assert, bytesToHex, isStrictHexString } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { traceFallback } from '../analytics';\nimport { TraceName } from '../analytics/traces';\nimport { projectLogger as log, WARNING_PREFIX } from '../logger';\nimport type { MultichainAccountServiceMessenger } from '../types';\nimport {\n assertAreBip44Accounts,\n assertIsBip44Account,\n BaseBip44AccountProvider,\n} from './BaseBip44AccountProvider';\nimport { withRetry, withTimeout } from './utils';\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 type EvmAccountProviderConfig = {\n discovery: {\n enabled?: boolean;\n maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n};\n\nexport const EVM_ACCOUNT_PROVIDER_NAME = 'EVM';\n\nexport const EVM_ACCOUNT_PROVIDER_DEFAULT_CONFIG = {\n discovery: {\n maxAttempts: 3,\n timeoutMs: 500,\n backOffMs: 500,\n },\n};\n\nexport class EvmAccountProvider extends BaseBip44AccountProvider {\n static NAME = EVM_ACCOUNT_PROVIDER_NAME;\n\n readonly #config: EvmAccountProviderConfig;\n\n readonly #trace: TraceCallback;\n\n readonly capabilities: KeyringCapabilities = {\n scopes: [EthScope.Eoa],\n bip44: {\n deriveIndex: true,\n deriveIndexRange: true,\n },\n };\n\n constructor(\n messenger: MultichainAccountServiceMessenger,\n config: EvmAccountProviderConfig = EVM_ACCOUNT_PROVIDER_DEFAULT_CONFIG,\n trace?: TraceCallback,\n ) {\n super(messenger);\n this.#config = {\n ...config,\n discovery: {\n ...config.discovery,\n enabled: config.discovery.enabled ?? true,\n },\n };\n this.#trace = trace ?? traceFallback;\n }\n\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 EvmAccountProvider.NAME;\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 /**\n * Create an EVM account.\n *\n * @param opts - The options for the creation of the account.\n * @param opts.entropySource - The entropy source to use for the creation of the account.\n * @param opts.groupIndex - The index of the group to create the account for.\n * @param opts.throwOnGap - Whether to throw an error if the account index is not contiguous.\n * @returns The created or existing keyring account(s) at the requested group\n * index. Returns an empty array if the keyring did not create an account.\n */\n async #createAccount({\n entropySource,\n groupIndex,\n throwOnGap,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n throwOnGap: boolean;\n }): Promise<KeyringAccount[]> {\n return await this.withKeyringV2<Keyring, KeyringAccount[]>(\n { id: entropySource },\n async ({ keyring }) => {\n const existing = await keyring.getAccounts();\n if (groupIndex < existing.length) {\n return [existing[groupIndex]];\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 return await keyring.createAccounts({\n type: AccountCreationType.Bip44DeriveIndex,\n entropySource,\n groupIndex,\n });\n },\n );\n }\n\n /**\n * Create accounts for the EVM provider.\n *\n * @param options - The options for the creation of the accounts.\n * @returns The accounts for the EVM provider.\n */\n async createAccounts(\n options: CreateAccountOptions,\n ): Promise<Bip44Account<KeyringAccount>[]> {\n assertCreateAccountOptionIsSupported(options, [\n `${AccountCreationType.Bip44DeriveIndex}`,\n `${AccountCreationType.Bip44DeriveIndexRange}`,\n ]);\n\n const { entropySource } = options;\n\n if (options.type === AccountCreationType.Bip44DeriveIndexRange) {\n const { range } = options;\n\n // Use a single withKeyring call for the entire range.\n const accountIds = await this.withKeyringV2<Keyring, AccountId[]>(\n { id: entropySource },\n async ({ keyring }) => {\n const existing = await keyring.getAccounts();\n\n // Validate no gaps: we can only create accounts starting from existing.length.\n if (range.from > existing.length) {\n throw new Error(\n `Bad account creation request, group index range would create gaps (${range.from} (from) > ${existing.length} (next available index))`,\n );\n }\n\n const result: AccountId[] = [];\n\n // Collect existing accounts within the range.\n for (\n let groupIndex = range.from;\n groupIndex <= range.to;\n groupIndex++\n ) {\n if (groupIndex < existing.length) {\n // Account already exists.\n result.push(existing[groupIndex].id);\n }\n }\n\n // Create new accounts one-by-one since HdKeyringV2 only supports\n // bip44:derive-index (not bip44:derive-index-range).\n for (\n let groupIndex = Math.max(range.from, existing.length);\n groupIndex <= range.to;\n groupIndex++\n ) {\n const [created] = await keyring.createAccounts({\n type: AccountCreationType.Bip44DeriveIndex,\n entropySource,\n groupIndex,\n });\n assert(created, 'Account creation failed');\n result.push(created.id);\n }\n\n return result;\n },\n );\n\n const accounts: InternalAccount[] = [];\n for (const account of this.messenger.call(\n 'AccountsController:getAccounts',\n accountIds,\n )) {\n assertInternalAccountExists(account);\n this.accounts.add(account.id);\n accounts.push(account);\n }\n\n assertAreBip44Accounts(accounts);\n return accounts;\n }\n\n // Handle Bip44DeriveIndex (single account creation).\n const { groupIndex } = options;\n\n const [created] = await this.#createAccount({\n entropySource,\n groupIndex,\n throwOnGap: true,\n });\n\n assert(created, 'Account creation failed');\n\n const account = this.messenger.call(\n 'AccountsController:getAccount',\n created.id,\n );\n\n // We MUST have the associated internal account.\n assertInternalAccountExists(account);\n\n const accountsArray = [account];\n assertAreBip44Accounts(accountsArray);\n\n this.accounts.add(account.id);\n return accountsArray;\n }\n\n /**\n * Get the address that would be derived for a given group index without\n * persisting an account in the keyring.\n *\n * Peeks at the next address via the HD `root` so discovery can short-circuit\n * (and skip the vault write + `stateChange` event) when there is no on-chain\n * activity at this index.\n *\n * @param opts - The options for the address derivation.\n * @param opts.entropySource - The entropy source to derive from.\n * @param opts.groupIndex - The group index to derive at.\n * @returns The derived address for the given group index.\n */\n async #getAddressFromGroupIndex({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Hex> {\n // NOTE: To avoid exposing this function at keyring level, we just re-use its internal state\n // and compute the derivation here.\n return await this.withKeyringV2<HdKeyring, Hex>(\n { id: entropySource },\n async ({ keyring }) => {\n // If the account already exist, do not re-derive and just re-use that account.\n const existing = await keyring.getAccounts();\n if (groupIndex < existing.length) {\n return existing[groupIndex].address as Hex;\n }\n\n // If not, then we just \"peek\" the next address to avoid creating the account.\n assert(keyring.root, 'Expected HD keyring.root to be set');\n const hdKey = keyring.root.deriveChild(groupIndex);\n assert(hdKey.publicKey, 'Expected public key to be set');\n\n return add0x(\n bytesToHex(publicToAddress(hdKey.publicKey, true)).toLowerCase(),\n );\n },\n );\n }\n\n /**\n * Get the transaction count for an EVM account.\n * This method uses a retry and timeout mechanism to handle transient failures.\n *\n * @param provider - The provider to use for the transaction count.\n * @param address - The address of the account.\n * @returns The transaction count.\n */\n async #getTransactionCount(\n provider: Provider,\n address: string,\n ): Promise<number> {\n const method = 'eth_getTransactionCount';\n\n const response = await withRetry(\n () =>\n withTimeout(\n () =>\n provider.request({\n method,\n params: [address, 'latest'],\n }),\n this.#config.discovery.timeoutMs,\n ),\n {\n maxAttempts: this.#config.discovery.maxAttempts,\n backOffMs: this.#config.discovery.backOffMs,\n },\n );\n\n // Make sure we got the right response format, if not, we fallback to \"0x0\", to avoid having to deal with `NaN`.\n if (!isStrictHexString(response)) {\n const message = `Received invalid hex response from \"${method}\" request: ${JSON.stringify(response)}`;\n\n log(`${WARNING_PREFIX} ${message}`);\n console.warn(message);\n\n return 0;\n }\n\n return parseInt(response, 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 return this.#trace(\n {\n name: TraceName.EvmDiscoverAccounts,\n data: {\n provider: this.getName(),\n },\n },\n async () => {\n if (!this.#config.discovery.enabled) {\n return [];\n }\n\n const provider = this.getEvmProvider();\n const { entropySource, groupIndex } = opts;\n\n const addressFromGroupIndex = await this.#getAddressFromGroupIndex({\n entropySource,\n groupIndex,\n });\n\n const count = await this.#getTransactionCount(\n provider,\n addressFromGroupIndex,\n );\n if (count === 0) {\n return [];\n }\n\n // We have some activity on this address, we try to create the account.\n const [created] = await this.#createAccount({\n entropySource,\n groupIndex,\n throwOnGap: false,\n });\n\n assert(created, 'Account creation failed');\n assert(\n addressFromGroupIndex === created.address,\n 'Created account does not match address from group index.',\n );\n\n const account = this.messenger.call(\n 'AccountsController:getAccount',\n created.id,\n );\n assertInternalAccountExists(account);\n assertIsBip44Account(account);\n this.accounts.add(account.id);\n return [account];\n },\n );\n }\n\n async resyncAccounts(): Promise<void> {\n // No-op for the EVM account provider, since keyring accounts are already on\n // the MetaMask side.\n }\n\n /**\n * Delete an EVM account by id.\n *\n * Resolves the account's entropy source from the tracked account, then\n * forwards to the v2 HD keyring's `deleteAccount(id)`. When this is the\n * last account on a non-primary HD keyring, the keyring controller will\n * automatically prune the empty keyring (see\n * `KeyringController.#cleanUpEmptiedKeyringsAfter`).\n *\n * @param id - The id of the account to delete.\n */\n async deleteAccount(id: Bip44Account<KeyringAccount>['id']): Promise<void> {\n const account = this.getAccount(id);\n const entropySource = account.options.entropy.id;\n\n await this.withKeyringV2<Keyring>(\n { id: entropySource },\n async ({ keyring }) => {\n await keyring.deleteAccount(id);\n },\n );\n\n this.accounts.delete(id);\n }\n}\n"]}
@@ -55,5 +55,17 @@ export declare class EvmAccountProvider extends BaseBip44AccountProvider {
55
55
  groupIndex: number;
56
56
  }): Promise<Bip44Account<KeyringAccount>[]>;
57
57
  resyncAccounts(): Promise<void>;
58
+ /**
59
+ * Delete an EVM account by id.
60
+ *
61
+ * Resolves the account's entropy source from the tracked account, then
62
+ * forwards to the v2 HD keyring's `deleteAccount(id)`. When this is the
63
+ * last account on a non-primary HD keyring, the keyring controller will
64
+ * automatically prune the empty keyring (see
65
+ * `KeyringController.#cleanUpEmptiedKeyringsAfter`).
66
+ *
67
+ * @param id - The id of the account to delete.
68
+ */
69
+ deleteAccount(id: Bip44Account<KeyringAccount>['id']): Promise<void>;
58
70
  }
59
71
  //# sourceMappingURL=EvmAccountProvider.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"EvmAccountProvider.d.cts","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,8BAA8B;AA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AoB,GAC5B,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;IAwL1C;;;;;;;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;IAsDrC,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;IAKrC;;;;;;;;;;OAUG;IACG,aAAa,CAAC,EAAE,EAAE,YAAY,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;CAa3E"}
@@ -55,5 +55,17 @@ export declare class EvmAccountProvider extends BaseBip44AccountProvider {
55
55
  groupIndex: number;
56
56
  }): Promise<Bip44Account<KeyringAccount>[]>;
57
57
  resyncAccounts(): Promise<void>;
58
+ /**
59
+ * Delete an EVM account by id.
60
+ *
61
+ * Resolves the account's entropy source from the tracked account, then
62
+ * forwards to the v2 HD keyring's `deleteAccount(id)`. When this is the
63
+ * last account on a non-primary HD keyring, the keyring controller will
64
+ * automatically prune the empty keyring (see
65
+ * `KeyringController.#cleanUpEmptiedKeyringsAfter`).
66
+ *
67
+ * @param id - The id of the account to delete.
68
+ */
69
+ deleteAccount(id: Bip44Account<KeyringAccount>['id']): Promise<void>;
58
70
  }
59
71
  //# sourceMappingURL=EvmAccountProvider.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"EvmAccountProvider.d.mts","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,8BAA8B;AAC1D,OAAO,KAAK,EAAE,aAAa,EAAE,mCAAmC;AAEhE,OAAO,KAAK,EACV,oBAAoB,EACpB,eAAe,EACf,cAAc,EACf,8BAA8B;AAO/B,OAAO,KAAK,EAAE,mBAAmB,EAAW,iCAAiC;AAE7E,OAAO,KAAK,EAAE,eAAe,EAA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AAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;IAsDrC,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;IAKrC;;;;;;;;;;OAUG;IACG,aAAa,CAAC,EAAE,EAAE,YAAY,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;CAa3E"}
@@ -192,6 +192,25 @@ export class EvmAccountProvider extends BaseBip44AccountProvider {
192
192
  // No-op for the EVM account provider, since keyring accounts are already on
193
193
  // the MetaMask side.
194
194
  }
195
+ /**
196
+ * Delete an EVM account by id.
197
+ *
198
+ * Resolves the account's entropy source from the tracked account, then
199
+ * forwards to the v2 HD keyring's `deleteAccount(id)`. When this is the
200
+ * last account on a non-primary HD keyring, the keyring controller will
201
+ * automatically prune the empty keyring (see
202
+ * `KeyringController.#cleanUpEmptiedKeyringsAfter`).
203
+ *
204
+ * @param id - The id of the account to delete.
205
+ */
206
+ async deleteAccount(id) {
207
+ const account = this.getAccount(id);
208
+ const entropySource = account.options.entropy.id;
209
+ await this.withKeyringV2({ id: entropySource }, async ({ keyring }) => {
210
+ await keyring.deleteAccount(id);
211
+ });
212
+ this.accounts.delete(id);
213
+ }
195
214
  }
196
215
  _EvmAccountProvider_config = new WeakMap(), _EvmAccountProvider_trace = new WeakMap(), _EvmAccountProvider_instances = new WeakSet(), _EvmAccountProvider_createAccount =
197
216
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"EvmAccountProvider.mjs","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,yBAAyB;AASnD,OAAO,EACL,mBAAmB,EACnB,oCAAoC,EACpC,cAAc,EACd,QAAQ,EACT,8BAA8B;AAE/B,OAAO,EAAE,YAAY,EAAE,qCAAqC;AAI5D,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,iBAAiB,EAAE,wBAAwB;AAG/E,OAAO,EAAE,a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BAAyB,CAAC;IAEzC,MAAM,QAAQ,GAAG,MAAM,SAAS,CAC9B,GAAG,EAAE,CACH,WAAW,CACT,GAAG,EAAE,CACH,QAAQ,CAAC,OAAO,CAAC;QACf,MAAM;QACN,MAAM,EAAE,CAAC,OAAO,EAAE,QAAQ,CAAC;KAC5B,CAAC,EACJ,uBAAA,IAAI,kCAAQ,CAAC,SAAS,CAAC,SAAS,CACjC,EACH;QACE,WAAW,EAAE,uBAAA,IAAI,kCAAQ,CAAC,SAAS,CAAC,WAAW;QAC/C,SAAS,EAAE,uBAAA,IAAI,kCAAQ,CAAC,SAAS,CAAC,SAAS;KAC5C,CACF,CAAC;IAEF,gHAAgH;IAChH,IAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC,EAAE,CAAC;QACjC,MAAM,OAAO,GAAG,uCAAuC,MAAM,cAAc,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC;QAEtG,GAAG,CAAC,GAAG,cAAc,IAAI,OAAO,EAAE,CAAC,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAEtB,OAAO,CAAC,CAAC;IACX,CAAC;IAED,OAAO,QAAQ,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AAChC,CAAC;AAjSM,uBAAI,GAAG,yBAAyB,AAA5B,CAA6B","sourcesContent":["import { publicToAddress } from '@ethereumjs/util';\nimport type { Bip44Account } from '@metamask/account-api';\nimport type { TraceCallback } from '@metamask/controller-utils';\nimport type { HdKeyring } from '@metamask/eth-hd-keyring/v2';\nimport type {\n CreateAccountOptions,\n EntropySourceId,\n KeyringAccount,\n} from '@metamask/keyring-api';\nimport {\n AccountCreationType,\n assertCreateAccountOptionIsSupported,\n EthAccountType,\n EthScope,\n} from '@metamask/keyring-api';\nimport type { KeyringCapabilities, Keyring } from '@metamask/keyring-api/v2';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { AccountId } from '@metamask/keyring-utils';\nimport type { Provider } from '@metamask/network-controller';\nimport { add0x, assert, bytesToHex, isStrictHexString } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { traceFallback } from '../analytics';\nimport { TraceName } from '../analytics/traces';\nimport { projectLogger as log, WARNING_PREFIX } from '../logger';\nimport type { MultichainAccountServiceMessenger } from '../types';\nimport {\n assertAreBip44Accounts,\n assertIsBip44Account,\n BaseBip44AccountProvider,\n} from './BaseBip44AccountProvider';\nimport { withRetry, withTimeout } from './utils';\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 type EvmAccountProviderConfig = {\n discovery: {\n enabled?: boolean;\n maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n};\n\nexport const EVM_ACCOUNT_PROVIDER_NAME = 'EVM';\n\nexport const EVM_ACCOUNT_PROVIDER_DEFAULT_CONFIG = {\n discovery: {\n maxAttempts: 3,\n timeoutMs: 500,\n backOffMs: 500,\n },\n};\n\nexport class EvmAccountProvider extends BaseBip44AccountProvider {\n static NAME = EVM_ACCOUNT_PROVIDER_NAME;\n\n readonly #config: EvmAccountProviderConfig;\n\n readonly #trace: TraceCallback;\n\n readonly capabilities: KeyringCapabilities = {\n scopes: [EthScope.Eoa],\n bip44: {\n deriveIndex: true,\n deriveIndexRange: true,\n },\n };\n\n constructor(\n messenger: MultichainAccountServiceMessenger,\n config: EvmAccountProviderConfig = EVM_ACCOUNT_PROVIDER_DEFAULT_CONFIG,\n trace?: TraceCallback,\n ) {\n super(messenger);\n this.#config = {\n ...config,\n discovery: {\n ...config.discovery,\n enabled: config.discovery.enabled ?? true,\n },\n };\n this.#trace = trace ?? traceFallback;\n }\n\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 EvmAccountProvider.NAME;\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 /**\n * Create an EVM account.\n *\n * @param opts - The options for the creation of the account.\n * @param opts.entropySource - The entropy source to use for the creation of the account.\n * @param opts.groupIndex - The index of the group to create the account for.\n * @param opts.throwOnGap - Whether to throw an error if the account index is not contiguous.\n * @returns The created or existing keyring account(s) at the requested group\n * index. Returns an empty array if the keyring did not create an account.\n */\n async #createAccount({\n entropySource,\n groupIndex,\n throwOnGap,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n throwOnGap: boolean;\n }): Promise<KeyringAccount[]> {\n return await this.withKeyringV2<Keyring, KeyringAccount[]>(\n { id: entropySource },\n async ({ keyring }) => {\n const existing = await keyring.getAccounts();\n if (groupIndex < existing.length) {\n return [existing[groupIndex]];\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 return await keyring.createAccounts({\n type: AccountCreationType.Bip44DeriveIndex,\n entropySource,\n groupIndex,\n });\n },\n );\n }\n\n /**\n * Create accounts for the EVM provider.\n *\n * @param options - The options for the creation of the accounts.\n * @returns The accounts for the EVM provider.\n */\n async createAccounts(\n options: CreateAccountOptions,\n ): Promise<Bip44Account<KeyringAccount>[]> {\n assertCreateAccountOptionIsSupported(options, [\n `${AccountCreationType.Bip44DeriveIndex}`,\n `${AccountCreationType.Bip44DeriveIndexRange}`,\n ]);\n\n const { entropySource } = options;\n\n if (options.type === AccountCreationType.Bip44DeriveIndexRange) {\n const { range } = options;\n\n // Use a single withKeyring call for the entire range.\n const accountIds = await this.withKeyringV2<Keyring, AccountId[]>(\n { id: entropySource },\n async ({ keyring }) => {\n const existing = await keyring.getAccounts();\n\n // Validate no gaps: we can only create accounts starting from existing.length.\n if (range.from > existing.length) {\n throw new Error(\n `Bad account creation request, group index range would create gaps (${range.from} (from) > ${existing.length} (next available index))`,\n );\n }\n\n const result: AccountId[] = [];\n\n // Collect existing accounts within the range.\n for (\n let groupIndex = range.from;\n groupIndex <= range.to;\n groupIndex++\n ) {\n if (groupIndex < existing.length) {\n // Account already exists.\n result.push(existing[groupIndex].id);\n }\n }\n\n // Create new accounts one-by-one since HdKeyringV2 only supports\n // bip44:derive-index (not bip44:derive-index-range).\n for (\n let groupIndex = Math.max(range.from, existing.length);\n groupIndex <= range.to;\n groupIndex++\n ) {\n const [created] = await keyring.createAccounts({\n type: AccountCreationType.Bip44DeriveIndex,\n entropySource,\n groupIndex,\n });\n assert(created, 'Account creation failed');\n result.push(created.id);\n }\n\n return result;\n },\n );\n\n const accounts: InternalAccount[] = [];\n for (const account of this.messenger.call(\n 'AccountsController:getAccounts',\n accountIds,\n )) {\n assertInternalAccountExists(account);\n this.accounts.add(account.id);\n accounts.push(account);\n }\n\n assertAreBip44Accounts(accounts);\n return accounts;\n }\n\n // Handle Bip44DeriveIndex (single account creation).\n const { groupIndex } = options;\n\n const [created] = await this.#createAccount({\n entropySource,\n groupIndex,\n throwOnGap: true,\n });\n\n assert(created, 'Account creation failed');\n\n const account = this.messenger.call(\n 'AccountsController:getAccount',\n created.id,\n );\n\n // We MUST have the associated internal account.\n assertInternalAccountExists(account);\n\n const accountsArray = [account];\n assertAreBip44Accounts(accountsArray);\n\n this.accounts.add(account.id);\n return accountsArray;\n }\n\n /**\n * Get the address that would be derived for a given group index without\n * persisting an account in the keyring.\n *\n * Peeks at the next address via the HD `root` so discovery can short-circuit\n * (and skip the vault write + `stateChange` event) when there is no on-chain\n * activity at this index.\n *\n * @param opts - The options for the address derivation.\n * @param opts.entropySource - The entropy source to derive from.\n * @param opts.groupIndex - The group index to derive at.\n * @returns The derived address for the given group index.\n */\n async #getAddressFromGroupIndex({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Hex> {\n // NOTE: To avoid exposing this function at keyring level, we just re-use its internal state\n // and compute the derivation here.\n return await this.withKeyringV2<HdKeyring, Hex>(\n { id: entropySource },\n async ({ keyring }) => {\n // If the account already exist, do not re-derive and just re-use that account.\n const existing = await keyring.getAccounts();\n if (groupIndex < existing.length) {\n return existing[groupIndex].address as Hex;\n }\n\n // If not, then we just \"peek\" the next address to avoid creating the account.\n assert(keyring.root, 'Expected HD keyring.root to be set');\n const hdKey = keyring.root.deriveChild(groupIndex);\n assert(hdKey.publicKey, 'Expected public key to be set');\n\n return add0x(\n bytesToHex(publicToAddress(hdKey.publicKey, true)).toLowerCase(),\n );\n },\n );\n }\n\n /**\n * Get the transaction count for an EVM account.\n * This method uses a retry and timeout mechanism to handle transient failures.\n *\n * @param provider - The provider to use for the transaction count.\n * @param address - The address of the account.\n * @returns The transaction count.\n */\n async #getTransactionCount(\n provider: Provider,\n address: string,\n ): Promise<number> {\n const method = 'eth_getTransactionCount';\n\n const response = await withRetry(\n () =>\n withTimeout(\n () =>\n provider.request({\n method,\n params: [address, 'latest'],\n }),\n this.#config.discovery.timeoutMs,\n ),\n {\n maxAttempts: this.#config.discovery.maxAttempts,\n backOffMs: this.#config.discovery.backOffMs,\n },\n );\n\n // Make sure we got the right response format, if not, we fallback to \"0x0\", to avoid having to deal with `NaN`.\n if (!isStrictHexString(response)) {\n const message = `Received invalid hex response from \"${method}\" request: ${JSON.stringify(response)}`;\n\n log(`${WARNING_PREFIX} ${message}`);\n console.warn(message);\n\n return 0;\n }\n\n return parseInt(response, 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 return this.#trace(\n {\n name: TraceName.EvmDiscoverAccounts,\n data: {\n provider: this.getName(),\n },\n },\n async () => {\n if (!this.#config.discovery.enabled) {\n return [];\n }\n\n const provider = this.getEvmProvider();\n const { entropySource, groupIndex } = opts;\n\n const addressFromGroupIndex = await this.#getAddressFromGroupIndex({\n entropySource,\n groupIndex,\n });\n\n const count = await this.#getTransactionCount(\n provider,\n addressFromGroupIndex,\n );\n if (count === 0) {\n return [];\n }\n\n // We have some activity on this address, we try to create the account.\n const [created] = await this.#createAccount({\n entropySource,\n groupIndex,\n throwOnGap: false,\n });\n\n assert(created, 'Account creation failed');\n assert(\n addressFromGroupIndex === created.address,\n 'Created account does not match address from group index.',\n );\n\n const account = this.messenger.call(\n 'AccountsController:getAccount',\n created.id,\n );\n assertInternalAccountExists(account);\n assertIsBip44Account(account);\n this.accounts.add(account.id);\n return [account];\n },\n );\n }\n\n async resyncAccounts(): Promise<void> {\n // No-op for the EVM account provider, since keyring accounts are already on\n // the MetaMask side.\n }\n}\n"]}
1
+ {"version":3,"file":"EvmAccountProvider.mjs","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,yBAAyB;AASnD,OAAO,EACL,mBAAmB,EACnB,oCAAoC,EACpC,cAAc,EACd,QAAQ,EACT,8BAA8B;AAE/B,OAAO,EAAE,YAAY,EAAE,qCAAqC;AAI5D,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,iBAAiB,EAAE,wBAAwB;AAG/E,OAAO,EAAE,aAAa,EAAE,+BAAqB;AAC7C,OAAO,EAAE,SAAS,EAAE,gCAA4B;AAChD,OAAO,EAAE,aAAa,IAAI,GAAG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/util';\nimport type { Bip44Account } from '@metamask/account-api';\nimport type { TraceCallback } from '@metamask/controller-utils';\nimport type { HdKeyring } from '@metamask/eth-hd-keyring/v2';\nimport type {\n CreateAccountOptions,\n EntropySourceId,\n KeyringAccount,\n} from '@metamask/keyring-api';\nimport {\n AccountCreationType,\n assertCreateAccountOptionIsSupported,\n EthAccountType,\n EthScope,\n} from '@metamask/keyring-api';\nimport type { KeyringCapabilities, Keyring } from '@metamask/keyring-api/v2';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { AccountId } from '@metamask/keyring-utils';\nimport type { Provider } from '@metamask/network-controller';\nimport { add0x, assert, bytesToHex, isStrictHexString } from '@metamask/utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { traceFallback } from '../analytics';\nimport { TraceName } from '../analytics/traces';\nimport { projectLogger as log, WARNING_PREFIX } from '../logger';\nimport type { MultichainAccountServiceMessenger } from '../types';\nimport {\n assertAreBip44Accounts,\n assertIsBip44Account,\n BaseBip44AccountProvider,\n} from './BaseBip44AccountProvider';\nimport { withRetry, withTimeout } from './utils';\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 type EvmAccountProviderConfig = {\n discovery: {\n enabled?: boolean;\n maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n};\n\nexport const EVM_ACCOUNT_PROVIDER_NAME = 'EVM';\n\nexport const EVM_ACCOUNT_PROVIDER_DEFAULT_CONFIG = {\n discovery: {\n maxAttempts: 3,\n timeoutMs: 500,\n backOffMs: 500,\n },\n};\n\nexport class EvmAccountProvider extends BaseBip44AccountProvider {\n static NAME = EVM_ACCOUNT_PROVIDER_NAME;\n\n readonly #config: EvmAccountProviderConfig;\n\n readonly #trace: TraceCallback;\n\n readonly capabilities: KeyringCapabilities = {\n scopes: [EthScope.Eoa],\n bip44: {\n deriveIndex: true,\n deriveIndexRange: true,\n },\n };\n\n constructor(\n messenger: MultichainAccountServiceMessenger,\n config: EvmAccountProviderConfig = EVM_ACCOUNT_PROVIDER_DEFAULT_CONFIG,\n trace?: TraceCallback,\n ) {\n super(messenger);\n this.#config = {\n ...config,\n discovery: {\n ...config.discovery,\n enabled: config.discovery.enabled ?? true,\n },\n };\n this.#trace = trace ?? traceFallback;\n }\n\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 EvmAccountProvider.NAME;\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 /**\n * Create an EVM account.\n *\n * @param opts - The options for the creation of the account.\n * @param opts.entropySource - The entropy source to use for the creation of the account.\n * @param opts.groupIndex - The index of the group to create the account for.\n * @param opts.throwOnGap - Whether to throw an error if the account index is not contiguous.\n * @returns The created or existing keyring account(s) at the requested group\n * index. Returns an empty array if the keyring did not create an account.\n */\n async #createAccount({\n entropySource,\n groupIndex,\n throwOnGap,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n throwOnGap: boolean;\n }): Promise<KeyringAccount[]> {\n return await this.withKeyringV2<Keyring, KeyringAccount[]>(\n { id: entropySource },\n async ({ keyring }) => {\n const existing = await keyring.getAccounts();\n if (groupIndex < existing.length) {\n return [existing[groupIndex]];\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 return await keyring.createAccounts({\n type: AccountCreationType.Bip44DeriveIndex,\n entropySource,\n groupIndex,\n });\n },\n );\n }\n\n /**\n * Create accounts for the EVM provider.\n *\n * @param options - The options for the creation of the accounts.\n * @returns The accounts for the EVM provider.\n */\n async createAccounts(\n options: CreateAccountOptions,\n ): Promise<Bip44Account<KeyringAccount>[]> {\n assertCreateAccountOptionIsSupported(options, [\n `${AccountCreationType.Bip44DeriveIndex}`,\n `${AccountCreationType.Bip44DeriveIndexRange}`,\n ]);\n\n const { entropySource } = options;\n\n if (options.type === AccountCreationType.Bip44DeriveIndexRange) {\n const { range } = options;\n\n // Use a single withKeyring call for the entire range.\n const accountIds = await this.withKeyringV2<Keyring, AccountId[]>(\n { id: entropySource },\n async ({ keyring }) => {\n const existing = await keyring.getAccounts();\n\n // Validate no gaps: we can only create accounts starting from existing.length.\n if (range.from > existing.length) {\n throw new Error(\n `Bad account creation request, group index range would create gaps (${range.from} (from) > ${existing.length} (next available index))`,\n );\n }\n\n const result: AccountId[] = [];\n\n // Collect existing accounts within the range.\n for (\n let groupIndex = range.from;\n groupIndex <= range.to;\n groupIndex++\n ) {\n if (groupIndex < existing.length) {\n // Account already exists.\n result.push(existing[groupIndex].id);\n }\n }\n\n // Create new accounts one-by-one since HdKeyringV2 only supports\n // bip44:derive-index (not bip44:derive-index-range).\n for (\n let groupIndex = Math.max(range.from, existing.length);\n groupIndex <= range.to;\n groupIndex++\n ) {\n const [created] = await keyring.createAccounts({\n type: AccountCreationType.Bip44DeriveIndex,\n entropySource,\n groupIndex,\n });\n assert(created, 'Account creation failed');\n result.push(created.id);\n }\n\n return result;\n },\n );\n\n const accounts: InternalAccount[] = [];\n for (const account of this.messenger.call(\n 'AccountsController:getAccounts',\n accountIds,\n )) {\n assertInternalAccountExists(account);\n this.accounts.add(account.id);\n accounts.push(account);\n }\n\n assertAreBip44Accounts(accounts);\n return accounts;\n }\n\n // Handle Bip44DeriveIndex (single account creation).\n const { groupIndex } = options;\n\n const [created] = await this.#createAccount({\n entropySource,\n groupIndex,\n throwOnGap: true,\n });\n\n assert(created, 'Account creation failed');\n\n const account = this.messenger.call(\n 'AccountsController:getAccount',\n created.id,\n );\n\n // We MUST have the associated internal account.\n assertInternalAccountExists(account);\n\n const accountsArray = [account];\n assertAreBip44Accounts(accountsArray);\n\n this.accounts.add(account.id);\n return accountsArray;\n }\n\n /**\n * Get the address that would be derived for a given group index without\n * persisting an account in the keyring.\n *\n * Peeks at the next address via the HD `root` so discovery can short-circuit\n * (and skip the vault write + `stateChange` event) when there is no on-chain\n * activity at this index.\n *\n * @param opts - The options for the address derivation.\n * @param opts.entropySource - The entropy source to derive from.\n * @param opts.groupIndex - The group index to derive at.\n * @returns The derived address for the given group index.\n */\n async #getAddressFromGroupIndex({\n entropySource,\n groupIndex,\n }: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Hex> {\n // NOTE: To avoid exposing this function at keyring level, we just re-use its internal state\n // and compute the derivation here.\n return await this.withKeyringV2<HdKeyring, Hex>(\n { id: entropySource },\n async ({ keyring }) => {\n // If the account already exist, do not re-derive and just re-use that account.\n const existing = await keyring.getAccounts();\n if (groupIndex < existing.length) {\n return existing[groupIndex].address as Hex;\n }\n\n // If not, then we just \"peek\" the next address to avoid creating the account.\n assert(keyring.root, 'Expected HD keyring.root to be set');\n const hdKey = keyring.root.deriveChild(groupIndex);\n assert(hdKey.publicKey, 'Expected public key to be set');\n\n return add0x(\n bytesToHex(publicToAddress(hdKey.publicKey, true)).toLowerCase(),\n );\n },\n );\n }\n\n /**\n * Get the transaction count for an EVM account.\n * This method uses a retry and timeout mechanism to handle transient failures.\n *\n * @param provider - The provider to use for the transaction count.\n * @param address - The address of the account.\n * @returns The transaction count.\n */\n async #getTransactionCount(\n provider: Provider,\n address: string,\n ): Promise<number> {\n const method = 'eth_getTransactionCount';\n\n const response = await withRetry(\n () =>\n withTimeout(\n () =>\n provider.request({\n method,\n params: [address, 'latest'],\n }),\n this.#config.discovery.timeoutMs,\n ),\n {\n maxAttempts: this.#config.discovery.maxAttempts,\n backOffMs: this.#config.discovery.backOffMs,\n },\n );\n\n // Make sure we got the right response format, if not, we fallback to \"0x0\", to avoid having to deal with `NaN`.\n if (!isStrictHexString(response)) {\n const message = `Received invalid hex response from \"${method}\" request: ${JSON.stringify(response)}`;\n\n log(`${WARNING_PREFIX} ${message}`);\n console.warn(message);\n\n return 0;\n }\n\n return parseInt(response, 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 return this.#trace(\n {\n name: TraceName.EvmDiscoverAccounts,\n data: {\n provider: this.getName(),\n },\n },\n async () => {\n if (!this.#config.discovery.enabled) {\n return [];\n }\n\n const provider = this.getEvmProvider();\n const { entropySource, groupIndex } = opts;\n\n const addressFromGroupIndex = await this.#getAddressFromGroupIndex({\n entropySource,\n groupIndex,\n });\n\n const count = await this.#getTransactionCount(\n provider,\n addressFromGroupIndex,\n );\n if (count === 0) {\n return [];\n }\n\n // We have some activity on this address, we try to create the account.\n const [created] = await this.#createAccount({\n entropySource,\n groupIndex,\n throwOnGap: false,\n });\n\n assert(created, 'Account creation failed');\n assert(\n addressFromGroupIndex === created.address,\n 'Created account does not match address from group index.',\n );\n\n const account = this.messenger.call(\n 'AccountsController:getAccount',\n created.id,\n );\n assertInternalAccountExists(account);\n assertIsBip44Account(account);\n this.accounts.add(account.id);\n return [account];\n },\n );\n }\n\n async resyncAccounts(): Promise<void> {\n // No-op for the EVM account provider, since keyring accounts are already on\n // the MetaMask side.\n }\n\n /**\n * Delete an EVM account by id.\n *\n * Resolves the account's entropy source from the tracked account, then\n * forwards to the v2 HD keyring's `deleteAccount(id)`. When this is the\n * last account on a non-primary HD keyring, the keyring controller will\n * automatically prune the empty keyring (see\n * `KeyringController.#cleanUpEmptiedKeyringsAfter`).\n *\n * @param id - The id of the account to delete.\n */\n async deleteAccount(id: Bip44Account<KeyringAccount>['id']): Promise<void> {\n const account = this.getAccount(id);\n const entropySource = account.options.entropy.id;\n\n await this.withKeyringV2<Keyring>(\n { id: entropySource },\n async ({ keyring }) => {\n await keyring.deleteAccount(id);\n },\n );\n\n this.accounts.delete(id);\n }\n}\n"]}