@metamask-previews/multichain-account-service 2.1.0-preview-037e3643 → 2.1.0-preview-1a8571ae

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 (122) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/MultichainAccountGroup.cjs.map +1 -1
  3. package/dist/MultichainAccountGroup.d.cts +2 -2
  4. package/dist/MultichainAccountGroup.d.mts +2 -2
  5. package/dist/MultichainAccountGroup.mjs.map +1 -1
  6. package/dist/MultichainAccountService.cjs +49 -5
  7. package/dist/MultichainAccountService.cjs.map +1 -1
  8. package/dist/MultichainAccountService.d.cts +23 -6
  9. package/dist/MultichainAccountService.d.cts.map +1 -1
  10. package/dist/MultichainAccountService.d.mts +23 -6
  11. package/dist/MultichainAccountService.d.mts.map +1 -1
  12. package/dist/MultichainAccountService.mjs +49 -5
  13. package/dist/MultichainAccountService.mjs.map +1 -1
  14. package/dist/MultichainAccountWallet.cjs.map +1 -1
  15. package/dist/MultichainAccountWallet.d.cts +2 -2
  16. package/dist/MultichainAccountWallet.d.mts +2 -2
  17. package/dist/MultichainAccountWallet.mjs.map +1 -1
  18. package/dist/analytics/index.cjs +18 -0
  19. package/dist/analytics/index.cjs.map +1 -0
  20. package/dist/analytics/index.d.cts +2 -0
  21. package/dist/analytics/index.d.cts.map +1 -0
  22. package/dist/analytics/index.d.mts +2 -0
  23. package/dist/analytics/index.d.mts.map +1 -0
  24. package/dist/analytics/index.mjs +2 -0
  25. package/dist/analytics/index.mjs.map +1 -0
  26. package/dist/analytics/traces.cjs +21 -0
  27. package/dist/analytics/traces.cjs.map +1 -0
  28. package/dist/analytics/traces.d.cts +13 -0
  29. package/dist/analytics/traces.d.cts.map +1 -0
  30. package/dist/analytics/traces.d.mts +13 -0
  31. package/dist/analytics/traces.d.mts.map +1 -0
  32. package/dist/analytics/traces.mjs +17 -0
  33. package/dist/analytics/traces.mjs.map +1 -0
  34. package/dist/constants/traces.cjs +9 -0
  35. package/dist/constants/traces.cjs.map +1 -0
  36. package/dist/constants/traces.d.cts +5 -0
  37. package/dist/constants/traces.d.cts.map +1 -0
  38. package/dist/constants/traces.d.mts +5 -0
  39. package/dist/constants/traces.d.mts.map +1 -0
  40. package/dist/constants/traces.mjs +6 -0
  41. package/dist/constants/traces.mjs.map +1 -0
  42. package/dist/providers/AccountProviderWrapper.cjs +11 -0
  43. package/dist/providers/AccountProviderWrapper.cjs.map +1 -1
  44. package/dist/providers/AccountProviderWrapper.d.cts +7 -0
  45. package/dist/providers/AccountProviderWrapper.d.cts.map +1 -1
  46. package/dist/providers/AccountProviderWrapper.d.mts +7 -0
  47. package/dist/providers/AccountProviderWrapper.d.mts.map +1 -1
  48. package/dist/providers/AccountProviderWrapper.mjs +11 -0
  49. package/dist/providers/AccountProviderWrapper.mjs.map +1 -1
  50. package/dist/providers/BaseBip44AccountProvider.cjs.map +1 -1
  51. package/dist/providers/BaseBip44AccountProvider.d.cts +13 -3
  52. package/dist/providers/BaseBip44AccountProvider.d.cts.map +1 -1
  53. package/dist/providers/BaseBip44AccountProvider.d.mts +13 -3
  54. package/dist/providers/BaseBip44AccountProvider.d.mts.map +1 -1
  55. package/dist/providers/BaseBip44AccountProvider.mjs.map +1 -1
  56. package/dist/providers/BtcAccountProvider.cjs +23 -43
  57. package/dist/providers/BtcAccountProvider.cjs.map +1 -1
  58. package/dist/providers/BtcAccountProvider.d.cts +3 -21
  59. package/dist/providers/BtcAccountProvider.d.cts.map +1 -1
  60. package/dist/providers/BtcAccountProvider.d.mts +3 -21
  61. package/dist/providers/BtcAccountProvider.d.mts.map +1 -1
  62. package/dist/providers/BtcAccountProvider.mjs +23 -43
  63. package/dist/providers/BtcAccountProvider.mjs.map +1 -1
  64. package/dist/providers/EvmAccountProvider.cjs +37 -22
  65. package/dist/providers/EvmAccountProvider.cjs.map +1 -1
  66. package/dist/providers/EvmAccountProvider.d.cts +3 -1
  67. package/dist/providers/EvmAccountProvider.d.cts.map +1 -1
  68. package/dist/providers/EvmAccountProvider.d.mts +3 -1
  69. package/dist/providers/EvmAccountProvider.d.mts.map +1 -1
  70. package/dist/providers/EvmAccountProvider.mjs +37 -22
  71. package/dist/providers/EvmAccountProvider.mjs.map +1 -1
  72. package/dist/providers/SnapAccountProvider.cjs +80 -9
  73. package/dist/providers/SnapAccountProvider.cjs.map +1 -1
  74. package/dist/providers/SnapAccountProvider.d.cts +6 -1
  75. package/dist/providers/SnapAccountProvider.d.cts.map +1 -1
  76. package/dist/providers/SnapAccountProvider.d.mts +6 -1
  77. package/dist/providers/SnapAccountProvider.d.mts.map +1 -1
  78. package/dist/providers/SnapAccountProvider.mjs +80 -9
  79. package/dist/providers/SnapAccountProvider.mjs.map +1 -1
  80. package/dist/providers/SolAccountProvider.cjs +25 -38
  81. package/dist/providers/SolAccountProvider.cjs.map +1 -1
  82. package/dist/providers/SolAccountProvider.d.cts +2 -1
  83. package/dist/providers/SolAccountProvider.d.cts.map +1 -1
  84. package/dist/providers/SolAccountProvider.d.mts +2 -1
  85. package/dist/providers/SolAccountProvider.d.mts.map +1 -1
  86. package/dist/providers/SolAccountProvider.mjs +25 -38
  87. package/dist/providers/SolAccountProvider.mjs.map +1 -1
  88. package/dist/providers/TrxAccountProvider.cjs +22 -43
  89. package/dist/providers/TrxAccountProvider.cjs.map +1 -1
  90. package/dist/providers/TrxAccountProvider.d.cts +2 -2
  91. package/dist/providers/TrxAccountProvider.d.cts.map +1 -1
  92. package/dist/providers/TrxAccountProvider.d.mts +2 -2
  93. package/dist/providers/TrxAccountProvider.d.mts.map +1 -1
  94. package/dist/providers/TrxAccountProvider.mjs +22 -43
  95. package/dist/providers/TrxAccountProvider.mjs.map +1 -1
  96. package/dist/providers/utils.cjs.map +1 -1
  97. package/dist/providers/utils.mjs.map +1 -1
  98. package/dist/tests/accounts.cjs +28 -1
  99. package/dist/tests/accounts.cjs.map +1 -1
  100. package/dist/tests/accounts.d.cts +11 -7
  101. package/dist/tests/accounts.d.cts.map +1 -1
  102. package/dist/tests/accounts.d.mts +11 -7
  103. package/dist/tests/accounts.d.mts.map +1 -1
  104. package/dist/tests/accounts.mjs +25 -0
  105. package/dist/tests/accounts.mjs.map +1 -1
  106. package/dist/tests/providers.cjs +1 -0
  107. package/dist/tests/providers.cjs.map +1 -1
  108. package/dist/tests/providers.d.cts +1 -0
  109. package/dist/tests/providers.d.cts.map +1 -1
  110. package/dist/tests/providers.d.mts +1 -0
  111. package/dist/tests/providers.d.mts.map +1 -1
  112. package/dist/tests/providers.mjs +1 -0
  113. package/dist/tests/providers.mjs.map +1 -1
  114. package/dist/types.cjs.map +1 -1
  115. package/dist/types.d.cts +9 -1
  116. package/dist/types.d.cts.map +1 -1
  117. package/dist/types.d.mts +9 -1
  118. package/dist/types.d.mts.map +1 -1
  119. package/dist/types.mjs.map +1 -1
  120. package/dist/utils.cjs.map +1 -1
  121. package/dist/utils.mjs.map +1 -1
  122. package/package.json +2 -2
@@ -1,4 +1,5 @@
1
1
  import type { Bip44Account } from "@metamask/account-api";
2
+ import type { TraceCallback } from "@metamask/controller-utils";
2
3
  import type { EntropySourceId, KeyringAccount } from "@metamask/keyring-api";
3
4
  import type { InternalAccount } from "@metamask/keyring-internal-api";
4
5
  import type { Provider } from "@metamask/network-controller";
@@ -15,7 +16,7 @@ export declare const EVM_ACCOUNT_PROVIDER_NAME: "EVM";
15
16
  export declare class EvmAccountProvider extends BaseBip44AccountProvider {
16
17
  #private;
17
18
  static NAME: "EVM";
18
- constructor(messenger: MultichainAccountServiceMessenger, config?: EvmAccountProviderConfig);
19
+ constructor(messenger: MultichainAccountServiceMessenger, config?: EvmAccountProviderConfig, trace?: TraceCallback);
19
20
  isAccountCompatible(account: Bip44Account<InternalAccount>): boolean;
20
21
  getName(): string;
21
22
  /**
@@ -40,5 +41,6 @@ export declare class EvmAccountProvider extends BaseBip44AccountProvider {
40
41
  entropySource: EntropySourceId;
41
42
  groupIndex: number;
42
43
  }): Promise<Bip44Account<KeyringAccount>[]>;
44
+ resyncAccounts(): Promise<void>;
43
45
  }
44
46
  //# 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;AAE1D,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;AAEpC,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAiB;AAkBlE,MAAM,MAAM,wBAAwB,GAAG;IACrC,SAAS,EAAE;QACT,WAAW,EAAE,MAAM,CAAC;QACpB,SAAS,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;CACH,CAAC;AAEF,eAAO,MAAM,yBAAyB,OAAiB,CAAC;AAExD,qBAAa,kBAAmB,SAAQ,wBAAwB;;IAC9D,MAAM,CAAC,IAAI,QAA6B;gBAKtC,SAAS,EAAE,iCAAiC,EAC5C,MAAM,GAAE,wBAMP;IAMH,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;IAyE3C;;;;;;;OAOG;IACG,gBAAgB,CAAC,IAAI,EAAE;QAC3B,aAAa,EAAE,eAAe,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAA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U,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;IA8CrC,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;CAItC"}
@@ -1,4 +1,5 @@
1
1
  import type { Bip44Account } from "@metamask/account-api";
2
+ import type { TraceCallback } from "@metamask/controller-utils";
2
3
  import type { EntropySourceId, KeyringAccount } from "@metamask/keyring-api";
3
4
  import type { InternalAccount } from "@metamask/keyring-internal-api";
4
5
  import type { Provider } from "@metamask/network-controller";
@@ -15,7 +16,7 @@ export declare const EVM_ACCOUNT_PROVIDER_NAME: "EVM";
15
16
  export declare class EvmAccountProvider extends BaseBip44AccountProvider {
16
17
  #private;
17
18
  static NAME: "EVM";
18
- constructor(messenger: MultichainAccountServiceMessenger, config?: EvmAccountProviderConfig);
19
+ constructor(messenger: MultichainAccountServiceMessenger, config?: EvmAccountProviderConfig, trace?: TraceCallback);
19
20
  isAccountCompatible(account: Bip44Account<InternalAccount>): boolean;
20
21
  getName(): string;
21
22
  /**
@@ -40,5 +41,6 @@ export declare class EvmAccountProvider extends BaseBip44AccountProvider {
40
41
  entropySource: EntropySourceId;
41
42
  groupIndex: number;
42
43
  }): Promise<Bip44Account<KeyringAccount>[]>;
44
+ resyncAccounts(): Promise<void>;
43
45
  }
44
46
  //# 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;AAE1D,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;AAEpC,OAAO,KAAK,EAAE,iCAAiC,EAAE,qB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iC,EAAE,qBAAiB;AAkBlE,MAAM,MAAM,wBAAwB,GAAG;IACrC,SAAS,EAAE;QACT,WAAW,EAAE,MAAM,CAAC;QACpB,SAAS,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;CACH,CAAC;AAEF,eAAO,MAAM,yBAAyB,OAAiB,CAAC;AAExD,qBAAa,kBAAmB,SAAQ,wBAAwB;;IAC9D,MAAM,CAAC,IAAI,QAA6B;gBAOtC,SAAS,EAAE,iCAAiC,EAC5C,MAAM,GAAE,wBAMP,EACD,KAAK,CAAC,EAAE,aAAa;IAOvB,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;IAyE3C;;;;;;;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;IA8CrC,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;CAItC"}
@@ -9,13 +9,15 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  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");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _EvmAccountProvider_instances, _EvmAccountProvider_config, _EvmAccountProvider_createAccount, _EvmAccountProvider_getTransactionCount, _EvmAccountProvider_getAddressFromGroupIndex;
12
+ var _EvmAccountProvider_instances, _EvmAccountProvider_config, _EvmAccountProvider_trace, _EvmAccountProvider_createAccount, _EvmAccountProvider_getTransactionCount, _EvmAccountProvider_getAddressFromGroupIndex;
13
13
  import { publicToAddress } from "@ethereumjs/util";
14
14
  import { EthAccountType } from "@metamask/keyring-api";
15
15
  import { KeyringTypes } from "@metamask/keyring-controller";
16
16
  import { add0x, assert, bytesToHex } from "@metamask/utils";
17
17
  import { assertAreBip44Accounts, assertIsBip44Account, BaseBip44AccountProvider } from "./BaseBip44AccountProvider.mjs";
18
18
  import { withRetry, withTimeout } from "./utils.mjs";
19
+ import { traceFallback } from "../analytics/index.mjs";
20
+ import { TraceName } from "../constants/traces.mjs";
19
21
  const ETH_MAINNET_CHAIN_ID = '0x1';
20
22
  /**
21
23
  * Asserts an internal account exists.
@@ -36,11 +38,13 @@ export class EvmAccountProvider extends BaseBip44AccountProvider {
36
38
  timeoutMs: 500,
37
39
  backOffMs: 500,
38
40
  },
39
- }) {
41
+ }, trace) {
40
42
  super(messenger);
41
43
  _EvmAccountProvider_instances.add(this);
42
44
  _EvmAccountProvider_config.set(this, void 0);
45
+ _EvmAccountProvider_trace.set(this, void 0);
43
46
  __classPrivateFieldSet(this, _EvmAccountProvider_config, config, "f");
47
+ __classPrivateFieldSet(this, _EvmAccountProvider_trace, trace ?? traceFallback, "f");
44
48
  }
45
49
  isAccountCompatible(account) {
46
50
  return (account.type === EthAccountType.Eoa &&
@@ -81,29 +85,40 @@ export class EvmAccountProvider extends BaseBip44AccountProvider {
81
85
  * @returns The accounts for the EVM provider.
82
86
  */
83
87
  async discoverAccounts(opts) {
84
- const provider = this.getEvmProvider();
85
- const { entropySource, groupIndex } = opts;
86
- const addressFromGroupIndex = await __classPrivateFieldGet(this, _EvmAccountProvider_instances, "m", _EvmAccountProvider_getAddressFromGroupIndex).call(this, {
87
- entropySource,
88
- groupIndex,
89
- });
90
- const count = await __classPrivateFieldGet(this, _EvmAccountProvider_instances, "m", _EvmAccountProvider_getTransactionCount).call(this, provider, addressFromGroupIndex);
91
- if (count === 0) {
92
- return [];
93
- }
94
- // We have some activity on this address, we try to create the account.
95
- const [address] = await __classPrivateFieldGet(this, _EvmAccountProvider_instances, "m", _EvmAccountProvider_createAccount).call(this, {
96
- entropySource,
97
- groupIndex,
88
+ return __classPrivateFieldGet(this, _EvmAccountProvider_trace, "f").call(this, {
89
+ name: TraceName.EvmDiscoverAccounts,
90
+ data: {
91
+ provider: this.getName(),
92
+ },
93
+ }, async () => {
94
+ const provider = this.getEvmProvider();
95
+ const { entropySource, groupIndex } = opts;
96
+ const addressFromGroupIndex = await __classPrivateFieldGet(this, _EvmAccountProvider_instances, "m", _EvmAccountProvider_getAddressFromGroupIndex).call(this, {
97
+ entropySource,
98
+ groupIndex,
99
+ });
100
+ const count = await __classPrivateFieldGet(this, _EvmAccountProvider_instances, "m", _EvmAccountProvider_getTransactionCount).call(this, provider, addressFromGroupIndex);
101
+ if (count === 0) {
102
+ return [];
103
+ }
104
+ // We have some activity on this address, we try to create the account.
105
+ const [address] = await __classPrivateFieldGet(this, _EvmAccountProvider_instances, "m", _EvmAccountProvider_createAccount).call(this, {
106
+ entropySource,
107
+ groupIndex,
108
+ });
109
+ assert(addressFromGroupIndex === address, 'Created account does not match address from group index.');
110
+ const account = this.messenger.call('AccountsController:getAccountByAddress', address);
111
+ assertInternalAccountExists(account);
112
+ assertIsBip44Account(account);
113
+ return [account];
98
114
  });
99
- assert(addressFromGroupIndex === address, 'Created account does not match address from group index.');
100
- const account = this.messenger.call('AccountsController:getAccountByAddress', address);
101
- assertInternalAccountExists(account);
102
- assertIsBip44Account(account);
103
- return [account];
115
+ }
116
+ async resyncAccounts() {
117
+ // No-op for the EVM account provider, since keyring accounts are already on
118
+ // the MetaMask side.
104
119
  }
105
120
  }
106
- _EvmAccountProvider_config = new WeakMap(), _EvmAccountProvider_instances = new WeakSet(), _EvmAccountProvider_createAccount = async function _EvmAccountProvider_createAccount({ entropySource, groupIndex, throwOnGap = false, }) {
121
+ _EvmAccountProvider_config = new WeakMap(), _EvmAccountProvider_trace = new WeakMap(), _EvmAccountProvider_instances = new WeakSet(), _EvmAccountProvider_createAccount = async function _EvmAccountProvider_createAccount({ entropySource, groupIndex, throwOnGap = false, }) {
107
122
  const result = await this.withKeyring({ id: entropySource }, async ({ keyring }) => {
108
123
  const existing = await keyring.getAccounts();
109
124
  if (groupIndex < existing.length) {
@@ -1 +1 @@
1
- {"version":3,"file":"EvmAccountProvider.mjs","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,yBAAyB;AAInD,OAAO,EAAE,cAAc,EAAE,8BAA8B;AACvD,OAAO,EAAE,YAAY,EAAE,qCAAqC;AAM5D,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAY,wBAAwB;AAEtE,OAAO,EACL,sBAAsB,EACtB,oBAAoB,EACpB,wBAAwB,EACzB,uCAAmC;AACpC,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,oBAAgB;AAGjD,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;AAUD,MAAM,CAAC,MAAM,yBAAyB,GAAG,KAAc,CAAC;AAExD,MAAM,OAAO,kBAAmB,SAAQ,wBAAwB;IAK9D,YACE,SAA4C,EAC5C,SAAmC;QACjC,SAAS,EAAE;YACT,WAAW,EAAE,CAAC;YACd,SAAS,EAAE,GAAG;YACd,SAAS,EAAE,GAAG;SACf;KACF;QAED,KAAK,CAAC,SAAS,CAAC,CAAC;;QAZV,6CAAkC;QAazC,uBAAA,IAAI,8BAAW,MAAM,MAAA,CAAC;IACxB,CAAC;IAED,mBAAmB,CAAC,OAAsC;QACxD,OAAO,CAC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EAAE,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE,CACjE,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC;AAzJM,uBAAI,GAAG,yBAAyB,AAA5B,CAA6B","sourcesContent":["import { publicToAddress } from '@ethereumjs/util';\nimport type { Bip44Account } from '@metamask/account-api';\nimport type { HdKeyring } from '@metamask/eth-hd-keyring';\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 { add0x, assert, bytesToHex, type Hex } from '@metamask/utils';\n\nimport {\n assertAreBip44Accounts,\n assertIsBip44Account,\n BaseBip44AccountProvider,\n} from './BaseBip44AccountProvider';\nimport { withRetry, withTimeout } from './utils';\nimport type { MultichainAccountServiceMessenger } from '../types';\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 maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n};\n\nexport const EVM_ACCOUNT_PROVIDER_NAME = 'EVM' as const;\n\nexport class EvmAccountProvider extends BaseBip44AccountProvider {\n static NAME = EVM_ACCOUNT_PROVIDER_NAME;\n\n readonly #config: EvmAccountProviderConfig;\n\n constructor(\n messenger: MultichainAccountServiceMessenger,\n config: EvmAccountProviderConfig = {\n discovery: {\n maxAttempts: 3,\n timeoutMs: 500,\n backOffMs: 500,\n },\n },\n ) {\n super(messenger);\n this.#config = config;\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 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 withRetry<Hex>(\n () =>\n withTimeout(\n provider.request({\n method: 'eth_getTransactionCount',\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 return parseInt(countHex, 16);\n }\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.withKeyring<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];\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 * 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 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 [address] = await this.#createAccount({\n entropySource,\n groupIndex,\n });\n assert(\n addressFromGroupIndex === address,\n 'Created account does not match address from group index.',\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.mjs","sourceRoot":"","sources":["../../src/providers/EvmAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,O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AAM,CAAC,KAAK,CAAC,SAAS,EAAE,+BAA+B,CAAC,CAAC;QAEzD,OAAO,KAAK,CACV,UAAU,CAAC,eAAe,CAAC,KAAK,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE,CACjE,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC;AA7JM,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';\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 { add0x, assert, bytesToHex, type Hex } from '@metamask/utils';\n\nimport {\n assertAreBip44Accounts,\n assertIsBip44Account,\n BaseBip44AccountProvider,\n} from './BaseBip44AccountProvider';\nimport { withRetry, withTimeout } from './utils';\nimport { traceFallback } from '../analytics';\nimport { TraceName } from '../constants/traces';\nimport type { MultichainAccountServiceMessenger } from '../types';\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 maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n};\n\nexport const EVM_ACCOUNT_PROVIDER_NAME = 'EVM' as const;\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 constructor(\n messenger: MultichainAccountServiceMessenger,\n config: EvmAccountProviderConfig = {\n discovery: {\n maxAttempts: 3,\n timeoutMs: 500,\n backOffMs: 500,\n },\n },\n trace?: TraceCallback,\n ) {\n super(messenger);\n this.#config = config;\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 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 withRetry<Hex>(\n () =>\n withTimeout(\n provider.request({\n method: 'eth_getTransactionCount',\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 return parseInt(countHex, 16);\n }\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.withKeyring<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];\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 * 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 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 [address] = await this.#createAccount({\n entropySource,\n groupIndex,\n });\n assert(\n addressFromGroupIndex === address,\n 'Created account does not match address from group index.',\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\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,26 +1,35 @@
1
1
  "use strict";
2
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
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
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
+ };
2
7
  var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
8
  if (kind === "m") throw new TypeError("Private method is not writable");
4
9
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
11
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
12
  };
8
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
- 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");
11
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
- };
13
- var _SnapAccountProvider_queue;
13
+ var _SnapAccountProvider_instances, _SnapAccountProvider_queue, _SnapAccountProvider_trace, _SnapAccountProvider_getKeyringClientFromSnapId, _SnapAccountProvider_withSnapKeyring;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.isSnapAccountProvider = exports.SnapAccountProvider = void 0;
16
16
  const keyring_controller_1 = require("@metamask/keyring-controller");
17
+ const keyring_snap_client_1 = require("@metamask/keyring-snap-client");
18
+ const snaps_utils_1 = require("@metamask/snaps-utils");
17
19
  const async_mutex_1 = require("async-mutex");
18
20
  const BaseBip44AccountProvider_1 = require("./BaseBip44AccountProvider.cjs");
21
+ const analytics_1 = require("../analytics/index.cjs");
22
+ const utils_1 = require("../utils.cjs");
19
23
  class SnapAccountProvider extends BaseBip44AccountProvider_1.BaseBip44AccountProvider {
20
- constructor(snapId, messenger, config) {
24
+ constructor(snapId, messenger, config,
25
+ /* istanbul ignore next */
26
+ trace = analytics_1.traceFallback) {
21
27
  super(messenger);
28
+ _SnapAccountProvider_instances.add(this);
22
29
  _SnapAccountProvider_queue.set(this, void 0);
30
+ _SnapAccountProvider_trace.set(this, void 0);
23
31
  this.snapId = snapId;
32
+ this.client = __classPrivateFieldGet(this, _SnapAccountProvider_instances, "m", _SnapAccountProvider_getKeyringClientFromSnapId).call(this, snapId);
24
33
  const maxConcurrency = config.maxConcurrency ?? Infinity;
25
34
  this.config = {
26
35
  ...config,
@@ -30,6 +39,7 @@ class SnapAccountProvider extends BaseBip44AccountProvider_1.BaseBip44AccountPro
30
39
  if (isFinite(maxConcurrency)) {
31
40
  __classPrivateFieldSet(this, _SnapAccountProvider_queue, new async_mutex_1.Semaphore(maxConcurrency), "f");
32
41
  }
42
+ __classPrivateFieldSet(this, _SnapAccountProvider_trace, trace, "f");
33
43
  }
34
44
  /**
35
45
  * Wraps an async operation with concurrency limiting based on maxConcurrency config.
@@ -45,6 +55,9 @@ class SnapAccountProvider extends BaseBip44AccountProvider_1.BaseBip44AccountPro
45
55
  }
46
56
  return operation();
47
57
  }
58
+ async trace(request, fn) {
59
+ return __classPrivateFieldGet(this, _SnapAccountProvider_trace, "f").call(this, request, fn);
60
+ }
48
61
  async getRestrictedSnapAccountCreator() {
49
62
  // NOTE: We're not supposed to make the keyring instance escape `withKeyring` but
50
63
  // we have to use the `SnapKeyring` instance to be able to create Solana account
@@ -52,16 +65,74 @@ class SnapAccountProvider extends BaseBip44AccountProvider_1.BaseBip44AccountPro
52
65
  // Also, creating account that way won't invalidate the Snap keyring state. The
53
66
  // account will get created and persisted properly with the Snap account creation
54
67
  // flow "asynchronously" (with `notify:accountCreated`).
55
- const createAccount = await this.withKeyring({ type: keyring_controller_1.KeyringTypes.snap }, async ({ keyring }) => keyring.createAccount.bind(keyring));
68
+ const createAccount = await __classPrivateFieldGet(this, _SnapAccountProvider_instances, "m", _SnapAccountProvider_withSnapKeyring).call(this, async ({ keyring }) => keyring.createAccount.bind(keyring));
56
69
  return (options) => createAccount(this.snapId, options, {
57
70
  displayAccountNameSuggestion: false,
58
71
  displayConfirmation: false,
59
72
  setSelectedAccount: false,
60
73
  });
61
74
  }
75
+ async resyncAccounts(accounts) {
76
+ const localSnapAccounts = accounts.filter((account) => account.metadata.snap && account.metadata.snap.id === this.snapId);
77
+ const snapAccounts = new Set((await this.client.listAccounts()).map((account) => account.id));
78
+ // NOTE: This should never happen, but we want to report that kind of errors still
79
+ // in case states are de-sync.
80
+ if (localSnapAccounts.length < snapAccounts.size) {
81
+ this.messenger.call('ErrorReportingService:captureException', new Error(`Snap "${this.snapId}" has de-synced accounts, Snap has more accounts than MetaMask!`));
82
+ // We don't recover from this case yet.
83
+ return;
84
+ }
85
+ // We want this part to be fast, so we only check for sizes, but we might need
86
+ // to make a real "diff" between the 2 states to not miss any de-sync.
87
+ if (localSnapAccounts.length > snapAccounts.size) {
88
+ // Accounts should never really be de-synced, so we want to log this to see how often this
89
+ // happens, cause that means that something else is buggy elsewhere...
90
+ this.messenger.call('ErrorReportingService:captureException', new Error(`Snap "${this.snapId}" has de-synced accounts, we'll attempt to re-sync them...`));
91
+ // We always use the MetaMask list as the main reference here.
92
+ await Promise.all(localSnapAccounts.map(async (account) => {
93
+ const { id: entropySource, groupIndex } = account.options.entropy;
94
+ try {
95
+ if (!snapAccounts.has(account.id)) {
96
+ // We still need to remove the accounts from the Snap keyring since we're
97
+ // about to create the same account again, which will use a new ID, but will
98
+ // keep using the same address, and the Snap keyring does not allow this.
99
+ await __classPrivateFieldGet(this, _SnapAccountProvider_instances, "m", _SnapAccountProvider_withSnapKeyring).call(this, async ({ keyring }) => await keyring.removeAccount(account.address));
100
+ // The Snap has no account in its state for this one, we re-create it.
101
+ await this.createAccounts({
102
+ entropySource,
103
+ groupIndex,
104
+ });
105
+ }
106
+ }
107
+ catch (error) {
108
+ const sentryError = (0, utils_1.createSentryError)(`Unable to re-sync account: ${groupIndex}`, error, {
109
+ provider: this.getName(),
110
+ groupIndex,
111
+ });
112
+ this.messenger.call('ErrorReportingService:captureException', sentryError);
113
+ }
114
+ }));
115
+ }
116
+ }
62
117
  }
63
118
  exports.SnapAccountProvider = SnapAccountProvider;
64
- _SnapAccountProvider_queue = new WeakMap();
119
+ _SnapAccountProvider_queue = new WeakMap(), _SnapAccountProvider_trace = new WeakMap(), _SnapAccountProvider_instances = new WeakSet(), _SnapAccountProvider_getKeyringClientFromSnapId = function _SnapAccountProvider_getKeyringClientFromSnapId(snapId) {
120
+ return new keyring_snap_client_1.KeyringClient({
121
+ send: async (request) => {
122
+ const response = await this.messenger.call('SnapController:handleRequest', {
123
+ snapId: snapId,
124
+ origin: 'metamask',
125
+ handler: snaps_utils_1.HandlerType.OnKeyringRequest,
126
+ request,
127
+ });
128
+ return response;
129
+ },
130
+ });
131
+ }, _SnapAccountProvider_withSnapKeyring = async function _SnapAccountProvider_withSnapKeyring(operation) {
132
+ return this.withKeyring({ type: keyring_controller_1.KeyringTypes.snap }, (args) => {
133
+ return operation(args);
134
+ });
135
+ };
65
136
  const isSnapAccountProvider = (provider) => {
66
137
  return provider instanceof SnapAccountProvider;
67
138
  };
@@ -1 +1 @@
1
- {"version":3,"file":"SnapAccountProvider.cjs","sourceRoot":"","s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AAE,KAAK;YAC1B,kBAAkB,EAAE,KAAK;SAC1B,CAAC,CAAC;IACP,CAAC;CAaF;AA9ED,kDA8EC;;AAEM,MAAM,qBAAqB,GAAG,CACnC,QAAiB,EACgB,EAAE;IACnC,OAAO,QAAQ,YAAY,mBAAmB,CAAC;AACjD,CAAC,CAAC;AAJW,QAAA,qBAAqB,yBAIhC","sourcesContent":["import { type Bip44Account } from '@metamask/account-api';\nimport type { SnapKeyring } from '@metamask/eth-snap-keyring';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { Json, SnapId } from '@metamask/snaps-sdk';\nimport { Semaphore } from 'async-mutex';\n\nimport { BaseBip44AccountProvider } from './BaseBip44AccountProvider';\nimport type { MultichainAccountServiceMessenger } from '../types';\n\nexport type RestrictedSnapKeyringCreateAccount = (\n options: Record<string, Json>,\n) => Promise<KeyringAccount>;\n\nexport type SnapAccountProviderConfig = {\n maxConcurrency?: number;\n discovery: {\n maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n createAccounts: {\n timeoutMs: number;\n };\n};\n\nexport abstract class SnapAccountProvider extends BaseBip44AccountProvider {\n readonly snapId: SnapId;\n\n protected readonly config: SnapAccountProviderConfig;\n\n readonly #queue?: Semaphore;\n\n constructor(\n snapId: SnapId,\n messenger: MultichainAccountServiceMessenger,\n config: SnapAccountProviderConfig,\n ) {\n super(messenger);\n\n this.snapId = snapId;\n\n const maxConcurrency = config.maxConcurrency ?? Infinity;\n this.config = {\n ...config,\n maxConcurrency,\n };\n\n // Create semaphore only if concurrency is limited\n if (isFinite(maxConcurrency)) {\n this.#queue = new Semaphore(maxConcurrency);\n }\n }\n\n /**\n * Wraps an async operation with concurrency limiting based on maxConcurrency config.\n * If maxConcurrency is Infinity (the default), the operation runs immediately without throttling.\n * Otherwise, it's queued through the semaphore to respect the concurrency limit.\n *\n * @param operation - The async operation to execute.\n * @returns The result of the operation.\n */\n protected async withMaxConcurrency<T>(\n operation: () => Promise<T>,\n ): Promise<T> {\n if (this.#queue) {\n return this.#queue.runExclusive(operation);\n }\n return operation();\n }\n\n protected async getRestrictedSnapAccountCreator(): Promise<RestrictedSnapKeyringCreateAccount> {\n // NOTE: We're not supposed to make the keyring instance escape `withKeyring` but\n // we have to use the `SnapKeyring` instance to be able to create Solana account\n // without triggering UI confirmation.\n // Also, creating account that way won't invalidate the Snap keyring state. The\n // account will get created and persisted properly with the Snap account creation\n // flow \"asynchronously\" (with `notify:accountCreated`).\n const createAccount = await this.withKeyring<\n SnapKeyring,\n SnapKeyring['createAccount']\n >({ type: KeyringTypes.snap }, async ({ keyring }) =>\n keyring.createAccount.bind(keyring),\n );\n\n return (options) =>\n createAccount(this.snapId, options, {\n displayAccountNameSuggestion: false,\n displayConfirmation: false,\n setSelectedAccount: false,\n });\n }\n\n abstract isAccountCompatible(account: Bip44Account<InternalAccount>): boolean;\n\n abstract createAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n\n abstract discoverAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n}\n\nexport const isSnapAccountProvider = (\n provider: unknown,\n): provider is SnapAccountProvider => {\n return provider instanceof SnapAccountProvider;\n};\n"]}
1
+ {"version":3,"file":"SnapAccountProvider.cjs","sourceRoot":"","sources":["../../src/providers/SnapAccountProvider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,qEAA4D;AAE5D,uEAA8D;AAE9D,uDAAoD;AACpD,6CAAwC;AAExC,6EAAsE;AACtE,sDAA6C;AAE7C,wCAA6C;AAkB7C,MAAsB,mBAAoB,SAAQ,mDAAwB;IAWxE,YACE,MAAc,EACd,SAA4C,EAC5C,MAAiC;IACjC,0BAA0B;IAC1B,QAAuB,yBAAa;QAEpC,KAAK,CAAC,SAAS,CAAC,CAAC;;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AAW,CACrB,EAAE,IAAI,EAAE,iCAAY,CAAC,IAAI,EAAE,EAC3B,CAAC,IAAI,EAAE,EAAE;QACP,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC;IACzB,CAAC,CACF,CAAC;AACJ,CAAC;AAeI,MAAM,qBAAqB,GAAG,CACnC,QAAiB,EACgB,EAAE;IACnC,OAAO,QAAQ,YAAY,mBAAmB,CAAC;AACjD,CAAC,CAAC;AAJW,QAAA,qBAAqB,yBAIhC","sourcesContent":["import { type Bip44Account } from '@metamask/account-api';\nimport type { TraceCallback, TraceRequest } from '@metamask/controller-utils';\nimport type { SnapKeyring } from '@metamask/eth-snap-keyring';\nimport type { EntropySourceId, KeyringAccount } from '@metamask/keyring-api';\nimport type { KeyringMetadata } from '@metamask/keyring-controller';\nimport { KeyringTypes } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { KeyringClient } from '@metamask/keyring-snap-client';\nimport type { Json, JsonRpcRequest, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { Semaphore } from 'async-mutex';\n\nimport { BaseBip44AccountProvider } from './BaseBip44AccountProvider';\nimport { traceFallback } from '../analytics';\nimport type { MultichainAccountServiceMessenger } from '../types';\nimport { createSentryError } from '../utils';\n\nexport type RestrictedSnapKeyringCreateAccount = (\n options: Record<string, Json>,\n) => Promise<KeyringAccount>;\n\nexport type SnapAccountProviderConfig = {\n maxConcurrency?: number;\n discovery: {\n maxAttempts: number;\n timeoutMs: number;\n backOffMs: number;\n };\n createAccounts: {\n timeoutMs: number;\n };\n};\n\nexport abstract class SnapAccountProvider extends BaseBip44AccountProvider {\n readonly snapId: SnapId;\n\n protected readonly config: SnapAccountProviderConfig;\n\n protected readonly client: KeyringClient;\n\n readonly #queue?: Semaphore;\n\n readonly #trace: TraceCallback;\n\n constructor(\n snapId: SnapId,\n messenger: MultichainAccountServiceMessenger,\n config: SnapAccountProviderConfig,\n /* istanbul ignore next */\n trace: TraceCallback = traceFallback,\n ) {\n super(messenger);\n\n this.snapId = snapId;\n this.client = this.#getKeyringClientFromSnapId(snapId);\n\n const maxConcurrency = config.maxConcurrency ?? Infinity;\n this.config = {\n ...config,\n maxConcurrency,\n };\n\n // Create semaphore only if concurrency is limited\n if (isFinite(maxConcurrency)) {\n this.#queue = new Semaphore(maxConcurrency);\n }\n\n this.#trace = trace;\n }\n\n /**\n * Wraps an async operation with concurrency limiting based on maxConcurrency config.\n * If maxConcurrency is Infinity (the default), the operation runs immediately without throttling.\n * Otherwise, it's queued through the semaphore to respect the concurrency limit.\n *\n * @param operation - The async operation to execute.\n * @returns The result of the operation.\n */\n protected async withMaxConcurrency<T>(\n operation: () => Promise<T>,\n ): Promise<T> {\n if (this.#queue) {\n return this.#queue.runExclusive(operation);\n }\n return operation();\n }\n\n protected async trace<ReturnType>(\n request: TraceRequest,\n fn: () => Promise<ReturnType>,\n ): Promise<ReturnType> {\n return this.#trace(request, fn);\n }\n\n protected async getRestrictedSnapAccountCreator(): Promise<RestrictedSnapKeyringCreateAccount> {\n // NOTE: We're not supposed to make the keyring instance escape `withKeyring` but\n // we have to use the `SnapKeyring` instance to be able to create Solana account\n // without triggering UI confirmation.\n // Also, creating account that way won't invalidate the Snap keyring state. The\n // account will get created and persisted properly with the Snap account creation\n // flow \"asynchronously\" (with `notify:accountCreated`).\n const createAccount = await this.#withSnapKeyring<\n SnapKeyring['createAccount']\n >(async ({ keyring }) => keyring.createAccount.bind(keyring));\n\n return (options) =>\n createAccount(this.snapId, options, {\n displayAccountNameSuggestion: false,\n displayConfirmation: false,\n setSelectedAccount: false,\n });\n }\n\n #getKeyringClientFromSnapId(snapId: string): KeyringClient {\n return new KeyringClient({\n send: async (request: JsonRpcRequest) => {\n const response = await this.messenger.call(\n 'SnapController:handleRequest',\n {\n snapId: snapId as SnapId,\n origin: 'metamask',\n handler: HandlerType.OnKeyringRequest,\n request,\n },\n );\n return response as Json;\n },\n });\n }\n\n async resyncAccounts(\n accounts: Bip44Account<InternalAccount>[],\n ): Promise<void> {\n const localSnapAccounts = accounts.filter(\n (account) =>\n account.metadata.snap && account.metadata.snap.id === this.snapId,\n );\n const snapAccounts = new Set(\n (await this.client.listAccounts()).map((account) => account.id),\n );\n\n // NOTE: This should never happen, but we want to report that kind of errors still\n // in case states are de-sync.\n if (localSnapAccounts.length < snapAccounts.size) {\n this.messenger.call(\n 'ErrorReportingService:captureException',\n new Error(\n `Snap \"${this.snapId}\" has de-synced accounts, Snap has more accounts than MetaMask!`,\n ),\n );\n\n // We don't recover from this case yet.\n return;\n }\n\n // We want this part to be fast, so we only check for sizes, but we might need\n // to make a real \"diff\" between the 2 states to not miss any de-sync.\n if (localSnapAccounts.length > snapAccounts.size) {\n // Accounts should never really be de-synced, so we want to log this to see how often this\n // happens, cause that means that something else is buggy elsewhere...\n this.messenger.call(\n 'ErrorReportingService:captureException',\n new Error(\n `Snap \"${this.snapId}\" has de-synced accounts, we'll attempt to re-sync them...`,\n ),\n );\n\n // We always use the MetaMask list as the main reference here.\n await Promise.all(\n localSnapAccounts.map(async (account) => {\n const { id: entropySource, groupIndex } = account.options.entropy;\n\n try {\n if (!snapAccounts.has(account.id)) {\n // We still need to remove the accounts from the Snap keyring since we're\n // about to create the same account again, which will use a new ID, but will\n // keep using the same address, and the Snap keyring does not allow this.\n await this.#withSnapKeyring(\n async ({ keyring }) =>\n await keyring.removeAccount(account.address),\n );\n\n // The Snap has no account in its state for this one, we re-create it.\n await this.createAccounts({\n entropySource,\n groupIndex,\n });\n }\n } catch (error) {\n const sentryError = createSentryError(\n `Unable to re-sync account: ${groupIndex}`,\n error as Error,\n {\n provider: this.getName(),\n groupIndex,\n },\n );\n this.messenger.call(\n 'ErrorReportingService:captureException',\n sentryError,\n );\n }\n }),\n );\n }\n }\n\n async #withSnapKeyring<CallbackResult = void>(\n operation: ({\n keyring,\n metadata,\n }: {\n keyring: SnapKeyring;\n metadata: KeyringMetadata;\n }) => Promise<CallbackResult>,\n ): Promise<CallbackResult> {\n return this.withKeyring<SnapKeyring, CallbackResult>(\n { type: KeyringTypes.snap },\n (args) => {\n return operation(args);\n },\n );\n }\n\n abstract isAccountCompatible(account: Bip44Account<InternalAccount>): boolean;\n\n abstract createAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n\n abstract discoverAccounts(options: {\n entropySource: EntropySourceId;\n groupIndex: number;\n }): Promise<Bip44Account<KeyringAccount>[]>;\n}\n\nexport const isSnapAccountProvider = (\n provider: unknown,\n): provider is SnapAccountProvider => {\n return provider instanceof SnapAccountProvider;\n};\n"]}
@@ -1,6 +1,8 @@
1
1
  import { type Bip44Account } from "@metamask/account-api";
2
+ import type { TraceCallback, TraceRequest } from "@metamask/controller-utils";
2
3
  import type { EntropySourceId, KeyringAccount } from "@metamask/keyring-api";
3
4
  import type { InternalAccount } from "@metamask/keyring-internal-api";
5
+ import { KeyringClient } from "@metamask/keyring-snap-client";
4
6
  import type { Json, SnapId } from "@metamask/snaps-sdk";
5
7
  import { BaseBip44AccountProvider } from "./BaseBip44AccountProvider.cjs";
6
8
  import type { MultichainAccountServiceMessenger } from "../types.cjs";
@@ -20,7 +22,8 @@ export declare abstract class SnapAccountProvider extends BaseBip44AccountProvid
20
22
  #private;
21
23
  readonly snapId: SnapId;
22
24
  protected readonly config: SnapAccountProviderConfig;
23
- constructor(snapId: SnapId, messenger: MultichainAccountServiceMessenger, config: SnapAccountProviderConfig);
25
+ protected readonly client: KeyringClient;
26
+ constructor(snapId: SnapId, messenger: MultichainAccountServiceMessenger, config: SnapAccountProviderConfig, trace?: TraceCallback);
24
27
  /**
25
28
  * Wraps an async operation with concurrency limiting based on maxConcurrency config.
26
29
  * If maxConcurrency is Infinity (the default), the operation runs immediately without throttling.
@@ -30,7 +33,9 @@ export declare abstract class SnapAccountProvider extends BaseBip44AccountProvid
30
33
  * @returns The result of the operation.
31
34
  */
32
35
  protected withMaxConcurrency<T>(operation: () => Promise<T>): Promise<T>;
36
+ protected trace<ReturnType>(request: TraceRequest, fn: () => Promise<ReturnType>): Promise<ReturnType>;
33
37
  protected getRestrictedSnapAccountCreator(): Promise<RestrictedSnapKeyringCreateAccount>;
38
+ resyncAccounts(accounts: Bip44Account<InternalAccount>[]): Promise<void>;
34
39
  abstract isAccountCompatible(account: Bip44Account<InternalAccount>): boolean;
35
40
  abstract createAccounts(options: {
36
41
  entropySource: EntropySourceId;
@@ -1 +1 @@
1
- {"version":3,"file":"SnapAccountProvider.d.cts","sourceRoot":"","sources":["../../src/providers/SnapAccountProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAE,8BAA8B;AAE1D,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,8BAA8B;AAE7E,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AACtE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,4BAA4B;AAGxD,OAAO,EAAE,wBAAwB,EAAE,uCAAmC;AACtE,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAiB;AAElE,MAAM,MAAM,kCAAkC,GAAG,CAC/C,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,KAC1B,OAAO,CAAC,cAAc,CAAC,CAAC;AAE7B,MAAM,MAAM,yBAAyB,GAAG;IACtC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE;QACT,WAAW,EAAE,MAAM,CAAC;QACpB,SAAS,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,cAAc,EAAE;QACd,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;CACH,CAAC;AAEF,8BAAsB,mBAAoB,SAAQ,wBAAwB;;IACxE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,yBAAyB,CAAC;gBAKnD,MAAM,EAAE,MAAM,EACd,SA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AG,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;IAE3C,QAAQ,CAAC,gBAAgB,CAAC,OAAO,EAAE;QACjC,aAAa,EAAE,eAAe,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;CAC5C;AAED,eAAO,MAAM,qBAAqB,aACtB,OAAO,oCAGlB,CAAC"}
@@ -1,6 +1,8 @@
1
1
  import { type Bip44Account } from "@metamask/account-api";
2
+ import type { TraceCallback, TraceRequest } from "@metamask/controller-utils";
2
3
  import type { EntropySourceId, KeyringAccount } from "@metamask/keyring-api";
3
4
  import type { InternalAccount } from "@metamask/keyring-internal-api";
5
+ import { KeyringClient } from "@metamask/keyring-snap-client";
4
6
  import type { Json, SnapId } from "@metamask/snaps-sdk";
5
7
  import { BaseBip44AccountProvider } from "./BaseBip44AccountProvider.mjs";
6
8
  import type { MultichainAccountServiceMessenger } from "../types.mjs";
@@ -20,7 +22,8 @@ export declare abstract class SnapAccountProvider extends BaseBip44AccountProvid
20
22
  #private;
21
23
  readonly snapId: SnapId;
22
24
  protected readonly config: SnapAccountProviderConfig;
23
- constructor(snapId: SnapId, messenger: MultichainAccountServiceMessenger, config: SnapAccountProviderConfig);
25
+ protected readonly client: KeyringClient;
26
+ constructor(snapId: SnapId, messenger: MultichainAccountServiceMessenger, config: SnapAccountProviderConfig, trace?: TraceCallback);
24
27
  /**
25
28
  * Wraps an async operation with concurrency limiting based on maxConcurrency config.
26
29
  * If maxConcurrency is Infinity (the default), the operation runs immediately without throttling.
@@ -30,7 +33,9 @@ export declare abstract class SnapAccountProvider extends BaseBip44AccountProvid
30
33
  * @returns The result of the operation.
31
34
  */
32
35
  protected withMaxConcurrency<T>(operation: () => Promise<T>): Promise<T>;
36
+ protected trace<ReturnType>(request: TraceRequest, fn: () => Promise<ReturnType>): Promise<ReturnType>;
33
37
  protected getRestrictedSnapAccountCreator(): Promise<RestrictedSnapKeyringCreateAccount>;
38
+ resyncAccounts(accounts: Bip44Account<InternalAccount>[]): Promise<void>;
34
39
  abstract isAccountCompatible(account: Bip44Account<InternalAccount>): boolean;
35
40
  abstract createAccounts(options: {
36
41
  entropySource: EntropySourceId;
@@ -1 +1 @@
1
- {"version":3,"file":"SnapAccountProvider.d.mts","sourceRoot":"","sources":["../../src/providers/SnapAccountProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAE,8BAA8B;AAE1D,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,8BAA8B;AAE7E,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AACtE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,4BAA4B;AAGxD,OAAO,EAAE,wBAAwB,EAAE,uCAAmC;AACtE,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAiB;AAElE,MAAM,MAAM,kCAAkC,GAAG,CAC/C,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,KAC1B,OAAO,CAAC,cAAc,CAAC,CAAC;AAE7B,MAAM,MAAM,yBAAyB,GAAG;IACtC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE;QACT,WAAW,EAAE,MAAM,CAAC;QACpB,SAAS,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,cAAc,EAAE;QACd,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;CACH,CAAC;AAEF,8BAAsB,mBAAoB,SAAQ,wBAAwB;;IACxE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,SAAS,CAAC,QAAQ,CAAC,MAAM,EAAE,yBAAyB,CAAC;gBAKnD,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,iCAAiC,EAC5C,MAAM,EAAE,yBAAyB;IAkBnC;;;;;;;OAOG;cACa,kBAAkB,CAAC,CAAC,EAClC,SAAS,EAAE,MAAM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,eAAe,CAAC;QAC/B,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;CAC5C;AAED,eAAO,MAAM,qBAAqB,aACtB,OAAO,oCAGlB,CAAC"}
@@ -1,23 +1,32 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ 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");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
1
6
  var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
7
  if (kind === "m") throw new TypeError("Private method is not writable");
3
8
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
10
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
11
  };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- 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");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _SnapAccountProvider_queue;
12
+ var _SnapAccountProvider_instances, _SnapAccountProvider_queue, _SnapAccountProvider_trace, _SnapAccountProvider_getKeyringClientFromSnapId, _SnapAccountProvider_withSnapKeyring;
13
13
  import { KeyringTypes } from "@metamask/keyring-controller";
14
+ import { KeyringClient } from "@metamask/keyring-snap-client";
15
+ import { HandlerType } from "@metamask/snaps-utils";
14
16
  import { Semaphore } from "async-mutex";
15
17
  import { BaseBip44AccountProvider } from "./BaseBip44AccountProvider.mjs";
18
+ import { traceFallback } from "../analytics/index.mjs";
19
+ import { createSentryError } from "../utils.mjs";
16
20
  export class SnapAccountProvider extends BaseBip44AccountProvider {
17
- constructor(snapId, messenger, config) {
21
+ constructor(snapId, messenger, config,
22
+ /* istanbul ignore next */
23
+ trace = traceFallback) {
18
24
  super(messenger);
25
+ _SnapAccountProvider_instances.add(this);
19
26
  _SnapAccountProvider_queue.set(this, void 0);
27
+ _SnapAccountProvider_trace.set(this, void 0);
20
28
  this.snapId = snapId;
29
+ this.client = __classPrivateFieldGet(this, _SnapAccountProvider_instances, "m", _SnapAccountProvider_getKeyringClientFromSnapId).call(this, snapId);
21
30
  const maxConcurrency = config.maxConcurrency ?? Infinity;
22
31
  this.config = {
23
32
  ...config,
@@ -27,6 +36,7 @@ export class SnapAccountProvider extends BaseBip44AccountProvider {
27
36
  if (isFinite(maxConcurrency)) {
28
37
  __classPrivateFieldSet(this, _SnapAccountProvider_queue, new Semaphore(maxConcurrency), "f");
29
38
  }
39
+ __classPrivateFieldSet(this, _SnapAccountProvider_trace, trace, "f");
30
40
  }
31
41
  /**
32
42
  * Wraps an async operation with concurrency limiting based on maxConcurrency config.
@@ -42,6 +52,9 @@ export class SnapAccountProvider extends BaseBip44AccountProvider {
42
52
  }
43
53
  return operation();
44
54
  }
55
+ async trace(request, fn) {
56
+ return __classPrivateFieldGet(this, _SnapAccountProvider_trace, "f").call(this, request, fn);
57
+ }
45
58
  async getRestrictedSnapAccountCreator() {
46
59
  // NOTE: We're not supposed to make the keyring instance escape `withKeyring` but
47
60
  // we have to use the `SnapKeyring` instance to be able to create Solana account
@@ -49,15 +62,73 @@ export class SnapAccountProvider extends BaseBip44AccountProvider {
49
62
  // Also, creating account that way won't invalidate the Snap keyring state. The
50
63
  // account will get created and persisted properly with the Snap account creation
51
64
  // flow "asynchronously" (with `notify:accountCreated`).
52
- const createAccount = await this.withKeyring({ type: KeyringTypes.snap }, async ({ keyring }) => keyring.createAccount.bind(keyring));
65
+ const createAccount = await __classPrivateFieldGet(this, _SnapAccountProvider_instances, "m", _SnapAccountProvider_withSnapKeyring).call(this, async ({ keyring }) => keyring.createAccount.bind(keyring));
53
66
  return (options) => createAccount(this.snapId, options, {
54
67
  displayAccountNameSuggestion: false,
55
68
  displayConfirmation: false,
56
69
  setSelectedAccount: false,
57
70
  });
58
71
  }
72
+ async resyncAccounts(accounts) {
73
+ const localSnapAccounts = accounts.filter((account) => account.metadata.snap && account.metadata.snap.id === this.snapId);
74
+ const snapAccounts = new Set((await this.client.listAccounts()).map((account) => account.id));
75
+ // NOTE: This should never happen, but we want to report that kind of errors still
76
+ // in case states are de-sync.
77
+ if (localSnapAccounts.length < snapAccounts.size) {
78
+ this.messenger.call('ErrorReportingService:captureException', new Error(`Snap "${this.snapId}" has de-synced accounts, Snap has more accounts than MetaMask!`));
79
+ // We don't recover from this case yet.
80
+ return;
81
+ }
82
+ // We want this part to be fast, so we only check for sizes, but we might need
83
+ // to make a real "diff" between the 2 states to not miss any de-sync.
84
+ if (localSnapAccounts.length > snapAccounts.size) {
85
+ // Accounts should never really be de-synced, so we want to log this to see how often this
86
+ // happens, cause that means that something else is buggy elsewhere...
87
+ this.messenger.call('ErrorReportingService:captureException', new Error(`Snap "${this.snapId}" has de-synced accounts, we'll attempt to re-sync them...`));
88
+ // We always use the MetaMask list as the main reference here.
89
+ await Promise.all(localSnapAccounts.map(async (account) => {
90
+ const { id: entropySource, groupIndex } = account.options.entropy;
91
+ try {
92
+ if (!snapAccounts.has(account.id)) {
93
+ // We still need to remove the accounts from the Snap keyring since we're
94
+ // about to create the same account again, which will use a new ID, but will
95
+ // keep using the same address, and the Snap keyring does not allow this.
96
+ await __classPrivateFieldGet(this, _SnapAccountProvider_instances, "m", _SnapAccountProvider_withSnapKeyring).call(this, async ({ keyring }) => await keyring.removeAccount(account.address));
97
+ // The Snap has no account in its state for this one, we re-create it.
98
+ await this.createAccounts({
99
+ entropySource,
100
+ groupIndex,
101
+ });
102
+ }
103
+ }
104
+ catch (error) {
105
+ const sentryError = createSentryError(`Unable to re-sync account: ${groupIndex}`, error, {
106
+ provider: this.getName(),
107
+ groupIndex,
108
+ });
109
+ this.messenger.call('ErrorReportingService:captureException', sentryError);
110
+ }
111
+ }));
112
+ }
113
+ }
59
114
  }
60
- _SnapAccountProvider_queue = new WeakMap();
115
+ _SnapAccountProvider_queue = new WeakMap(), _SnapAccountProvider_trace = new WeakMap(), _SnapAccountProvider_instances = new WeakSet(), _SnapAccountProvider_getKeyringClientFromSnapId = function _SnapAccountProvider_getKeyringClientFromSnapId(snapId) {
116
+ return new KeyringClient({
117
+ send: async (request) => {
118
+ const response = await this.messenger.call('SnapController:handleRequest', {
119
+ snapId: snapId,
120
+ origin: 'metamask',
121
+ handler: HandlerType.OnKeyringRequest,
122
+ request,
123
+ });
124
+ return response;
125
+ },
126
+ });
127
+ }, _SnapAccountProvider_withSnapKeyring = async function _SnapAccountProvider_withSnapKeyring(operation) {
128
+ return this.withKeyring({ type: KeyringTypes.snap }, (args) => {
129
+ return operation(args);
130
+ });
131
+ };
61
132
  export const isSnapAccountProvider = (provider) => {
62
133
  return provider instanceof SnapAccountProvider;
63
134
  };