@metamask-previews/profile-metrics-controller 4.0.3-preview-4f4c98e → 4.0.3-preview-eb263b0ee
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +0 -1
- package/dist/ProfileMetricsController-method-action-types.cjs +7 -0
- package/dist/ProfileMetricsController-method-action-types.cjs.map +1 -0
- package/dist/{ProfileMetricsController-method-action-types.d.ts → ProfileMetricsController-method-action-types.d.cts} +2 -2
- package/dist/ProfileMetricsController-method-action-types.d.cts.map +1 -0
- package/dist/ProfileMetricsController-method-action-types.d.mts +18 -0
- package/dist/ProfileMetricsController-method-action-types.d.mts.map +1 -0
- package/dist/{ProfileMetricsController-method-action-types.js → ProfileMetricsController-method-action-types.mjs} +1 -1
- package/dist/ProfileMetricsController-method-action-types.mjs.map +1 -0
- package/dist/ProfileMetricsController.cjs +399 -0
- package/dist/ProfileMetricsController.cjs.map +1 -0
- package/dist/{ProfileMetricsController.d.ts → ProfileMetricsController.d.cts} +18 -18
- package/dist/ProfileMetricsController.d.cts.map +1 -0
- package/dist/ProfileMetricsController.d.mts +154 -0
- package/dist/ProfileMetricsController.d.mts.map +1 -0
- package/dist/{ProfileMetricsController.js → ProfileMetricsController.mjs} +5 -5
- package/dist/ProfileMetricsController.mjs.map +1 -0
- package/dist/ProfileMetricsService-method-action-types.cjs +7 -0
- package/dist/ProfileMetricsService-method-action-types.cjs.map +1 -0
- package/dist/{ProfileMetricsService-method-action-types.d.ts → ProfileMetricsService-method-action-types.d.cts} +2 -2
- package/dist/ProfileMetricsService-method-action-types.d.cts.map +1 -0
- package/dist/ProfileMetricsService-method-action-types.d.mts +45 -0
- package/dist/ProfileMetricsService-method-action-types.d.mts.map +1 -0
- package/dist/{ProfileMetricsService-method-action-types.js → ProfileMetricsService-method-action-types.mjs} +1 -1
- package/dist/ProfileMetricsService-method-action-types.mjs.map +1 -0
- package/dist/ProfileMetricsService.cjs +298 -0
- package/dist/ProfileMetricsService.cjs.map +1 -0
- package/dist/{ProfileMetricsService.d.ts → ProfileMetricsService.d.cts} +7 -7
- package/dist/ProfileMetricsService.d.cts.map +1 -0
- package/dist/ProfileMetricsService.d.mts +204 -0
- package/dist/ProfileMetricsService.d.mts.map +1 -0
- package/dist/{ProfileMetricsService.js → ProfileMetricsService.mjs} +6 -6
- package/dist/ProfileMetricsService.mjs.map +1 -0
- package/dist/ProofOfOwnershipService-method-action-types.cjs +7 -0
- package/dist/ProofOfOwnershipService-method-action-types.cjs.map +1 -0
- package/dist/{ProofOfOwnershipService-method-action-types.d.ts → ProofOfOwnershipService-method-action-types.d.cts} +2 -2
- package/dist/ProofOfOwnershipService-method-action-types.d.cts.map +1 -0
- package/dist/ProofOfOwnershipService-method-action-types.d.mts +29 -0
- package/dist/ProofOfOwnershipService-method-action-types.d.mts.map +1 -0
- package/dist/{ProofOfOwnershipService-method-action-types.js → ProofOfOwnershipService-method-action-types.mjs} +1 -1
- package/dist/ProofOfOwnershipService-method-action-types.mjs.map +1 -0
- package/dist/ProofOfOwnershipService.cjs +211 -0
- package/dist/ProofOfOwnershipService.cjs.map +1 -0
- package/dist/{ProofOfOwnershipService.d.ts → ProofOfOwnershipService.d.cts} +7 -7
- package/dist/ProofOfOwnershipService.d.cts.map +1 -0
- package/dist/ProofOfOwnershipService.d.mts +112 -0
- package/dist/ProofOfOwnershipService.d.mts.map +1 -0
- package/dist/{ProofOfOwnershipService.js → ProofOfOwnershipService.mjs} +6 -6
- package/dist/ProofOfOwnershipService.mjs.map +1 -0
- package/dist/index.cjs +14 -0
- package/dist/index.cjs.map +1 -0
- package/dist/{index.d.ts → index.d.cts} +9 -9
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +9 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +4 -0
- package/dist/index.mjs.map +1 -0
- package/dist/utils/canonicalize.cjs +72 -0
- package/dist/utils/canonicalize.cjs.map +1 -0
- package/dist/utils/{canonicalize.d.ts → canonicalize.d.cts} +1 -1
- package/dist/utils/canonicalize.d.cts.map +1 -0
- package/dist/utils/canonicalize.d.mts +30 -0
- package/dist/utils/canonicalize.d.mts.map +1 -0
- package/dist/utils/{canonicalize.js → canonicalize.mjs} +3 -3
- package/dist/utils/canonicalize.mjs.map +1 -0
- package/package.json +16 -12
- package/dist/ProfileMetricsController-method-action-types.d.ts.map +0 -1
- package/dist/ProfileMetricsController-method-action-types.js.map +0 -1
- package/dist/ProfileMetricsController.d.ts.map +0 -1
- package/dist/ProfileMetricsController.js.map +0 -1
- package/dist/ProfileMetricsService-method-action-types.d.ts.map +0 -1
- package/dist/ProfileMetricsService-method-action-types.js.map +0 -1
- package/dist/ProfileMetricsService.d.ts.map +0 -1
- package/dist/ProfileMetricsService.js.map +0 -1
- package/dist/ProofOfOwnershipService-method-action-types.d.ts.map +0 -1
- package/dist/ProofOfOwnershipService-method-action-types.js.map +0 -1
- package/dist/ProofOfOwnershipService.d.ts.map +0 -1
- package/dist/ProofOfOwnershipService.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -4
- package/dist/index.js.map +0 -1
- package/dist/utils/canonicalize.d.ts.map +0 -1
- package/dist/utils/canonicalize.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,7 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
### Changed
|
|
11
11
|
|
|
12
|
-
- **BREAKING:** Bump minimum Node.js version to 22 ([#9168](https://github.com/MetaMask/core/pull/9168))
|
|
13
12
|
- Bump `@metamask/transaction-controller` from `^69.4.0` to `^69.6.1` ([#9780](https://github.com/MetaMask/core/pull/9780), [#9798](https://github.com/MetaMask/core/pull/9798), [#9823](https://github.com/MetaMask/core/pull/9823), [#9960](https://github.com/MetaMask/core/pull/9960), [#9969](https://github.com/MetaMask/core/pull/9969))
|
|
14
13
|
- Bump `@metamask/superstruct` from `^3.1.0` to `^3.4.1` ([#9754](https://github.com/MetaMask/core/pull/9754))
|
|
15
14
|
- Bump `@metamask/accounts-controller` from `^39.0.6` to `^39.1.1` ([#9791](https://github.com/MetaMask/core/pull/9791), [#9807](https://github.com/MetaMask/core/pull/9807), [#9969](https://github.com/MetaMask/core/pull/9969))
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ProfileMetricsController-method-action-types.cjs","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"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* This file is auto generated.
|
|
3
3
|
* Do not edit manually.
|
|
4
4
|
*/
|
|
5
|
-
import type { ProfileMetricsController } from
|
|
5
|
+
import type { ProfileMetricsController } from "./ProfileMetricsController.cjs";
|
|
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.
|
|
18
|
+
//# sourceMappingURL=ProfileMetricsController-method-action-types.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ProfileMetricsController-method-action-types.d.cts","sourceRoot":"","sources":["../src/ProfileMetricsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,wBAAwB,EAAE,uCAAsC;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"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is auto generated.
|
|
3
|
+
* Do not edit manually.
|
|
4
|
+
*/
|
|
5
|
+
import type { ProfileMetricsController } from "./ProfileMetricsController.mjs";
|
|
6
|
+
/**
|
|
7
|
+
* Skip the initial delay period by setting the end timestamp to the current time.
|
|
8
|
+
* Metrics will be sent on the next poll.
|
|
9
|
+
*/
|
|
10
|
+
export type ProfileMetricsControllerSkipInitialDelayAction = {
|
|
11
|
+
type: `ProfileMetricsController:skipInitialDelay`;
|
|
12
|
+
handler: ProfileMetricsController['skipInitialDelay'];
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Union of all ProfileMetricsController action types.
|
|
16
|
+
*/
|
|
17
|
+
export type ProfileMetricsControllerMethodActions = ProfileMetricsControllerSkipInitialDelayAction;
|
|
18
|
+
//# sourceMappingURL=ProfileMetricsController-method-action-types.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ProfileMetricsController-method-action-types.d.mts","sourceRoot":"","sources":["../src/ProfileMetricsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,wBAAwB,EAAE,uCAAsC;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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ProfileMetricsController-method-action-types.mjs","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"]}
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
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
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
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 _ProfileMetricsController_instances, _ProfileMetricsController_mutex, _ProfileMetricsController_assertUserOptedIn, _ProfileMetricsController_getMetaMetricsId, _ProfileMetricsController_initialDelayDuration, _ProfileMetricsController_attachProofs, _ProfileMetricsController_getFullAccountsByAddress, _ProfileMetricsController_enqueueAccountsIfNeeded, _ProfileMetricsController_setInitialDelayEndTimestampIfNull, _ProfileMetricsController_isInitialDelayComplete, _ProfileMetricsController_addAccountToQueue, _ProfileMetricsController_removeAccountFromQueue;
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.ProfileMetricsController = exports.getDefaultProfileMetricsControllerState = exports.DEFAULT_INITIAL_DELAY_DURATION = exports.controllerName = void 0;
|
|
16
|
+
const polling_controller_1 = require("@metamask/polling-controller");
|
|
17
|
+
const utils_1 = require("@metamask/utils");
|
|
18
|
+
const async_mutex_1 = require("async-mutex");
|
|
19
|
+
const canonicalize_js_1 = require("./utils/canonicalize.cjs");
|
|
20
|
+
/**
|
|
21
|
+
* The name of the {@link ProfileMetricsController}, used to namespace the
|
|
22
|
+
* controller's actions and events and to namespace the controller's state data
|
|
23
|
+
* when composed with other controllers.
|
|
24
|
+
*/
|
|
25
|
+
exports.controllerName = 'ProfileMetricsController';
|
|
26
|
+
/**
|
|
27
|
+
* The default delay duration before data is sent for the first time.
|
|
28
|
+
*/
|
|
29
|
+
exports.DEFAULT_INITIAL_DELAY_DURATION = (0, utils_1.inMilliseconds)(1, utils_1.Duration.Minute);
|
|
30
|
+
/**
|
|
31
|
+
* The metadata for each property in {@link ProfileMetricsControllerState}.
|
|
32
|
+
*/
|
|
33
|
+
const profileMetricsControllerMetadata = {
|
|
34
|
+
initialEnqueueCompleted: {
|
|
35
|
+
persist: true,
|
|
36
|
+
includeInDebugSnapshot: true,
|
|
37
|
+
includeInStateLogs: true,
|
|
38
|
+
usedInUi: false,
|
|
39
|
+
},
|
|
40
|
+
syncQueue: {
|
|
41
|
+
persist: true,
|
|
42
|
+
includeInDebugSnapshot: false,
|
|
43
|
+
includeInStateLogs: true,
|
|
44
|
+
usedInUi: false,
|
|
45
|
+
},
|
|
46
|
+
initialDelayEndTimestamp: {
|
|
47
|
+
persist: true,
|
|
48
|
+
includeInDebugSnapshot: true,
|
|
49
|
+
includeInStateLogs: true,
|
|
50
|
+
usedInUi: false,
|
|
51
|
+
},
|
|
52
|
+
proofBackfillEnqueued: {
|
|
53
|
+
persist: true,
|
|
54
|
+
includeInDebugSnapshot: true,
|
|
55
|
+
includeInStateLogs: true,
|
|
56
|
+
usedInUi: false,
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Constructs the default {@link ProfileMetricsController} state. This allows
|
|
61
|
+
* consumers to provide a partial state object when initializing the controller
|
|
62
|
+
* and also helps in constructing complete state objects for this controller in
|
|
63
|
+
* tests.
|
|
64
|
+
*
|
|
65
|
+
* @returns The default {@link ProfileMetricsController} state.
|
|
66
|
+
*/
|
|
67
|
+
function getDefaultProfileMetricsControllerState() {
|
|
68
|
+
return {
|
|
69
|
+
initialEnqueueCompleted: false,
|
|
70
|
+
syncQueue: {},
|
|
71
|
+
proofBackfillEnqueued: false,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
exports.getDefaultProfileMetricsControllerState = getDefaultProfileMetricsControllerState;
|
|
75
|
+
const MESSENGER_EXPOSED_METHODS = ['skipInitialDelay'];
|
|
76
|
+
/**
|
|
77
|
+
* Manages user profile metrics.
|
|
78
|
+
*
|
|
79
|
+
* For users who opt-in to metrics, this controller ensures we have metrics about their user
|
|
80
|
+
* profile (metrics ID and accounts).
|
|
81
|
+
*/
|
|
82
|
+
class ProfileMetricsController extends (0, polling_controller_1.StaticIntervalPollingController)() {
|
|
83
|
+
/**
|
|
84
|
+
* Constructs a new {@link ProfileMetricsController}.
|
|
85
|
+
*
|
|
86
|
+
* @param args - The constructor arguments.
|
|
87
|
+
* @param args.messenger - The messenger suited for this controller.
|
|
88
|
+
* @param args.state - The desired state with which to initialize this
|
|
89
|
+
* controller. Missing properties will be filled in with defaults.
|
|
90
|
+
* @param args.assertUserOptedIn - A function that asserts whether the user has
|
|
91
|
+
* opted in to user profile features. If the user has not opted in, sync
|
|
92
|
+
* operations will be no-ops.
|
|
93
|
+
* @param args.getMetaMetricsId - A function that returns the MetaMetrics ID
|
|
94
|
+
* of the user.
|
|
95
|
+
* @param args.interval - The interval, in milliseconds, at which the controller will
|
|
96
|
+
* attempt to send user profile data. Defaults to 10 seconds.
|
|
97
|
+
* @param args.initialDelayDuration - The delay duration before data is sent
|
|
98
|
+
* for the first time, in milliseconds. Defaults to 10 minutes.
|
|
99
|
+
*/
|
|
100
|
+
constructor({ messenger, state, assertUserOptedIn, getMetaMetricsId, interval = 10 * 1000, initialDelayDuration = exports.DEFAULT_INITIAL_DELAY_DURATION, }) {
|
|
101
|
+
super({
|
|
102
|
+
messenger,
|
|
103
|
+
metadata: profileMetricsControllerMetadata,
|
|
104
|
+
name: exports.controllerName,
|
|
105
|
+
state: {
|
|
106
|
+
...getDefaultProfileMetricsControllerState(),
|
|
107
|
+
...state,
|
|
108
|
+
},
|
|
109
|
+
});
|
|
110
|
+
_ProfileMetricsController_instances.add(this);
|
|
111
|
+
_ProfileMetricsController_mutex.set(this, new async_mutex_1.Mutex());
|
|
112
|
+
_ProfileMetricsController_assertUserOptedIn.set(this, void 0);
|
|
113
|
+
_ProfileMetricsController_getMetaMetricsId.set(this, void 0);
|
|
114
|
+
_ProfileMetricsController_initialDelayDuration.set(this, void 0);
|
|
115
|
+
__classPrivateFieldSet(this, _ProfileMetricsController_assertUserOptedIn, assertUserOptedIn, "f");
|
|
116
|
+
__classPrivateFieldSet(this, _ProfileMetricsController_getMetaMetricsId, getMetaMetricsId, "f");
|
|
117
|
+
__classPrivateFieldSet(this, _ProfileMetricsController_initialDelayDuration, initialDelayDuration, "f");
|
|
118
|
+
this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
|
|
119
|
+
this.messenger.subscribe('KeyringController:unlock', () => {
|
|
120
|
+
if (__classPrivateFieldGet(this, _ProfileMetricsController_assertUserOptedIn, "f").call(this)) {
|
|
121
|
+
// If the user has already opted in at the start of the session,
|
|
122
|
+
// it must have opted in during onboarding, or during a previous session.
|
|
123
|
+
this.skipInitialDelay();
|
|
124
|
+
}
|
|
125
|
+
__classPrivateFieldGet(this, _ProfileMetricsController_instances, "m", _ProfileMetricsController_enqueueAccountsIfNeeded).call(this).catch(this.messenger.captureException ?? console.error);
|
|
126
|
+
this.startPolling(null);
|
|
127
|
+
});
|
|
128
|
+
this.messenger.subscribe('KeyringController:lock', () => this.stopAllPolling());
|
|
129
|
+
this.messenger.subscribe('TransactionController:transactionSubmitted', () => this.skipInitialDelay());
|
|
130
|
+
this.messenger.subscribe('AccountsController:accountAdded', (account) => {
|
|
131
|
+
__classPrivateFieldGet(this, _ProfileMetricsController_instances, "m", _ProfileMetricsController_addAccountToQueue).call(this, account).catch(console.error);
|
|
132
|
+
});
|
|
133
|
+
this.messenger.subscribe('AccountsController:accountRemoved', (account) => {
|
|
134
|
+
__classPrivateFieldGet(this, _ProfileMetricsController_instances, "m", _ProfileMetricsController_removeAccountFromQueue).call(this, account).catch(console.error);
|
|
135
|
+
});
|
|
136
|
+
this.setIntervalLength(interval);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Skip the initial delay period by setting the end timestamp to the current time.
|
|
140
|
+
* Metrics will be sent on the next poll.
|
|
141
|
+
*/
|
|
142
|
+
skipInitialDelay() {
|
|
143
|
+
this.update((state) => {
|
|
144
|
+
state.initialDelayEndTimestamp = Date.now();
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Execute a single poll to sync user profile data.
|
|
149
|
+
*
|
|
150
|
+
* The queued accounts are sent to the ProfileMetricsService, each with
|
|
151
|
+
* a proof of ownership when one can be produced (see {@link #attachProofs}),
|
|
152
|
+
* and the sync queue is cleared. This operation is mutexed to prevent
|
|
153
|
+
* concurrent executions.
|
|
154
|
+
*
|
|
155
|
+
* @returns A promise that resolves when the poll is complete.
|
|
156
|
+
*/
|
|
157
|
+
async _executePoll() {
|
|
158
|
+
await __classPrivateFieldGet(this, _ProfileMetricsController_mutex, "f").runExclusive(async () => {
|
|
159
|
+
if (!__classPrivateFieldGet(this, _ProfileMetricsController_assertUserOptedIn, "f").call(this)) {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
__classPrivateFieldGet(this, _ProfileMetricsController_instances, "m", _ProfileMetricsController_setInitialDelayEndTimestampIfNull).call(this);
|
|
163
|
+
if (!__classPrivateFieldGet(this, _ProfileMetricsController_instances, "m", _ProfileMetricsController_isInitialDelayComplete).call(this)) {
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const fullAccountsByAddress = __classPrivateFieldGet(this, _ProfileMetricsController_instances, "m", _ProfileMetricsController_getFullAccountsByAddress).call(this);
|
|
167
|
+
for (const [entropySourceId, accounts] of Object.entries(this.state.syncQueue)) {
|
|
168
|
+
const normalizedEntropySourceId = entropySourceId === 'null' ? null : entropySourceId;
|
|
169
|
+
// Skip proof-of-ownership for accounts without an entropy source
|
|
170
|
+
const accountsWithProofs = normalizedEntropySourceId === null
|
|
171
|
+
? accounts
|
|
172
|
+
: await __classPrivateFieldGet(this, _ProfileMetricsController_instances, "m", _ProfileMetricsController_attachProofs).call(this, accounts, fullAccountsByAddress, normalizedEntropySourceId);
|
|
173
|
+
try {
|
|
174
|
+
await this.messenger.call('ProfileMetricsService:submitMetrics', {
|
|
175
|
+
metametricsId: __classPrivateFieldGet(this, _ProfileMetricsController_getMetaMetricsId, "f").call(this),
|
|
176
|
+
entropySourceId: normalizedEntropySourceId,
|
|
177
|
+
accounts: accountsWithProofs,
|
|
178
|
+
});
|
|
179
|
+
this.update((state) => {
|
|
180
|
+
delete state.syncQueue[entropySourceId];
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
// We want to log the error but continue processing other batches.
|
|
185
|
+
console.error(`Failed to submit profile metrics for entropy source ID ${entropySourceId}:`, error);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
exports.ProfileMetricsController = ProfileMetricsController;
|
|
192
|
+
_ProfileMetricsController_mutex = new WeakMap(), _ProfileMetricsController_assertUserOptedIn = new WeakMap(), _ProfileMetricsController_getMetaMetricsId = new WeakMap(), _ProfileMetricsController_initialDelayDuration = new WeakMap(), _ProfileMetricsController_instances = new WeakSet(), _ProfileMetricsController_attachProofs =
|
|
193
|
+
/**
|
|
194
|
+
* Attach a proof of ownership to each account in a single entropy-source
|
|
195
|
+
* batch when possible, canonicalizing the address along the way.
|
|
196
|
+
*
|
|
197
|
+
* Per-account failures (unknown namespace, snap missing the
|
|
198
|
+
* `signProofOfOwnership` method, snap rejection) and whole-batch nonce
|
|
199
|
+
* failures are caught and downgraded to "submit without a proof" so the
|
|
200
|
+
* batch still goes through and the proof is retried on the next poll.
|
|
201
|
+
*
|
|
202
|
+
* @param accounts - The queued accounts for a single batch.
|
|
203
|
+
* @param fullAccountsByAddress - Live `InternalAccount` lookup keyed by address.
|
|
204
|
+
* @param entropySourceId - The entropy source ID for this batch. Callers
|
|
205
|
+
* are expected to short-circuit before invoking this method when the
|
|
206
|
+
* batch has no entropy source; see `_executePoll` for why.
|
|
207
|
+
* @returns The accounts with `proof` populated where signing succeeded.
|
|
208
|
+
*/
|
|
209
|
+
async function _ProfileMetricsController_attachProofs(accounts, fullAccountsByAddress, entropySourceId) {
|
|
210
|
+
const candidates = new Map();
|
|
211
|
+
const identifiers = new Set();
|
|
212
|
+
for (const queued of accounts) {
|
|
213
|
+
const fullAccount = fullAccountsByAddress.get(queued.address);
|
|
214
|
+
if (!fullAccount) {
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
try {
|
|
218
|
+
const [scope] = fullAccount.scopes;
|
|
219
|
+
if (!scope) {
|
|
220
|
+
throw new Error(`Scope not found for account ${fullAccount.id}`);
|
|
221
|
+
}
|
|
222
|
+
const { namespace } = (0, utils_1.parseCaipChainId)(scope);
|
|
223
|
+
const canonicalAddress = (0, canonicalize_js_1.canonicalizeAddress)(fullAccount.address, namespace);
|
|
224
|
+
candidates.set(queued.address, {
|
|
225
|
+
account: fullAccount,
|
|
226
|
+
canonicalAddress,
|
|
227
|
+
});
|
|
228
|
+
identifiers.add(canonicalAddress);
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
// Unsupported namespaces are an expected pass-through; anything
|
|
232
|
+
// else is logged so a new namespace doesn't go unnoticed.
|
|
233
|
+
if (!(error instanceof canonicalize_js_1.ProofUnsupportedNamespaceError)) {
|
|
234
|
+
console.error(`Skipping proof for account ${fullAccount.id}:`, error);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (candidates.size === 0) {
|
|
239
|
+
return accounts;
|
|
240
|
+
}
|
|
241
|
+
let nonces = {};
|
|
242
|
+
try {
|
|
243
|
+
nonces = await this.messenger.call('ProfileMetricsService:fetchNonces', {
|
|
244
|
+
identifiers: [...identifiers],
|
|
245
|
+
entropySourceId,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
console.error(`Failed to fetch proof-of-ownership nonces for entropy source ID ${entropySourceId}:`, error);
|
|
250
|
+
}
|
|
251
|
+
return await Promise.all(accounts.map(async (queued) => {
|
|
252
|
+
const candidate = candidates.get(queued.address);
|
|
253
|
+
if (!candidate) {
|
|
254
|
+
return queued;
|
|
255
|
+
}
|
|
256
|
+
const nonce = nonces[candidate.canonicalAddress];
|
|
257
|
+
if (!nonce) {
|
|
258
|
+
return { ...queued, address: candidate.canonicalAddress };
|
|
259
|
+
}
|
|
260
|
+
let proof;
|
|
261
|
+
try {
|
|
262
|
+
proof = await this.messenger.call('ProofOfOwnershipService:sign', {
|
|
263
|
+
account: candidate.account,
|
|
264
|
+
nonce,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
catch (error) {
|
|
268
|
+
console.error(`Failed to sign proof of ownership for account ${candidate.account.id}:`, error);
|
|
269
|
+
return { ...queued, address: candidate.canonicalAddress };
|
|
270
|
+
}
|
|
271
|
+
return {
|
|
272
|
+
address: candidate.canonicalAddress,
|
|
273
|
+
scopes: queued.scopes,
|
|
274
|
+
proof,
|
|
275
|
+
};
|
|
276
|
+
}));
|
|
277
|
+
}, _ProfileMetricsController_getFullAccountsByAddress = function _ProfileMetricsController_getFullAccountsByAddress() {
|
|
278
|
+
const byAddress = new Map();
|
|
279
|
+
const accountsState = this.messenger.call('AccountsController:getState');
|
|
280
|
+
for (const account of Object.values(accountsState.internalAccounts.accounts)) {
|
|
281
|
+
byAddress.set(account.address, account);
|
|
282
|
+
}
|
|
283
|
+
return byAddress;
|
|
284
|
+
}, _ProfileMetricsController_enqueueAccountsIfNeeded =
|
|
285
|
+
/**
|
|
286
|
+
* Enqueue all currently-known accounts onto the sync queue if needed.
|
|
287
|
+
* Single entry point covering both the fresh-install first sync and
|
|
288
|
+
* the one-time proof-of-ownership backfill for users upgrading.
|
|
289
|
+
*
|
|
290
|
+
* Bails for opted-out users (the poll wouldn't drain the queue
|
|
291
|
+
* anyway), and bails once both bootstrap steps have already run.
|
|
292
|
+
* Otherwise enqueues all known accounts and flips both flags so this
|
|
293
|
+
* becomes a permanent no-op for the lifetime of the install.
|
|
294
|
+
*/
|
|
295
|
+
async function _ProfileMetricsController_enqueueAccountsIfNeeded() {
|
|
296
|
+
await __classPrivateFieldGet(this, _ProfileMetricsController_mutex, "f").runExclusive(async () => {
|
|
297
|
+
if (!__classPrivateFieldGet(this, _ProfileMetricsController_assertUserOptedIn, "f").call(this)) {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
if (this.state.initialEnqueueCompleted &&
|
|
301
|
+
this.state.proofBackfillEnqueued) {
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const groupedAccounts = groupAccountsByEntropySourceId(Object.values(this.messenger.call('AccountsController:getState').internalAccounts
|
|
305
|
+
.accounts));
|
|
306
|
+
this.update((state) => {
|
|
307
|
+
// Replace the queue rather than append. `AccountsController` is
|
|
308
|
+
// the source of truth and the queue is otherwise kept in sync
|
|
309
|
+
// with it via the `accountAdded` / `accountRemoved` subscriptions,
|
|
310
|
+
// so assigning here avoids duplicating entries that survived from
|
|
311
|
+
// a prior session or were pushed earlier in this same unlock
|
|
312
|
+
// cycle. Duplicates would matter because nonces are single-use:
|
|
313
|
+
// letting one through causes `#attachProofs` to sign and submit
|
|
314
|
+
// twice with the same nonce.
|
|
315
|
+
state.syncQueue = groupedAccounts;
|
|
316
|
+
state.initialEnqueueCompleted = true;
|
|
317
|
+
state.proofBackfillEnqueued = true;
|
|
318
|
+
});
|
|
319
|
+
});
|
|
320
|
+
}, _ProfileMetricsController_setInitialDelayEndTimestampIfNull = function _ProfileMetricsController_setInitialDelayEndTimestampIfNull() {
|
|
321
|
+
this.update((state) => {
|
|
322
|
+
state.initialDelayEndTimestamp ?? (state.initialDelayEndTimestamp = Date.now() + __classPrivateFieldGet(this, _ProfileMetricsController_initialDelayDuration, "f"));
|
|
323
|
+
});
|
|
324
|
+
}, _ProfileMetricsController_isInitialDelayComplete = function _ProfileMetricsController_isInitialDelayComplete() {
|
|
325
|
+
return (this.state.initialDelayEndTimestamp !== undefined &&
|
|
326
|
+
Date.now() >= this.state.initialDelayEndTimestamp);
|
|
327
|
+
}, _ProfileMetricsController_addAccountToQueue =
|
|
328
|
+
/**
|
|
329
|
+
* Queue the given account to be synced at the next poll.
|
|
330
|
+
*
|
|
331
|
+
* @param account - The account to sync.
|
|
332
|
+
*/
|
|
333
|
+
async function _ProfileMetricsController_addAccountToQueue(account) {
|
|
334
|
+
await __classPrivateFieldGet(this, _ProfileMetricsController_mutex, "f").runExclusive(async () => {
|
|
335
|
+
this.update((state) => {
|
|
336
|
+
const entropySourceId = getAccountEntropySourceId(account) ?? 'null';
|
|
337
|
+
if (!state.syncQueue[entropySourceId]) {
|
|
338
|
+
state.syncQueue[entropySourceId] = [];
|
|
339
|
+
}
|
|
340
|
+
state.syncQueue[entropySourceId].push({
|
|
341
|
+
address: account.address,
|
|
342
|
+
scopes: account.scopes,
|
|
343
|
+
});
|
|
344
|
+
});
|
|
345
|
+
});
|
|
346
|
+
}, _ProfileMetricsController_removeAccountFromQueue =
|
|
347
|
+
/**
|
|
348
|
+
* Remove the given account from the sync queue.
|
|
349
|
+
*
|
|
350
|
+
* @param account - The account address to remove.
|
|
351
|
+
*/
|
|
352
|
+
async function _ProfileMetricsController_removeAccountFromQueue(account) {
|
|
353
|
+
await __classPrivateFieldGet(this, _ProfileMetricsController_mutex, "f").runExclusive(async () => {
|
|
354
|
+
this.update((state) => {
|
|
355
|
+
for (const [entropySourceId, groupedAddresses] of Object.entries(state.syncQueue)) {
|
|
356
|
+
const index = groupedAddresses.findIndex(({ address }) => address === account);
|
|
357
|
+
if (index === -1) {
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
groupedAddresses.splice(index, 1);
|
|
361
|
+
if (groupedAddresses.length === 0) {
|
|
362
|
+
delete state.syncQueue[entropySourceId];
|
|
363
|
+
}
|
|
364
|
+
break;
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
});
|
|
368
|
+
};
|
|
369
|
+
/**
|
|
370
|
+
* Retrieves the entropy source ID from the given account, if it exists.
|
|
371
|
+
*
|
|
372
|
+
* @param account - The account from which to retrieve the entropy source ID.
|
|
373
|
+
* @returns The entropy source ID, or null if it does not exist.
|
|
374
|
+
*/
|
|
375
|
+
function getAccountEntropySourceId(account) {
|
|
376
|
+
if (account.options.entropy?.type === 'mnemonic') {
|
|
377
|
+
return account.options.entropy.id;
|
|
378
|
+
}
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Groups accounts by their entropy source ID.
|
|
383
|
+
*
|
|
384
|
+
* @param accounts - The accounts to group.
|
|
385
|
+
* @returns An object where each key is an entropy source ID and each value is
|
|
386
|
+
* an array of account addresses associated with that entropy source ID.
|
|
387
|
+
*/
|
|
388
|
+
function groupAccountsByEntropySourceId(accounts) {
|
|
389
|
+
return accounts.reduce((result, account) => {
|
|
390
|
+
const entropySourceId = getAccountEntropySourceId(account);
|
|
391
|
+
const key = entropySourceId ?? 'null';
|
|
392
|
+
if (!result[key]) {
|
|
393
|
+
result[key] = [];
|
|
394
|
+
}
|
|
395
|
+
result[key].push({ address: account.address, scopes: account.scopes });
|
|
396
|
+
return result;
|
|
397
|
+
}, {});
|
|
398
|
+
}
|
|
399
|
+
//# sourceMappingURL=ProfileMetricsController.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ProfileMetricsController.cjs","sourceRoot":"","sources":["../src/ProfileMetricsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAgBA,qEAA+E;AAE/E,2CAA6E;AAC7E,6CAAoC;AASpC,8DAGiC;AAEjC;;;;GAIG;AACU,QAAA,cAAc,GAAG,0BAA0B,CAAC;AAEzD;;GAEG;AACU,QAAA,8BAA8B,GAAG,IAAA,sBAAc,EAC1D,CAAC,EACD,gBAAQ,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,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C,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QACvE,OAAO,MAAM,CAAC;IAChB,CAAC,EACD,EAAE,CACH,CAAC;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"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import type { AccountsControllerAccountAddedEvent, AccountsControllerAccountRemovedEvent, AccountsControllerGetStateAction } from
|
|
2
|
-
import type { ControllerGetStateAction, ControllerStateChangeEvent } from
|
|
3
|
-
import type { KeyringControllerLockEvent, KeyringControllerUnlockEvent } from
|
|
4
|
-
import type { Messenger } from
|
|
5
|
-
import { TransactionControllerTransactionSubmittedEvent } from
|
|
6
|
-
import type { ProfileMetricsControllerMethodActions } from
|
|
7
|
-
import type { ProfileMetricsServiceMethodActions } from
|
|
8
|
-
import type { AccountWithScopes } from
|
|
9
|
-
import type { ProofOfOwnershipServiceMethodActions } from
|
|
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";
|
|
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
|
|
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>>;
|
|
90
97
|
_executePoll(input: import("@metamask/utils").Json): Promise<void>;
|
|
91
98
|
startPolling(input: import("@metamask/utils").Json): string;
|
|
92
99
|
stopAllPolling(): void;
|
|
93
100
|
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.
|
|
154
|
+
//# sourceMappingURL=ProfileMetricsController.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ProfileMetricsController.d.cts","sourceRoot":"","sources":["../src/ProfileMetricsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mCAAmC,EACnC,qCAAqC,EACrC,gCAAgC,EACjC,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,KAAK,EACV,0BAA0B,EAC1B,4BAA4B,EAC7B,qCAAqC;AAEtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAErD,OAAO,EAAE,8CAA8C,EAAE,yCAAyC;AAIlG,OAAO,KAAK,EAAE,qCAAqC,EAAE,2DAA0D;AAC/G,OAAO,KAAK,EAAE,kCAAkC,EAAE,wDAAuD;AACzG,OAAO,KAAK,EAEV,iBAAiB,EAClB,oCAAmC;AACpC,OAAO,KAAK,EAAE,oCAAoC,EAAE,0DAAyD;AAM7G;;;;GAIG;AACH,eAAO,MAAM,cAAc,6BAA6B,CAAC;AAEzD;;GAEG;AACH,eAAO,MAAM,8BAA8B,QAG1C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,6BAA6B,GAAG;IAC1C;;;OAGG;IACH,uBAAuB,EAAE,OAAO,CAAC;IACjC;;;;;OAKG;IACH,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAC/C;;OAEG;IACH,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC;;;;;;OAMG;IACH,qBAAqB,EAAE,OAAO,CAAC;CAChC,CAAC;AAgCF;;;;;;;GAOG;AACH,wBAAgB,uCAAuC,IAAI,6BAA6B,CAMvF;AAID;;GAEG;AACH,MAAM,MAAM,sCAAsC,GAAG,wBAAwB,CAC3E,OAAO,cAAc,EACrB,6BAA6B,CAC9B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,+BAA+B,GACvC,sCAAsC,GACtC,qCAAqC,CAAC;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