@metamask-previews/profile-metrics-controller 4.0.4-preview-6eff555ee → 5.0.0-preview-0a30e47

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 (84) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/dist/{ProfileMetricsController-method-action-types.d.mts → ProfileMetricsController-method-action-types.d.ts} +2 -2
  3. package/dist/ProfileMetricsController-method-action-types.d.ts.map +1 -0
  4. package/dist/{ProfileMetricsController-method-action-types.mjs → ProfileMetricsController-method-action-types.js} +1 -1
  5. package/dist/ProfileMetricsController-method-action-types.js.map +1 -0
  6. package/dist/{ProfileMetricsController.d.cts → ProfileMetricsController.d.ts} +18 -18
  7. package/dist/ProfileMetricsController.d.ts.map +1 -0
  8. package/dist/ProfileMetricsController.js +398 -0
  9. package/dist/ProfileMetricsController.js.map +1 -0
  10. package/dist/{ProfileMetricsService-method-action-types.d.cts → ProfileMetricsService-method-action-types.d.ts} +2 -2
  11. package/dist/ProfileMetricsService-method-action-types.d.ts.map +1 -0
  12. package/dist/{ProfileMetricsService-method-action-types.mjs → ProfileMetricsService-method-action-types.js} +1 -1
  13. package/dist/ProfileMetricsService-method-action-types.js.map +1 -0
  14. package/dist/{ProfileMetricsService.d.mts → ProfileMetricsService.d.ts} +7 -7
  15. package/dist/ProfileMetricsService.d.ts.map +1 -0
  16. package/dist/{ProfileMetricsService.mjs → ProfileMetricsService.js} +93 -103
  17. package/dist/ProfileMetricsService.js.map +1 -0
  18. package/dist/{ProofOfOwnershipService-method-action-types.d.cts → ProofOfOwnershipService-method-action-types.d.ts} +2 -2
  19. package/dist/ProofOfOwnershipService-method-action-types.d.ts.map +1 -0
  20. package/dist/{ProofOfOwnershipService-method-action-types.mjs → ProofOfOwnershipService-method-action-types.js} +1 -1
  21. package/dist/ProofOfOwnershipService-method-action-types.js.map +1 -0
  22. package/dist/{ProofOfOwnershipService.d.cts → ProofOfOwnershipService.d.ts} +7 -7
  23. package/dist/ProofOfOwnershipService.d.ts.map +1 -0
  24. package/dist/{ProofOfOwnershipService.mjs → ProofOfOwnershipService.js} +70 -80
  25. package/dist/ProofOfOwnershipService.js.map +1 -0
  26. package/dist/{index.d.cts → index.d.ts} +9 -9
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +4 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/utils/{canonicalize.d.cts → canonicalize.d.ts} +1 -1
  31. package/dist/utils/canonicalize.d.ts.map +1 -0
  32. package/dist/utils/{canonicalize.mjs → canonicalize.js} +3 -3
  33. package/dist/utils/canonicalize.js.map +1 -0
  34. package/package.json +21 -25
  35. package/dist/ProfileMetricsController-method-action-types.cjs +0 -7
  36. package/dist/ProfileMetricsController-method-action-types.cjs.map +0 -1
  37. package/dist/ProfileMetricsController-method-action-types.d.cts +0 -18
  38. package/dist/ProfileMetricsController-method-action-types.d.cts.map +0 -1
  39. package/dist/ProfileMetricsController-method-action-types.d.mts.map +0 -1
  40. package/dist/ProfileMetricsController-method-action-types.mjs.map +0 -1
  41. package/dist/ProfileMetricsController.cjs +0 -399
  42. package/dist/ProfileMetricsController.cjs.map +0 -1
  43. package/dist/ProfileMetricsController.d.cts.map +0 -1
  44. package/dist/ProfileMetricsController.d.mts +0 -154
  45. package/dist/ProfileMetricsController.d.mts.map +0 -1
  46. package/dist/ProfileMetricsController.mjs +0 -394
  47. package/dist/ProfileMetricsController.mjs.map +0 -1
  48. package/dist/ProfileMetricsService-method-action-types.cjs +0 -7
  49. package/dist/ProfileMetricsService-method-action-types.cjs.map +0 -1
  50. package/dist/ProfileMetricsService-method-action-types.d.cts.map +0 -1
  51. package/dist/ProfileMetricsService-method-action-types.d.mts +0 -45
  52. package/dist/ProfileMetricsService-method-action-types.d.mts.map +0 -1
  53. package/dist/ProfileMetricsService-method-action-types.mjs.map +0 -1
  54. package/dist/ProfileMetricsService.cjs +0 -298
  55. package/dist/ProfileMetricsService.cjs.map +0 -1
  56. package/dist/ProfileMetricsService.d.cts +0 -204
  57. package/dist/ProfileMetricsService.d.cts.map +0 -1
  58. package/dist/ProfileMetricsService.d.mts.map +0 -1
  59. package/dist/ProfileMetricsService.mjs.map +0 -1
  60. package/dist/ProofOfOwnershipService-method-action-types.cjs +0 -7
  61. package/dist/ProofOfOwnershipService-method-action-types.cjs.map +0 -1
  62. package/dist/ProofOfOwnershipService-method-action-types.d.cts.map +0 -1
  63. package/dist/ProofOfOwnershipService-method-action-types.d.mts +0 -29
  64. package/dist/ProofOfOwnershipService-method-action-types.d.mts.map +0 -1
  65. package/dist/ProofOfOwnershipService-method-action-types.mjs.map +0 -1
  66. package/dist/ProofOfOwnershipService.cjs +0 -211
  67. package/dist/ProofOfOwnershipService.cjs.map +0 -1
  68. package/dist/ProofOfOwnershipService.d.cts.map +0 -1
  69. package/dist/ProofOfOwnershipService.d.mts +0 -112
  70. package/dist/ProofOfOwnershipService.d.mts.map +0 -1
  71. package/dist/ProofOfOwnershipService.mjs.map +0 -1
  72. package/dist/index.cjs +0 -14
  73. package/dist/index.cjs.map +0 -1
  74. package/dist/index.d.cts.map +0 -1
  75. package/dist/index.d.mts +0 -9
  76. package/dist/index.d.mts.map +0 -1
  77. package/dist/index.mjs +0 -4
  78. package/dist/index.mjs.map +0 -1
  79. package/dist/utils/canonicalize.cjs +0 -72
  80. package/dist/utils/canonicalize.cjs.map +0 -1
  81. package/dist/utils/canonicalize.d.cts.map +0 -1
  82. package/dist/utils/canonicalize.d.mts +0 -30
  83. package/dist/utils/canonicalize.d.mts.map +0 -1
  84. package/dist/utils/canonicalize.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ### Changed
11
+
12
+ - Bump `uuid` from `^8.3.2` to `^9.0.1` ([#10117](https://github.com/MetaMask/core/pull/10117))
13
+
14
+ ## [5.0.0]
15
+
16
+ ### Changed
17
+
18
+ - **BREAKING:** Drop CommonJS support ([#9536](https://github.com/MetaMask/core/pull/9536))
19
+ - This package is now ESM-only, but can still be used in CommonJS projects via `require(esm)` in modern Node.js versions (22+), or dynamic imports in older Node.js versions.
20
+ - **BREAKING:** Bump minimum Node.js version to 22 ([#9976](https://github.com/MetaMask/core/pull/9976))
21
+ - **BREAKING:** Bump TypeScript target to ES2022 ([#10019](https://github.com/MetaMask/core/pull/10019))
22
+ - This package now ships ES2022 code, requiring a compatible modern environment or bundler configuration to consume.
23
+ - Bump `@metamask/accounts-controller` from `^39.1.1` to `^40.0.0` ([#10160](https://github.com/MetaMask/core/pull/10160))
24
+ - Bump `@metamask/base-controller` from `^9.1.0` to `^10.0.0` ([#10160](https://github.com/MetaMask/core/pull/10160))
25
+ - Bump `@metamask/controller-utils` from `^12.3.0` to `^13.0.0` ([#10160](https://github.com/MetaMask/core/pull/10160))
26
+ - Bump `@metamask/keyring-controller` from `^27.1.1` to `^28.0.0` ([#10160](https://github.com/MetaMask/core/pull/10160))
27
+ - Bump `@metamask/messenger` from `^2.0.0` to `^3.0.0` ([#10160](https://github.com/MetaMask/core/pull/10160))
28
+ - Bump `@metamask/polling-controller` from `^16.0.9` to `^17.0.0` ([#10160](https://github.com/MetaMask/core/pull/10160))
29
+ - Bump `@metamask/profile-sync-controller` from `^30.0.0` to `^31.0.0` ([#10160](https://github.com/MetaMask/core/pull/10160))
30
+ - Bump `@metamask/transaction-controller` from `^69.8.1` to `^70.0.0` ([#10160](https://github.com/MetaMask/core/pull/10160))
31
+
10
32
  ## [4.0.4]
11
33
 
12
34
  ### Changed
@@ -228,7 +250,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
228
250
 
229
251
  - Initial release ([#7194](https://github.com/MetaMask/core/pull/7194), [#7196](https://github.com/MetaMask/core/pull/7196), [#7263](https://github.com/MetaMask/core/pull/7263))
230
252
 
231
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-metrics-controller@4.0.4...HEAD
253
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-metrics-controller@5.0.0...HEAD
254
+ [5.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-metrics-controller@4.0.4...@metamask/profile-metrics-controller@5.0.0
232
255
  [4.0.4]: https://github.com/MetaMask/core/compare/@metamask/profile-metrics-controller@4.0.3...@metamask/profile-metrics-controller@4.0.4
233
256
  [4.0.3]: https://github.com/MetaMask/core/compare/@metamask/profile-metrics-controller@4.0.2...@metamask/profile-metrics-controller@4.0.3
234
257
  [4.0.2]: https://github.com/MetaMask/core/compare/@metamask/profile-metrics-controller@4.0.1...@metamask/profile-metrics-controller@4.0.2
@@ -2,7 +2,7 @@
2
2
  * This file is auto generated.
3
3
  * Do not edit manually.
4
4
  */
5
- import type { ProfileMetricsController } from "./ProfileMetricsController.mjs";
5
+ import type { ProfileMetricsController } from './ProfileMetricsController.js';
6
6
  /**
7
7
  * Skip the initial delay period by setting the end timestamp to the current time.
8
8
  * Metrics will be sent on the next poll.
@@ -15,4 +15,4 @@ export type ProfileMetricsControllerSkipInitialDelayAction = {
15
15
  * Union of all ProfileMetricsController action types.
16
16
  */
17
17
  export type ProfileMetricsControllerMethodActions = ProfileMetricsControllerSkipInitialDelayAction;
18
- //# sourceMappingURL=ProfileMetricsController-method-action-types.d.mts.map
18
+ //# sourceMappingURL=ProfileMetricsController-method-action-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ProfileMetricsController-method-action-types.d.ts","sourceRoot":"","sources":["../src/ProfileMetricsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAE9E;;;GAGG;AACH,MAAM,MAAM,8CAA8C,GAAG;IAC3D,IAAI,EAAE,2CAA2C,CAAC;IAClD,OAAO,EAAE,wBAAwB,CAAC,kBAAkB,CAAC,CAAC;CACvD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qCAAqC,GAC/C,8CAA8C,CAAC"}
@@ -3,4 +3,4 @@
3
3
  * Do not edit manually.
4
4
  */
5
5
  export {};
6
- //# sourceMappingURL=ProfileMetricsController-method-action-types.mjs.map
6
+ //# sourceMappingURL=ProfileMetricsController-method-action-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ProfileMetricsController-method-action-types.js","sourceRoot":"","sources":["../src/ProfileMetricsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { ProfileMetricsController } from './ProfileMetricsController.js';\n\n/**\n * Skip the initial delay period by setting the end timestamp to the current time.\n * Metrics will be sent on the next poll.\n */\nexport type ProfileMetricsControllerSkipInitialDelayAction = {\n type: `ProfileMetricsController:skipInitialDelay`;\n handler: ProfileMetricsController['skipInitialDelay'];\n};\n\n/**\n * Union of all ProfileMetricsController action types.\n */\nexport type ProfileMetricsControllerMethodActions =\n ProfileMetricsControllerSkipInitialDelayAction;\n"]}
@@ -1,12 +1,12 @@
1
- import type { AccountsControllerAccountAddedEvent, AccountsControllerAccountRemovedEvent, AccountsControllerGetStateAction } from "@metamask/accounts-controller";
2
- import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
3
- import type { KeyringControllerLockEvent, KeyringControllerUnlockEvent } from "@metamask/keyring-controller";
4
- import type { Messenger } from "@metamask/messenger";
5
- import { TransactionControllerTransactionSubmittedEvent } from "@metamask/transaction-controller";
6
- import type { ProfileMetricsControllerMethodActions } from "./ProfileMetricsController-method-action-types.cjs";
7
- import type { ProfileMetricsServiceMethodActions } from "./ProfileMetricsService-method-action-types.cjs";
8
- import type { AccountWithScopes } from "./ProfileMetricsService.cjs";
9
- import type { ProofOfOwnershipServiceMethodActions } from "./ProofOfOwnershipService-method-action-types.cjs";
1
+ import type { AccountsControllerAccountAddedEvent, AccountsControllerAccountRemovedEvent, AccountsControllerGetStateAction } from '@metamask/accounts-controller';
2
+ import type { ControllerGetStateAction, ControllerStateChangeEvent } from '@metamask/base-controller';
3
+ import type { KeyringControllerLockEvent, KeyringControllerUnlockEvent } from '@metamask/keyring-controller';
4
+ import type { Messenger } from '@metamask/messenger';
5
+ import { TransactionControllerTransactionSubmittedEvent } from '@metamask/transaction-controller';
6
+ import type { ProfileMetricsControllerMethodActions } from './ProfileMetricsController-method-action-types.js';
7
+ import type { ProfileMetricsServiceMethodActions } from './ProfileMetricsService-method-action-types.js';
8
+ import type { AccountWithScopes } from './ProfileMetricsService.js';
9
+ import type { ProofOfOwnershipServiceMethodActions } from './ProofOfOwnershipService-method-action-types.js';
10
10
  /**
11
11
  * The name of the {@link ProfileMetricsController}, used to namespace the
12
12
  * controller's actions and events and to namespace the controller's state data
@@ -86,18 +86,18 @@ type AllowedEvents = KeyringControllerUnlockEvent | KeyringControllerLockEvent |
86
86
  */
87
87
  export type ProfileMetricsControllerMessenger = Messenger<typeof controllerName, ProfileMetricsControllerActions | AllowedActions, ProfileMetricsControllerEvents | AllowedEvents>;
88
88
  declare const ProfileMetricsController_base: (abstract new (...args: any[]) => {
89
- readonly "__#6@#intervalIds": Record<string, NodeJS.Timeout>;
90
- "__#6@#intervalLength": number | undefined;
91
- setIntervalLength(intervalLength: number): void;
92
- getIntervalLength(): number | undefined;
93
- _startPolling(input: import("@metamask/utils").Json): void;
94
- _stopPollingByPollingTokenSetId(key: string): void;
95
- readonly "__#3@#pollingTokenSets": Map<string, Set<string>>;
96
- readonly "__#3@#callbacks": Map<string, Set<(input: import("@metamask/utils").Json) => void>>;
89
+ readonly _callbacks: Map<string, Set<(input: import("@metamask/utils").Json) => void>>;
97
90
  _executePoll(input: import("@metamask/utils").Json): Promise<void>;
98
91
  startPolling(input: import("@metamask/utils").Json): string;
99
92
  stopAllPolling(): void;
100
93
  stopPollingByPollingToken(pollingToken: string): void;
94
+ readonly _intervalIds: Record<import("@metamask/polling-controller").PollingTokenSetId, NodeJS.Timeout>;
95
+ _intervalLength: number | undefined;
96
+ setIntervalLength(intervalLength: number): void;
97
+ getIntervalLength(): number | undefined;
98
+ _startPolling(input: import("@metamask/utils").Json): void;
99
+ _stopPollingByPollingTokenSetId(key: import("@metamask/polling-controller").PollingTokenSetId): void;
100
+ readonly _pollingTokenSets: Map<import("@metamask/polling-controller").PollingTokenSetId, Set<string>>;
101
101
  onPollingComplete(input: import("@metamask/utils").Json, callback: (input: import("@metamask/utils").Json) => void): void;
102
102
  }) & typeof import("@metamask/base-controller").BaseController;
103
103
  /**
@@ -151,4 +151,4 @@ export declare class ProfileMetricsController extends ProfileMetricsController_b
151
151
  _executePoll(): Promise<void>;
152
152
  }
153
153
  export {};
154
- //# sourceMappingURL=ProfileMetricsController.d.cts.map
154
+ //# sourceMappingURL=ProfileMetricsController.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ProfileMetricsController.d.ts","sourceRoot":"","sources":["../src/ProfileMetricsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mCAAmC,EACnC,qCAAqC,EACrC,gCAAgC,EACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EACV,0BAA0B,EAC1B,4BAA4B,EAC7B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAErD,OAAO,EAAE,8CAA8C,EAAE,MAAM,kCAAkC,CAAC;AAIlG,OAAO,KAAK,EAAE,qCAAqC,EAAE,MAAM,mDAAmD,CAAC;AAC/G,OAAO,KAAK,EAAE,kCAAkC,EAAE,MAAM,gDAAgD,CAAC;AACzG,OAAO,KAAK,EAEV,iBAAiB,EAClB,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,kDAAkD,CAAC;AAM7G;;;;GAIG;AACH,eAAO,MAAM,cAAc,6BAA6B,CAAC;AAEzD;;GAEG;AAC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ACL,iBAAiB,EACjB,gBAAgB,EAChB,QAAoB,EACpB,oBAAqD,GACtD,EAAE;QACD,SAAS,EAAE,iCAAiC,CAAC;QAC7C,KAAK,CAAC,EAAE,OAAO,CAAC,6BAA6B,CAAC,CAAC;QAC/C,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,iBAAiB,EAAE,MAAM,OAAO,CAAC;QACjC,gBAAgB,EAAE,MAAM,MAAM,CAAC;QAC/B,oBAAoB,CAAC,EAAE,MAAM,CAAC;KAC/B,EAiDA;IAED;;;OAGG;IACH,gBAAgB,IAAI,IAAI,CAIvB;IAED;;;;;;;;;OASG;IACG,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC,CA0ClC;CA0OF"}
@@ -0,0 +1,398 @@
1
+ import { StaticIntervalPollingController } from '@metamask/polling-controller';
2
+ import { Duration, inMilliseconds, parseCaipChainId } from '@metamask/utils';
3
+ import { Mutex } from 'async-mutex';
4
+ import { canonicalizeAddress, ProofUnsupportedNamespaceError, } from './utils/canonicalize.js';
5
+ /**
6
+ * The name of the {@link ProfileMetricsController}, used to namespace the
7
+ * controller's actions and events and to namespace the controller's state data
8
+ * when composed with other controllers.
9
+ */
10
+ export const controllerName = 'ProfileMetricsController';
11
+ /**
12
+ * The default delay duration before data is sent for the first time.
13
+ */
14
+ export const DEFAULT_INITIAL_DELAY_DURATION = inMilliseconds(1, Duration.Minute);
15
+ /**
16
+ * The metadata for each property in {@link ProfileMetricsControllerState}.
17
+ */
18
+ const profileMetricsControllerMetadata = {
19
+ initialEnqueueCompleted: {
20
+ persist: true,
21
+ includeInDebugSnapshot: true,
22
+ includeInStateLogs: true,
23
+ usedInUi: false,
24
+ },
25
+ syncQueue: {
26
+ persist: true,
27
+ includeInDebugSnapshot: false,
28
+ includeInStateLogs: true,
29
+ usedInUi: false,
30
+ },
31
+ initialDelayEndTimestamp: {
32
+ persist: true,
33
+ includeInDebugSnapshot: true,
34
+ includeInStateLogs: true,
35
+ usedInUi: false,
36
+ },
37
+ proofBackfillEnqueued: {
38
+ persist: true,
39
+ includeInDebugSnapshot: true,
40
+ includeInStateLogs: true,
41
+ usedInUi: false,
42
+ },
43
+ };
44
+ /**
45
+ * Constructs the default {@link ProfileMetricsController} state. This allows
46
+ * consumers to provide a partial state object when initializing the controller
47
+ * and also helps in constructing complete state objects for this controller in
48
+ * tests.
49
+ *
50
+ * @returns The default {@link ProfileMetricsController} state.
51
+ */
52
+ export function getDefaultProfileMetricsControllerState() {
53
+ return {
54
+ initialEnqueueCompleted: false,
55
+ syncQueue: {},
56
+ proofBackfillEnqueued: false,
57
+ };
58
+ }
59
+ const MESSENGER_EXPOSED_METHODS = ['skipInitialDelay'];
60
+ /**
61
+ * Manages user profile metrics.
62
+ *
63
+ * For users who opt-in to metrics, this controller ensures we have metrics about their user
64
+ * profile (metrics ID and accounts).
65
+ */
66
+ export class ProfileMetricsController extends StaticIntervalPollingController() {
67
+ #mutex = new Mutex();
68
+ #assertUserOptedIn;
69
+ #getMetaMetricsId;
70
+ #initialDelayDuration;
71
+ /**
72
+ * Constructs a new {@link ProfileMetricsController}.
73
+ *
74
+ * @param args - The constructor arguments.
75
+ * @param args.messenger - The messenger suited for this controller.
76
+ * @param args.state - The desired state with which to initialize this
77
+ * controller. Missing properties will be filled in with defaults.
78
+ * @param args.assertUserOptedIn - A function that asserts whether the user has
79
+ * opted in to user profile features. If the user has not opted in, sync
80
+ * operations will be no-ops.
81
+ * @param args.getMetaMetricsId - A function that returns the MetaMetrics ID
82
+ * of the user.
83
+ * @param args.interval - The interval, in milliseconds, at which the controller will
84
+ * attempt to send user profile data. Defaults to 10 seconds.
85
+ * @param args.initialDelayDuration - The delay duration before data is sent
86
+ * for the first time, in milliseconds. Defaults to 10 minutes.
87
+ */
88
+ constructor({ messenger, state, assertUserOptedIn, getMetaMetricsId, interval = 10 * 1000, initialDelayDuration = DEFAULT_INITIAL_DELAY_DURATION, }) {
89
+ super({
90
+ messenger,
91
+ metadata: profileMetricsControllerMetadata,
92
+ name: controllerName,
93
+ state: {
94
+ ...getDefaultProfileMetricsControllerState(),
95
+ ...state,
96
+ },
97
+ });
98
+ this.#assertUserOptedIn = assertUserOptedIn;
99
+ this.#getMetaMetricsId = getMetaMetricsId;
100
+ this.#initialDelayDuration = initialDelayDuration;
101
+ this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
102
+ this.messenger.subscribe('KeyringController:unlock', () => {
103
+ if (this.#assertUserOptedIn()) {
104
+ // If the user has already opted in at the start of the session,
105
+ // it must have opted in during onboarding, or during a previous session.
106
+ this.skipInitialDelay();
107
+ }
108
+ this.#enqueueAccountsIfNeeded().catch(this.messenger.captureException ?? console.error);
109
+ this.startPolling(null);
110
+ });
111
+ this.messenger.subscribe('KeyringController:lock', () => this.stopAllPolling());
112
+ this.messenger.subscribe('TransactionController:transactionSubmitted', () => this.skipInitialDelay());
113
+ this.messenger.subscribe('AccountsController:accountAdded', (account) => {
114
+ this.#addAccountToQueue(account).catch(console.error);
115
+ });
116
+ this.messenger.subscribe('AccountsController:accountRemoved', (account) => {
117
+ this.#removeAccountFromQueue(account).catch(console.error);
118
+ });
119
+ this.setIntervalLength(interval);
120
+ }
121
+ /**
122
+ * Skip the initial delay period by setting the end timestamp to the current time.
123
+ * Metrics will be sent on the next poll.
124
+ */
125
+ skipInitialDelay() {
126
+ this.update((state) => {
127
+ state.initialDelayEndTimestamp = Date.now();
128
+ });
129
+ }
130
+ /**
131
+ * Execute a single poll to sync user profile data.
132
+ *
133
+ * The queued accounts are sent to the ProfileMetricsService, each with
134
+ * a proof of ownership when one can be produced (see {@link #attachProofs}),
135
+ * and the sync queue is cleared. This operation is mutexed to prevent
136
+ * concurrent executions.
137
+ *
138
+ * @returns A promise that resolves when the poll is complete.
139
+ */
140
+ async _executePoll() {
141
+ await this.#mutex.runExclusive(async () => {
142
+ if (!this.#assertUserOptedIn()) {
143
+ return;
144
+ }
145
+ this.#setInitialDelayEndTimestampIfNull();
146
+ if (!this.#isInitialDelayComplete()) {
147
+ return;
148
+ }
149
+ const fullAccountsByAddress = this.#getFullAccountsByAddress();
150
+ for (const [entropySourceId, accounts] of Object.entries(this.state.syncQueue)) {
151
+ const normalizedEntropySourceId = entropySourceId === 'null' ? null : entropySourceId;
152
+ // Skip proof-of-ownership for accounts without an entropy source
153
+ const accountsWithProofs = normalizedEntropySourceId === null
154
+ ? accounts
155
+ : await this.#attachProofs(accounts, fullAccountsByAddress, normalizedEntropySourceId);
156
+ try {
157
+ await this.messenger.call('ProfileMetricsService:submitMetrics', {
158
+ metametricsId: this.#getMetaMetricsId(),
159
+ entropySourceId: normalizedEntropySourceId,
160
+ accounts: accountsWithProofs,
161
+ });
162
+ this.update((state) => {
163
+ delete state.syncQueue[entropySourceId];
164
+ });
165
+ }
166
+ catch (error) {
167
+ // We want to log the error but continue processing other batches.
168
+ console.error(`Failed to submit profile metrics for entropy source ID ${entropySourceId}:`, error);
169
+ }
170
+ }
171
+ });
172
+ }
173
+ /**
174
+ * Attach a proof of ownership to each account in a single entropy-source
175
+ * batch when possible, canonicalizing the address along the way.
176
+ *
177
+ * Per-account failures (unknown namespace, snap missing the
178
+ * `signProofOfOwnership` method, snap rejection) and whole-batch nonce
179
+ * failures are caught and downgraded to "submit without a proof" so the
180
+ * batch still goes through and the proof is retried on the next poll.
181
+ *
182
+ * @param accounts - The queued accounts for a single batch.
183
+ * @param fullAccountsByAddress - Live `InternalAccount` lookup keyed by address.
184
+ * @param entropySourceId - The entropy source ID for this batch. Callers
185
+ * are expected to short-circuit before invoking this method when the
186
+ * batch has no entropy source; see `_executePoll` for why.
187
+ * @returns The accounts with `proof` populated where signing succeeded.
188
+ */
189
+ async #attachProofs(accounts, fullAccountsByAddress, entropySourceId) {
190
+ const candidates = new Map();
191
+ const identifiers = new Set();
192
+ for (const queued of accounts) {
193
+ const fullAccount = fullAccountsByAddress.get(queued.address);
194
+ if (!fullAccount) {
195
+ continue;
196
+ }
197
+ try {
198
+ const [scope] = fullAccount.scopes;
199
+ if (!scope) {
200
+ throw new Error(`Scope not found for account ${fullAccount.id}`);
201
+ }
202
+ const { namespace } = parseCaipChainId(scope);
203
+ const canonicalAddress = canonicalizeAddress(fullAccount.address, namespace);
204
+ candidates.set(queued.address, {
205
+ account: fullAccount,
206
+ canonicalAddress,
207
+ });
208
+ identifiers.add(canonicalAddress);
209
+ }
210
+ catch (error) {
211
+ // Unsupported namespaces are an expected pass-through; anything
212
+ // else is logged so a new namespace doesn't go unnoticed.
213
+ if (!(error instanceof ProofUnsupportedNamespaceError)) {
214
+ console.error(`Skipping proof for account ${fullAccount.id}:`, error);
215
+ }
216
+ }
217
+ }
218
+ if (candidates.size === 0) {
219
+ return accounts;
220
+ }
221
+ let nonces = {};
222
+ try {
223
+ nonces = await this.messenger.call('ProfileMetricsService:fetchNonces', {
224
+ identifiers: [...identifiers],
225
+ entropySourceId,
226
+ });
227
+ }
228
+ catch (error) {
229
+ console.error(`Failed to fetch proof-of-ownership nonces for entropy source ID ${entropySourceId}:`, error);
230
+ }
231
+ return await Promise.all(accounts.map(async (queued) => {
232
+ const candidate = candidates.get(queued.address);
233
+ if (!candidate) {
234
+ return queued;
235
+ }
236
+ const nonce = nonces[candidate.canonicalAddress];
237
+ if (!nonce) {
238
+ return { ...queued, address: candidate.canonicalAddress };
239
+ }
240
+ let proof;
241
+ try {
242
+ proof = await this.messenger.call('ProofOfOwnershipService:sign', {
243
+ account: candidate.account,
244
+ nonce,
245
+ });
246
+ }
247
+ catch (error) {
248
+ console.error(`Failed to sign proof of ownership for account ${candidate.account.id}:`, error);
249
+ return { ...queued, address: candidate.canonicalAddress };
250
+ }
251
+ return {
252
+ address: candidate.canonicalAddress,
253
+ scopes: queued.scopes,
254
+ proof,
255
+ };
256
+ }));
257
+ }
258
+ /**
259
+ * Snapshot the live `InternalAccount` map keyed by address for the
260
+ * current poll.
261
+ *
262
+ * @returns A map of address → `InternalAccount`.
263
+ */
264
+ #getFullAccountsByAddress() {
265
+ const byAddress = new Map();
266
+ const accountsState = this.messenger.call('AccountsController:getState');
267
+ for (const account of Object.values(accountsState.internalAccounts.accounts)) {
268
+ byAddress.set(account.address, account);
269
+ }
270
+ return byAddress;
271
+ }
272
+ /**
273
+ * Enqueue all currently-known accounts onto the sync queue if needed.
274
+ * Single entry point covering both the fresh-install first sync and
275
+ * the one-time proof-of-ownership backfill for users upgrading.
276
+ *
277
+ * Bails for opted-out users (the poll wouldn't drain the queue
278
+ * anyway), and bails once both bootstrap steps have already run.
279
+ * Otherwise enqueues all known accounts and flips both flags so this
280
+ * becomes a permanent no-op for the lifetime of the install.
281
+ */
282
+ async #enqueueAccountsIfNeeded() {
283
+ await this.#mutex.runExclusive(async () => {
284
+ if (!this.#assertUserOptedIn()) {
285
+ return;
286
+ }
287
+ if (this.state.initialEnqueueCompleted &&
288
+ this.state.proofBackfillEnqueued) {
289
+ return;
290
+ }
291
+ const groupedAccounts = groupAccountsByEntropySourceId(Object.values(this.messenger.call('AccountsController:getState').internalAccounts
292
+ .accounts));
293
+ this.update((state) => {
294
+ // Replace the queue rather than append. `AccountsController` is
295
+ // the source of truth and the queue is otherwise kept in sync
296
+ // with it via the `accountAdded` / `accountRemoved` subscriptions,
297
+ // so assigning here avoids duplicating entries that survived from
298
+ // a prior session or were pushed earlier in this same unlock
299
+ // cycle. Duplicates would matter because nonces are single-use:
300
+ // letting one through causes `#attachProofs` to sign and submit
301
+ // twice with the same nonce.
302
+ state.syncQueue = groupedAccounts;
303
+ state.initialEnqueueCompleted = true;
304
+ state.proofBackfillEnqueued = true;
305
+ });
306
+ });
307
+ }
308
+ /**
309
+ * Set the initial delay end timestamp if it is not already set.
310
+ */
311
+ #setInitialDelayEndTimestampIfNull() {
312
+ this.update((state) => {
313
+ state.initialDelayEndTimestamp ??=
314
+ Date.now() + this.#initialDelayDuration;
315
+ });
316
+ }
317
+ /**
318
+ * Check if the initial delay end timestamp is in the past.
319
+ *
320
+ * @returns True if the initial delay period has completed, false otherwise.
321
+ */
322
+ #isInitialDelayComplete() {
323
+ return (this.state.initialDelayEndTimestamp !== undefined &&
324
+ Date.now() >= this.state.initialDelayEndTimestamp);
325
+ }
326
+ /**
327
+ * Queue the given account to be synced at the next poll.
328
+ *
329
+ * @param account - The account to sync.
330
+ */
331
+ async #addAccountToQueue(account) {
332
+ await this.#mutex.runExclusive(async () => {
333
+ this.update((state) => {
334
+ const entropySourceId = getAccountEntropySourceId(account) ?? 'null';
335
+ if (!state.syncQueue[entropySourceId]) {
336
+ state.syncQueue[entropySourceId] = [];
337
+ }
338
+ state.syncQueue[entropySourceId].push({
339
+ address: account.address,
340
+ scopes: account.scopes,
341
+ });
342
+ });
343
+ });
344
+ }
345
+ /**
346
+ * Remove the given account from the sync queue.
347
+ *
348
+ * @param account - The account address to remove.
349
+ */
350
+ async #removeAccountFromQueue(account) {
351
+ await this.#mutex.runExclusive(async () => {
352
+ this.update((state) => {
353
+ for (const [entropySourceId, groupedAddresses] of Object.entries(state.syncQueue)) {
354
+ const index = groupedAddresses.findIndex(({ address }) => address === account);
355
+ if (index === -1) {
356
+ continue;
357
+ }
358
+ groupedAddresses.splice(index, 1);
359
+ if (groupedAddresses.length === 0) {
360
+ delete state.syncQueue[entropySourceId];
361
+ }
362
+ break;
363
+ }
364
+ });
365
+ });
366
+ }
367
+ }
368
+ /**
369
+ * Retrieves the entropy source ID from the given account, if it exists.
370
+ *
371
+ * @param account - The account from which to retrieve the entropy source ID.
372
+ * @returns The entropy source ID, or null if it does not exist.
373
+ */
374
+ function getAccountEntropySourceId(account) {
375
+ if (account.options.entropy?.type === 'mnemonic') {
376
+ return account.options.entropy.id;
377
+ }
378
+ return null;
379
+ }
380
+ /**
381
+ * Groups accounts by their entropy source ID.
382
+ *
383
+ * @param accounts - The accounts to group.
384
+ * @returns An object where each key is an entropy source ID and each value is
385
+ * an array of account addresses associated with that entropy source ID.
386
+ */
387
+ function groupAccountsByEntropySourceId(accounts) {
388
+ return accounts.reduce((result, account) => {
389
+ const entropySourceId = getAccountEntropySourceId(account);
390
+ const key = entropySourceId ?? 'null';
391
+ if (!result[key]) {
392
+ result[key] = [];
393
+ }
394
+ result[key].push({ address: account.address, scopes: account.scopes });
395
+ return result;
396
+ }, {});
397
+ }
398
+ //# sourceMappingURL=ProfileMetricsController.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ProfileMetricsController.js","sourceRoot":"","sources":["../src/ProfileMetricsController.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAE/E,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAC7E,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AASpC,OAAO,EACL,mBAAmB,EACnB,8BAA8B,GAC/B,MAAM,yBAAyB,CAAC;AAEjC;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAEzD;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,cAAc,CAC1D,CAAC,EACD,QAAQ,CAAC,MAAM,CAChB,CAAC;AAgCF;;GAEG;AACH,MAAM,gCAAgC,GAAG;IACvC,uBAAuB,EAAE;QACvB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,kBAAkB,EAAE,IAAI;QACxB,QAAQ,EAAE,KAAK;KAChB;IACD,SAAS,EAAE;QACT,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,kBAAkB,EAAE,IAAI;QACxB,QAAQ,EAAE,KAAK;KAChB;IACD,wBAAwB,EAAE;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,kBAAkB,EAAE,IAAI;QACxB,QAAQ,EAAE,KAAK;KAChB;IACD,qBAAqB,EAAE;QACrB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,kBAAkB,EAAE,IAAI;QACxB,QAAQ,EAAE,KAAK;KAChB;CACqD,C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C;AACJ,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountRemovedEvent,\n AccountsControllerGetStateAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type {\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { TransactionControllerTransactionSubmittedEvent } from '@metamask/transaction-controller';\nimport { Duration, inMilliseconds, parseCaipChainId } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport type { ProfileMetricsControllerMethodActions } from './ProfileMetricsController-method-action-types.js';\nimport type { ProfileMetricsServiceMethodActions } from './ProfileMetricsService-method-action-types.js';\nimport type {\n AccountOwnershipProof,\n AccountWithScopes,\n} from './ProfileMetricsService.js';\nimport type { ProofOfOwnershipServiceMethodActions } from './ProofOfOwnershipService-method-action-types.js';\nimport {\n canonicalizeAddress,\n ProofUnsupportedNamespaceError,\n} from './utils/canonicalize.js';\n\n/**\n * The name of the {@link ProfileMetricsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'ProfileMetricsController';\n\n/**\n * The default delay duration before data is sent for the first time.\n */\nexport const DEFAULT_INITIAL_DELAY_DURATION = inMilliseconds(\n 1,\n Duration.Minute,\n);\n\n/**\n * Describes the shape of the state object for {@link ProfileMetricsController}.\n */\nexport type ProfileMetricsControllerState = {\n /**\n * Whether existing accounts have been added\n * to the queue.\n */\n initialEnqueueCompleted: boolean;\n /**\n * The queue of accounts to be synced.\n * Each key is an entropy source ID, and each value is an array of account\n * addresses associated with that entropy source. Accounts with no entropy\n * source ID are grouped under the key \"null\".\n */\n syncQueue: Record<string, AccountWithScopes[]>;\n /**\n * The timestamp when the first data sending can be attempted.\n */\n initialDelayEndTimestamp?: number;\n /**\n * Whether previously-synced accounts have been re-enqueued so their\n * proofs of ownership are submitted alongside everything else. Set on\n * the first unlock after upgrading to a version that signs proofs of\n * ownership; fresh installs flip this on their initial sync since the\n * first poll already attaches proofs.\n */\n proofBackfillEnqueued: boolean;\n};\n\n/**\n * The metadata for each property in {@link ProfileMetricsControllerState}.\n */\nconst profileMetricsControllerMetadata = {\n initialEnqueueCompleted: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: false,\n },\n syncQueue: {\n persist: true,\n includeInDebugSnapshot: false,\n includeInStateLogs: true,\n usedInUi: false,\n },\n initialDelayEndTimestamp: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: false,\n },\n proofBackfillEnqueued: {\n persist: true,\n includeInDebugSnapshot: true,\n includeInStateLogs: true,\n usedInUi: false,\n },\n} satisfies StateMetadata<ProfileMetricsControllerState>;\n\n/**\n * Constructs the default {@link ProfileMetricsController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link ProfileMetricsController} state.\n */\nexport function getDefaultProfileMetricsControllerState(): ProfileMetricsControllerState {\n return {\n initialEnqueueCompleted: false,\n syncQueue: {},\n proofBackfillEnqueued: false,\n };\n}\n\nconst MESSENGER_EXPOSED_METHODS = ['skipInitialDelay'] as const;\n\n/**\n * Retrieves the state of the {@link ProfileMetricsController}.\n */\nexport type ProfileMetricsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n ProfileMetricsControllerState\n>;\n\n/**\n * Actions that {@link ProfileMetricsControllerMessenger} exposes to other consumers.\n */\nexport type ProfileMetricsControllerActions =\n | ProfileMetricsControllerGetStateAction\n | ProfileMetricsControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link ProfileMetricsControllerMessenger} calls.\n */\ntype AllowedActions =\n | ProfileMetricsServiceMethodActions\n | ProofOfOwnershipServiceMethodActions\n | AccountsControllerGetStateAction;\n\n/**\n * Published when the state of {@link ProfileMetricsController} changes.\n */\nexport type ProfileMetricsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n ProfileMetricsControllerState\n >;\n\n/**\n * Events that {@link ProfileMetricsControllerMessenger} exposes to other consumers.\n */\nexport type ProfileMetricsControllerEvents =\n ProfileMetricsControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link ProfileMetricsControllerMessenger} subscribes\n * to.\n */\ntype AllowedEvents =\n | KeyringControllerUnlockEvent\n | KeyringControllerLockEvent\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRemovedEvent\n | TransactionControllerTransactionSubmittedEvent;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link ProfileMetricsController}.\n */\nexport type ProfileMetricsControllerMessenger = Messenger<\n typeof controllerName,\n ProfileMetricsControllerActions | AllowedActions,\n ProfileMetricsControllerEvents | AllowedEvents\n>;\n\n/**\n * Manages user profile metrics.\n *\n * For users who opt-in to metrics, this controller ensures we have metrics about their user\n * profile (metrics ID and accounts).\n */\nexport class ProfileMetricsController extends StaticIntervalPollingController()<\n typeof controllerName,\n ProfileMetricsControllerState,\n ProfileMetricsControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #assertUserOptedIn: () => boolean;\n\n readonly #getMetaMetricsId: () => string;\n\n readonly #initialDelayDuration: number;\n\n /**\n * Constructs a new {@link ProfileMetricsController}.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this controller.\n * @param args.state - The desired state with which to initialize this\n * controller. Missing properties will be filled in with defaults.\n * @param args.assertUserOptedIn - A function that asserts whether the user has\n * opted in to user profile features. If the user has not opted in, sync\n * operations will be no-ops.\n * @param args.getMetaMetricsId - A function that returns the MetaMetrics ID\n * of the user.\n * @param args.interval - The interval, in milliseconds, at which the controller will\n * attempt to send user profile data. Defaults to 10 seconds.\n * @param args.initialDelayDuration - The delay duration before data is sent\n * for the first time, in milliseconds. Defaults to 10 minutes.\n */\n constructor({\n messenger,\n state,\n assertUserOptedIn,\n getMetaMetricsId,\n interval = 10 * 1000,\n initialDelayDuration = DEFAULT_INITIAL_DELAY_DURATION,\n }: {\n messenger: ProfileMetricsControllerMessenger;\n state?: Partial<ProfileMetricsControllerState>;\n interval?: number;\n assertUserOptedIn: () => boolean;\n getMetaMetricsId: () => string;\n initialDelayDuration?: number;\n }) {\n super({\n messenger,\n metadata: profileMetricsControllerMetadata,\n name: controllerName,\n state: {\n ...getDefaultProfileMetricsControllerState(),\n ...state,\n },\n });\n\n this.#assertUserOptedIn = assertUserOptedIn;\n this.#getMetaMetricsId = getMetaMetricsId;\n this.#initialDelayDuration = initialDelayDuration;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n if (this.#assertUserOptedIn()) {\n // If the user has already opted in at the start of the session,\n // it must have opted in during onboarding, or during a previous session.\n this.skipInitialDelay();\n }\n this.#enqueueAccountsIfNeeded().catch(\n this.messenger.captureException ?? console.error,\n );\n this.startPolling(null);\n });\n\n this.messenger.subscribe('KeyringController:lock', () =>\n this.stopAllPolling(),\n );\n\n this.messenger.subscribe('TransactionController:transactionSubmitted', () =>\n this.skipInitialDelay(),\n );\n\n this.messenger.subscribe('AccountsController:accountAdded', (account) => {\n this.#addAccountToQueue(account).catch(console.error);\n });\n\n this.messenger.subscribe('AccountsController:accountRemoved', (account) => {\n this.#removeAccountFromQueue(account).catch(console.error);\n });\n\n this.setIntervalLength(interval);\n }\n\n /**\n * Skip the initial delay period by setting the end timestamp to the current time.\n * Metrics will be sent on the next poll.\n */\n skipInitialDelay(): void {\n this.update((state) => {\n state.initialDelayEndTimestamp = Date.now();\n });\n }\n\n /**\n * Execute a single poll to sync user profile data.\n *\n * The queued accounts are sent to the ProfileMetricsService, each with\n * a proof of ownership when one can be produced (see {@link #attachProofs}),\n * and the sync queue is cleared. This operation is mutexed to prevent\n * concurrent executions.\n *\n * @returns A promise that resolves when the poll is complete.\n */\n async _executePoll(): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n if (!this.#assertUserOptedIn()) {\n return;\n }\n this.#setInitialDelayEndTimestampIfNull();\n if (!this.#isInitialDelayComplete()) {\n return;\n }\n const fullAccountsByAddress = this.#getFullAccountsByAddress();\n for (const [entropySourceId, accounts] of Object.entries(\n this.state.syncQueue,\n )) {\n const normalizedEntropySourceId =\n entropySourceId === 'null' ? null : entropySourceId;\n // Skip proof-of-ownership for accounts without an entropy source\n const accountsWithProofs =\n normalizedEntropySourceId === null\n ? accounts\n : await this.#attachProofs(\n accounts,\n fullAccountsByAddress,\n normalizedEntropySourceId,\n );\n try {\n await this.messenger.call('ProfileMetricsService:submitMetrics', {\n metametricsId: this.#getMetaMetricsId(),\n entropySourceId: normalizedEntropySourceId,\n accounts: accountsWithProofs,\n });\n this.update((state) => {\n delete state.syncQueue[entropySourceId];\n });\n } catch (error) {\n // We want to log the error but continue processing other batches.\n console.error(\n `Failed to submit profile metrics for entropy source ID ${entropySourceId}:`,\n error,\n );\n }\n }\n });\n }\n\n /**\n * Attach a proof of ownership to each account in a single entropy-source\n * batch when possible, canonicalizing the address along the way.\n *\n * Per-account failures (unknown namespace, snap missing the\n * `signProofOfOwnership` method, snap rejection) and whole-batch nonce\n * failures are caught and downgraded to \"submit without a proof\" so the\n * batch still goes through and the proof is retried on the next poll.\n *\n * @param accounts - The queued accounts for a single batch.\n * @param fullAccountsByAddress - Live `InternalAccount` lookup keyed by address.\n * @param entropySourceId - The entropy source ID for this batch. Callers\n * are expected to short-circuit before invoking this method when the\n * batch has no entropy source; see `_executePoll` for why.\n * @returns The accounts with `proof` populated where signing succeeded.\n */\n async #attachProofs(\n accounts: AccountWithScopes[],\n fullAccountsByAddress: Map<string, InternalAccount>,\n entropySourceId: string,\n ): Promise<AccountWithScopes[]> {\n const candidates = new Map<\n string,\n { account: InternalAccount; canonicalAddress: string }\n >();\n const identifiers = new Set<string>();\n for (const queued of accounts) {\n const fullAccount = fullAccountsByAddress.get(queued.address);\n if (!fullAccount) {\n continue;\n }\n try {\n const [scope] = fullAccount.scopes;\n if (!scope) {\n throw new Error(`Scope not found for account ${fullAccount.id}`);\n }\n const { namespace } = parseCaipChainId(scope);\n const canonicalAddress = canonicalizeAddress(\n fullAccount.address,\n namespace,\n );\n candidates.set(queued.address, {\n account: fullAccount,\n canonicalAddress,\n });\n identifiers.add(canonicalAddress);\n } catch (error) {\n // Unsupported namespaces are an expected pass-through; anything\n // else is logged so a new namespace doesn't go unnoticed.\n if (!(error instanceof ProofUnsupportedNamespaceError)) {\n console.error(`Skipping proof for account ${fullAccount.id}:`, error);\n }\n }\n }\n\n if (candidates.size === 0) {\n return accounts;\n }\n\n let nonces: Record<string, string> = {};\n try {\n nonces = await this.messenger.call('ProfileMetricsService:fetchNonces', {\n identifiers: [...identifiers],\n entropySourceId,\n });\n } catch (error) {\n console.error(\n `Failed to fetch proof-of-ownership nonces for entropy source ID ${entropySourceId}:`,\n error,\n );\n }\n\n return await Promise.all(\n accounts.map(async (queued): Promise<AccountWithScopes> => {\n const candidate = candidates.get(queued.address);\n if (!candidate) {\n return queued;\n }\n const nonce = nonces[candidate.canonicalAddress];\n if (!nonce) {\n return { ...queued, address: candidate.canonicalAddress };\n }\n let proof: AccountOwnershipProof;\n try {\n proof = await this.messenger.call('ProofOfOwnershipService:sign', {\n account: candidate.account,\n nonce,\n });\n } catch (error) {\n console.error(\n `Failed to sign proof of ownership for account ${candidate.account.id}:`,\n error,\n );\n return { ...queued, address: candidate.canonicalAddress };\n }\n return {\n address: candidate.canonicalAddress,\n scopes: queued.scopes,\n proof,\n };\n }),\n );\n }\n\n /**\n * Snapshot the live `InternalAccount` map keyed by address for the\n * current poll.\n *\n * @returns A map of address → `InternalAccount`.\n */\n #getFullAccountsByAddress(): Map<string, InternalAccount> {\n const byAddress = new Map<string, InternalAccount>();\n const accountsState = this.messenger.call('AccountsController:getState');\n for (const account of Object.values(\n accountsState.internalAccounts.accounts,\n )) {\n byAddress.set(account.address, account);\n }\n return byAddress;\n }\n\n /**\n * Enqueue all currently-known accounts onto the sync queue if needed.\n * Single entry point covering both the fresh-install first sync and\n * the one-time proof-of-ownership backfill for users upgrading.\n *\n * Bails for opted-out users (the poll wouldn't drain the queue\n * anyway), and bails once both bootstrap steps have already run.\n * Otherwise enqueues all known accounts and flips both flags so this\n * becomes a permanent no-op for the lifetime of the install.\n */\n async #enqueueAccountsIfNeeded(): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n if (!this.#assertUserOptedIn()) {\n return;\n }\n if (\n this.state.initialEnqueueCompleted &&\n this.state.proofBackfillEnqueued\n ) {\n return;\n }\n const groupedAccounts = groupAccountsByEntropySourceId(\n Object.values(\n this.messenger.call('AccountsController:getState').internalAccounts\n .accounts,\n ),\n );\n this.update((state) => {\n // Replace the queue rather than append. `AccountsController` is\n // the source of truth and the queue is otherwise kept in sync\n // with it via the `accountAdded` / `accountRemoved` subscriptions,\n // so assigning here avoids duplicating entries that survived from\n // a prior session or were pushed earlier in this same unlock\n // cycle. Duplicates would matter because nonces are single-use:\n // letting one through causes `#attachProofs` to sign and submit\n // twice with the same nonce.\n state.syncQueue = groupedAccounts;\n state.initialEnqueueCompleted = true;\n state.proofBackfillEnqueued = true;\n });\n });\n }\n\n /**\n * Set the initial delay end timestamp if it is not already set.\n */\n #setInitialDelayEndTimestampIfNull(): void {\n this.update((state) => {\n state.initialDelayEndTimestamp ??=\n Date.now() + this.#initialDelayDuration;\n });\n }\n\n /**\n * Check if the initial delay end timestamp is in the past.\n *\n * @returns True if the initial delay period has completed, false otherwise.\n */\n #isInitialDelayComplete(): boolean {\n return (\n this.state.initialDelayEndTimestamp !== undefined &&\n Date.now() >= this.state.initialDelayEndTimestamp\n );\n }\n\n /**\n * Queue the given account to be synced at the next poll.\n *\n * @param account - The account to sync.\n */\n async #addAccountToQueue(account: InternalAccount): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n this.update((state) => {\n const entropySourceId = getAccountEntropySourceId(account) ?? 'null';\n if (!state.syncQueue[entropySourceId]) {\n state.syncQueue[entropySourceId] = [];\n }\n state.syncQueue[entropySourceId].push({\n address: account.address,\n scopes: account.scopes,\n });\n });\n });\n }\n\n /**\n * Remove the given account from the sync queue.\n *\n * @param account - The account address to remove.\n */\n async #removeAccountFromQueue(account: string): Promise<void> {\n await this.#mutex.runExclusive(async () => {\n this.update((state) => {\n for (const [entropySourceId, groupedAddresses] of Object.entries(\n state.syncQueue,\n )) {\n const index = groupedAddresses.findIndex(\n ({ address }) => address === account,\n );\n if (index === -1) {\n continue;\n }\n groupedAddresses.splice(index, 1);\n if (groupedAddresses.length === 0) {\n delete state.syncQueue[entropySourceId];\n }\n break;\n }\n });\n });\n }\n}\n\n/**\n * Retrieves the entropy source ID from the given account, if it exists.\n *\n * @param account - The account from which to retrieve the entropy source ID.\n * @returns The entropy source ID, or null if it does not exist.\n */\nfunction getAccountEntropySourceId(account: InternalAccount): string | null {\n if (account.options.entropy?.type === 'mnemonic') {\n return account.options.entropy.id;\n }\n return null;\n}\n\n/**\n * Groups accounts by their entropy source ID.\n *\n * @param accounts - The accounts to group.\n * @returns An object where each key is an entropy source ID and each value is\n * an array of account addresses associated with that entropy source ID.\n */\nfunction groupAccountsByEntropySourceId(\n accounts: InternalAccount[],\n): Record<string, AccountWithScopes[]> {\n return accounts.reduce(\n (result: Record<string, AccountWithScopes[]>, account) => {\n const entropySourceId = getAccountEntropySourceId(account);\n const key = entropySourceId ?? 'null';\n if (!result[key]) {\n result[key] = [];\n }\n result[key].push({ address: account.address, scopes: account.scopes });\n return result;\n },\n {},\n );\n}\n"]}
@@ -2,7 +2,7 @@
2
2
  * This file is auto generated.
3
3
  * Do not edit manually.
4
4
  */
5
- import type { ProfileMetricsService } from "./ProfileMetricsService.cjs";
5
+ import type { ProfileMetricsService } from './ProfileMetricsService.js';
6
6
  /**
7
7
  * Fetch single-use nonces from the auth API, one per identifier.
8
8
  *
@@ -42,4 +42,4 @@ export type ProfileMetricsServiceSubmitMetricsAction = {
42
42
  * Union of all ProfileMetricsService action types.
43
43
  */
44
44
  export type ProfileMetricsServiceMethodActions = ProfileMetricsServiceFetchNoncesAction | ProfileMetricsServiceSubmitMetricsAction;
45
- //# sourceMappingURL=ProfileMetricsService-method-action-types.d.cts.map
45
+ //# sourceMappingURL=ProfileMetricsService-method-action-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ProfileMetricsService-method-action-types.d.ts","sourceRoot":"","sources":["../src/ProfileMetricsService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAExE;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,MAAM,sCAAsC,GAAG;IACnD,IAAI,EAAE,mCAAmC,CAAC;IAC1C,OAAO,EAAE,qBAAqB,CAAC,aAAa,CAAC,CAAC;CAC/C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,wCAAwC,GAAG;IACrD,IAAI,EAAE,qCAAqC,CAAC;IAC5C,OAAO,EAAE,qBAAqB,CAAC,eAAe,CAAC,CAAC;CACjD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kCAAkC,GAC1C,sCAAsC,GACtC,wCAAwC,CAAC"}
@@ -3,4 +3,4 @@
3
3
  * Do not edit manually.
4
4
  */
5
5
  export {};
6
- //# sourceMappingURL=ProfileMetricsService-method-action-types.mjs.map
6
+ //# sourceMappingURL=ProfileMetricsService-method-action-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ProfileMetricsService-method-action-types.js","sourceRoot":"","sources":["../src/ProfileMetricsService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { ProfileMetricsService } from './ProfileMetricsService.js';\n\n/**\n * Fetch single-use nonces from the auth API, one per identifier.\n *\n * Requests larger than {@link MAX_NONCE_BATCH_SIZE} are split into multiple\n * `POST /api/v2/nonce/batch` calls fired in parallel; the resulting maps are\n * merged into a single record. Each chunk independently goes through the\n * service policy (retry, circuit-breaker, degraded). If any chunk ultimately\n * fails, the whole call rejects so the caller can soft-degrade the entire\n * entropy-source batch consistently.\n *\n * The returned record is keyed by the auth API's echoed `identifier` field\n * (`response[i].identifier -> response[i].nonce`). The call asserts that\n * the response identifier set is exactly the requested set; any mismatch\n * (missing, extra, or duplicated identifier) causes the chunk to throw so\n * the caller never silently proceeds with partial nonces.\n *\n * @param data - The identifiers to mint nonces for, plus the optional\n * entropy source ID used to scope the bearer token.\n * @returns A map of identifier -> nonce.\n * @throws {RangeError} if no identifiers are provided.\n */\nexport type ProfileMetricsServiceFetchNoncesAction = {\n type: `ProfileMetricsService:fetchNonces`;\n handler: ProfileMetricsService['fetchNonces'];\n};\n\n/**\n * Submit metrics to the API.\n *\n * @param data - The data to send in the metrics update request.\n * @returns The response from the API.\n */\nexport type ProfileMetricsServiceSubmitMetricsAction = {\n type: `ProfileMetricsService:submitMetrics`;\n handler: ProfileMetricsService['submitMetrics'];\n};\n\n/**\n * Union of all ProfileMetricsService action types.\n */\nexport type ProfileMetricsServiceMethodActions =\n | ProfileMetricsServiceFetchNoncesAction\n | ProfileMetricsServiceSubmitMetricsAction;\n"]}