-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathmetametrics-controller.ts
More file actions
1789 lines (1634 loc) · 57.8 KB
/
metametrics-controller.ts
File metadata and controls
1789 lines (1634 loc) · 57.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
isEqual,
memoize,
merge,
omit,
omitBy,
pickBy,
size,
sum,
} from 'lodash';
import { keccak256 } from 'ethereum-cryptography/keccak';
import { v4 as uuidv4 } from 'uuid';
import { NameType } from '@metamask/name-controller';
import {
bytesToHex,
getErrorMessage,
type Hex,
isErrorWithMessage,
isErrorWithStack,
} from '@metamask/utils';
import type {
NetworkClientId,
NetworkControllerGetNetworkClientByIdAction,
NetworkControllerGetStateAction,
NetworkControllerNetworkDidChangeEvent,
} from '@metamask/network-controller';
import type { Browser } from 'webextension-polyfill';
import type { Nft } from '@metamask/assets-controllers';
import {
BaseController,
type ControllerGetStateAction,
type ControllerStateChangeEvent,
type StateMetadata,
} from '@metamask/base-controller';
import type { Messenger } from '@metamask/messenger';
import type { Json } from '@metamask/utils';
import { ENVIRONMENT_TYPE_BACKGROUND } from '../../../shared/constants/app';
import {
METAMETRICS_ANONYMOUS_ID,
METAMETRICS_BACKGROUND_PAGE_OBJECT,
MetaMetricsEventCategory,
MetaMetricsEventName,
MetaMetricsUserTrait,
} from '../../../shared/constants/metametrics';
import type {
MetaMetricsEventFragment,
MetaMetricsUserTraits,
SegmentEventPayload,
MetaMetricsContext,
MetaMetricsEventPayload,
MetaMetricsEventOptions,
MetaMetricsPagePayload,
MetaMetricsPageOptions,
MetaMetricsPageObject,
MetaMetricsReferrerObject,
} from '../../../shared/constants/metametrics';
import { SECOND } from '../../../shared/constants/time';
import { isManifestV3 } from '../../../shared/modules/mv3.utils';
import { METAMETRICS_FINALIZE_EVENT_FRAGMENT_ALARM } from '../../../shared/constants/alarms';
import {
checkAlarmExists,
generateRandomId,
getInstallType,
getPlatform,
isValidDate,
} from '../lib/util';
import {
AnonymousTransactionMetaMetricsEvent,
TransactionMetaMetricsEvent,
} from '../../../shared/constants/transaction';
import Analytics from '../lib/segment/analytics';
import {
trace,
endTrace,
type TraceRequest,
type EndTraceRequest,
type TraceCallback,
} from '../../../shared/lib/trace';
///: BEGIN:ONLY_INCLUDE_IF(build-main)
import { ENVIRONMENT } from '../../../development/build/constants';
///: END:ONLY_INCLUDE_IF
import { KeyringType } from '../../../shared/constants/keyring';
import type { captureException } from '../../../shared/lib/sentry';
import type { FlattenedBackgroundStateProxy } from '../../../shared/types';
import type {
PreferencesControllerGetStateAction,
PreferencesControllerStateChangeEvent,
} from './preferences-controller';
// Unique name for the controller
const controllerName = 'MetaMetricsController';
const EXTENSION_UNINSTALL_URL = 'https://metamask.io/uninstalled';
export const overrideAnonymousEventNames = {
[TransactionMetaMetricsEvent.added]:
AnonymousTransactionMetaMetricsEvent.added,
[TransactionMetaMetricsEvent.approved]:
AnonymousTransactionMetaMetricsEvent.approved,
[TransactionMetaMetricsEvent.finalized]:
AnonymousTransactionMetaMetricsEvent.finalized,
[TransactionMetaMetricsEvent.rejected]:
AnonymousTransactionMetaMetricsEvent.rejected,
[TransactionMetaMetricsEvent.submitted]:
AnonymousTransactionMetaMetricsEvent.submitted,
[MetaMetricsEventName.SignatureRequested]:
MetaMetricsEventName.SignatureRequestedAnon,
[MetaMetricsEventName.SignatureApproved]:
MetaMetricsEventName.SignatureApprovedAnon,
[MetaMetricsEventName.SignatureRejected]:
MetaMetricsEventName.SignatureRejectedAnon,
} as const;
const defaultCaptureException = (err: unknown) => {
// throw error on clean stack so its captured by platform integrations (eg sentry)
// but does not interrupt the call stack
setTimeout(() => {
throw err;
});
};
// The function is used to build a unique messageId for segment messages
// It uses actionId and uniqueIdentifier from event if present
const buildUniqueMessageId = (args: {
uniqueIdentifier?: string;
actionId?: string;
isDuplicateAnonymizedEvent?: boolean;
}): string => {
const messageIdParts = [];
if (args.uniqueIdentifier) {
messageIdParts.push(args.uniqueIdentifier);
}
if (args.actionId) {
messageIdParts.push(args.actionId);
}
if (messageIdParts.length && args.isDuplicateAnonymizedEvent) {
messageIdParts.push('0x000');
}
if (messageIdParts.length) {
return messageIdParts.join('-');
}
return generateRandomId();
};
const exceptionsToFilter: Record<string, boolean> = {
[`You must pass either an "anonymousId" or a "userId".`]: true,
};
/**
* The type of a Segment event to create.
*
* Must correspond to the name of a method in {@link Analytics}.
*/
type SegmentEventType = 'identify' | 'track' | 'page';
/**
* Represents a buffered trace that is stored before user consent.
* Simplified for JSON serialization - doesn't include callback functions.
*/
type BufferedTrace = {
type: 'start' | 'end';
request: Record<string, Json>;
parentTraceName?: string;
};
export type MetaMaskState = Pick<
FlattenedBackgroundStateProxy,
| 'ledgerTransportType'
| 'networkConfigurationsByChainId'
| 'internalAccounts'
| 'allNfts'
| 'allTokens'
| 'theme'
| 'participateInMetaMetrics'
| 'dataCollectionForMarketing'
| 'useNftDetection'
| 'openSeaEnabled'
| 'securityAlertsEnabled'
| 'useTokenDetection'
| 'names'
| 'addressBook'
| 'currentCurrency'
| 'srpSessionData'
| 'keyrings'
| 'multichainNetworkConfigurationsByChainId'
// TODO: Remove as this is no longer a top-level property of the flattened background state object.
// | 'security_providers'
> & {
preferences: Pick<
FlattenedBackgroundStateProxy['preferences'],
| 'privacyMode'
| 'tokenNetworkFilter'
| 'showNativeTokenAsMainBalance'
| 'tokenSortConfig'
>;
};
/**
* {@link MetaMetricsController}'s metadata.
*
* This allows us to choose if fields of the state should be persisted or not
* using the `persist` flag; and if they can be sent to Sentry or not, using
* the `anonymous` flag.
*/
const controllerMetadata: StateMetadata<MetaMetricsControllerState> = {
metaMetricsId: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: true,
},
participateInMetaMetrics: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: true,
},
latestNonAnonymousEventTimestamp: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: true,
},
fragments: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
eventsBeforeMetricsOptIn: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
tracesBeforeMetricsOptIn: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
traits: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
dataCollectionForMarketing: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
marketingCampaignCookieId: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: false,
},
segmentApiCalls: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
};
/**
* The state that MetaMetricsController stores.
*
* @property metaMetricsId - The user's metaMetricsId that will be attached to all non-anonymized event payloads
* @property participateInMetaMetrics - The user's preference for participating in the MetaMetrics analytics program.
* This setting controls whether or not events are tracked
* @property latestNonAnonymousEventTimestamp - The timestamp at which last non anonymous event is tracked.
* @property fragments - Object keyed by UUID with stored fragments as values.
* @property eventsBeforeMetricsOptIn - Array of queued events added before a user opts into metrics.
* @property tracesBeforeMetricsOptIn - Array of queued traces added before a user opts into metrics.
* @property traits - Traits that are not derived from other state keys.
* @property dataCollectionForMarketing - Flag to determine if data collection for marketing is enabled.
* @property marketingCampaignCookieId - The marketing campaign cookie id.
* @property segmentApiCalls - Object keyed by messageId with segment event type and payload as values.
*/
export type MetaMetricsControllerState = {
metaMetricsId: string | null;
participateInMetaMetrics: boolean | null;
latestNonAnonymousEventTimestamp: number;
fragments: Record<string, MetaMetricsEventFragment>;
eventsBeforeMetricsOptIn: MetaMetricsEventPayload[];
tracesBeforeMetricsOptIn: BufferedTrace[];
traits: MetaMetricsUserTraits;
dataCollectionForMarketing: boolean | null;
marketingCampaignCookieId: string | null;
segmentApiCalls: Record<
string,
{
eventType: SegmentEventType;
payload: SegmentEventPayload;
}
>;
};
/**
* Returns the state of the {@link MetaMetricsController}.
*/
export type MetaMetricsControllerGetStateAction = ControllerGetStateAction<
typeof controllerName,
MetaMetricsControllerState
>;
export type MetaMetricsControllerTrackEventAction = {
type: `${typeof controllerName}:trackEvent`;
handler: MetaMetricsController['trackEvent'];
};
export type MetaMetricsControllerGetMetaMetricsIdAction = {
type: `${typeof controllerName}:getMetaMetricsId`;
handler: MetaMetricsController['getMetaMetricsId'];
};
export type MetaMetricsControllerCreateEventFragmentAction = {
type: `${typeof controllerName}:createEventFragment`;
handler: MetaMetricsController['createEventFragment'];
};
export type MetaMetricsControllerGetEventFragmentByIdAction = {
type: `${typeof controllerName}:getEventFragmentById`;
handler: MetaMetricsController['getEventFragmentById'];
};
export type MetaMetricsControllerUpdateEventFragmentAction = {
type: `${typeof controllerName}:updateEventFragment`;
handler: MetaMetricsController['updateEventFragment'];
};
export type MetaMetricsControllerDeleteEventFragmentAction = {
type: `${typeof controllerName}:deleteEventFragment`;
handler: MetaMetricsController['deleteEventFragment'];
};
export type MetaMetricsControllerFinalizeEventFragmentAction = {
type: `${typeof controllerName}:finalizeEventFragment`;
handler: MetaMetricsController['finalizeEventFragment'];
};
/**
* Actions exposed by the {@link MetaMetricsController}.
*/
export type MetaMetricsControllerActions =
| MetaMetricsControllerGetStateAction
| MetaMetricsControllerTrackEventAction
| MetaMetricsControllerGetMetaMetricsIdAction
| MetaMetricsControllerCreateEventFragmentAction
| MetaMetricsControllerGetEventFragmentByIdAction
| MetaMetricsControllerUpdateEventFragmentAction
| MetaMetricsControllerDeleteEventFragmentAction
| MetaMetricsControllerFinalizeEventFragmentAction;
/**
* Event emitted when the state of the {@link MetaMetricsController} changes.
*/
export type MetaMetricsControllerStateChangeEvent = ControllerStateChangeEvent<
typeof controllerName,
MetaMetricsControllerState
>;
export type MetaMetricsControllerEvents = MetaMetricsControllerStateChangeEvent;
/**
* Actions that this controller is allowed to call.
*/
export type AllowedActions =
| PreferencesControllerGetStateAction
| NetworkControllerGetStateAction
| NetworkControllerGetNetworkClientByIdAction;
/**
* Events that this controller is allowed to subscribe.
*/
export type AllowedEvents =
| PreferencesControllerStateChangeEvent
| NetworkControllerNetworkDidChangeEvent;
/**
* Messenger type for the {@link MetaMetricsController}.
*/
export type MetaMetricsControllerMessenger = Messenger<
typeof controllerName,
MetaMetricsControllerActions | AllowedActions,
MetaMetricsControllerEvents | AllowedEvents
>;
type CaptureException = typeof captureException | ((err: unknown) => void);
export type MetaMetricsControllerOptions = {
state?: Partial<MetaMetricsControllerState>;
messenger: MetaMetricsControllerMessenger;
segment: Analytics;
version: string;
environment: string;
extension: Browser;
captureException?: CaptureException;
};
/**
* Function to get default state of the {@link MetaMetricsController}.
*/
export const getDefaultMetaMetricsControllerState =
(): MetaMetricsControllerState => ({
participateInMetaMetrics: null,
metaMetricsId: null,
dataCollectionForMarketing: null,
marketingCampaignCookieId: null,
latestNonAnonymousEventTimestamp: 0,
eventsBeforeMetricsOptIn: [],
tracesBeforeMetricsOptIn: [],
traits: {},
fragments: {},
segmentApiCalls: {},
});
export default class MetaMetricsController extends BaseController<
typeof controllerName,
MetaMetricsControllerState,
MetaMetricsControllerMessenger
> {
#captureException: CaptureException;
chainId: Hex;
locale: string;
previousUserTraits?: MetaMetricsUserTraits;
version: MetaMetricsControllerOptions['version'];
#extension: MetaMetricsControllerOptions['extension'];
#environment: MetaMetricsControllerOptions['environment'];
#segment: MetaMetricsControllerOptions['segment'];
/**
* @param options
* @param options.state - Initial controller state.
* @param options.messenger - Messenger used to communicate with BaseV2 controller.
* @param options.segment - an instance of analytics for tracking
* events that conform to the new MetaMetrics tracking plan.
* @param options.version - The version of the extension
* @param options.environment - The environment the extension is running in
* @param options.extension - webextension-polyfill
* @param options.captureException
*/
constructor({
state = {},
messenger,
segment,
version,
environment,
extension,
captureException = defaultCaptureException,
}: MetaMetricsControllerOptions) {
super({
name: controllerName,
metadata: controllerMetadata,
state: {
...getDefaultMetaMetricsControllerState(),
...state,
},
messenger,
});
this.#captureException = (err: unknown) => {
const message = getErrorMessage(err);
// This is a temporary measure. Currently there are errors flooding sentry due to a problem in how we are tracking anonymousId
// We intend on removing this as soon as we understand how to correctly solve that problem.
if (!exceptionsToFilter[message]) {
captureException(err);
}
};
this.chainId = this.#getCurrentChainId();
const preferencesControllerState = this.messenger.call(
'PreferencesController:getState',
);
this.locale = preferencesControllerState.currentLocale.replace('_', '-');
this.version =
environment === 'production' ? version : `${version}-${environment}`;
this.#extension = extension;
this.#environment = environment;
this.messenger.registerActionHandler(
'MetaMetricsController:trackEvent',
this.trackEvent.bind(this),
);
this.messenger.registerActionHandler(
'MetaMetricsController:getMetaMetricsId',
this.getMetaMetricsId.bind(this),
);
this.messenger.registerActionHandler(
'MetaMetricsController:createEventFragment',
this.createEventFragment.bind(this),
);
this.messenger.registerActionHandler(
'MetaMetricsController:getEventFragmentById',
this.getEventFragmentById.bind(this),
);
this.messenger.registerActionHandler(
'MetaMetricsController:updateEventFragment',
this.updateEventFragment.bind(this),
);
this.messenger.registerActionHandler(
'MetaMetricsController:deleteEventFragment',
this.deleteEventFragment.bind(this),
);
this.messenger.registerActionHandler(
'MetaMetricsController:finalizeEventFragment',
this.finalizeEventFragment.bind(this),
);
const abandonedFragments = omitBy(state.fragments, 'persist');
this.messenger.subscribe(
'PreferencesController:stateChange',
({ currentLocale }) => {
this.locale = currentLocale?.replace('_', '-');
},
);
this.messenger.subscribe(
'NetworkController:networkDidChange',
({ selectedNetworkClientId }) => {
this.chainId = this.#getCurrentChainId(selectedNetworkClientId);
},
);
this.#segment = segment;
// Track abandoned fragments that weren't properly cleaned up.
// Abandoned fragments are those that were stored in persistent memory
// and are available at controller instance creation, but do not have the
// 'persist' flag set. This means anytime the extension is unlocked, any
// fragments that are not marked as persistent will be purged and the
// failure event will be emitted.
Object.values(abandonedFragments).forEach((fragment) => {
this.processAbandonedFragment(fragment);
});
// Code below submits any pending segmentApiCalls to Segment if/when the controller is re-instantiated
if (isManifestV3) {
// TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31880
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
Object.values(state.segmentApiCalls || {}).forEach(
({ eventType, payload }) => {
try {
this.#submitSegmentAPICall(eventType, payload);
} catch (error) {
this.#captureException(error);
}
},
);
}
// Close out event fragments that were created but not progressed. An
// interval is used to routinely check if a fragment has not been updated
// within the fragment's timeout window. When creating a new event fragment
// a timeout can be specified that will cause an abandoned event to be
// tracked if the event isn't progressed within that amount of time.
if (isManifestV3) {
/* eslint-disable no-undef */
this.#extension.alarms.getAll().then((alarms) => {
const hasAlarm = checkAlarmExists(
alarms,
METAMETRICS_FINALIZE_EVENT_FRAGMENT_ALARM,
);
if (!hasAlarm) {
this.#extension.alarms.create(
METAMETRICS_FINALIZE_EVENT_FRAGMENT_ALARM,
{
delayInMinutes: 1,
periodInMinutes: 1,
},
);
}
});
this.#extension.alarms.onAlarm.addListener((alarmInfo) => {
if (alarmInfo.name === METAMETRICS_FINALIZE_EVENT_FRAGMENT_ALARM) {
this.finalizeAbandonedFragments();
}
});
} else {
setInterval(() => {
this.finalizeAbandonedFragments();
}, SECOND * 30);
}
}
/**
* Gets the current chain ID.
*
* @param networkClientId - The network client ID to get the chain ID for.
*/
#getCurrentChainId(networkClientId?: NetworkClientId): Hex {
const selectedNetworkClientId =
// TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31880
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
networkClientId ||
this.messenger.call('NetworkController:getState').selectedNetworkClientId;
const {
configuration: { chainId },
} = this.messenger.call(
'NetworkController:getNetworkClientById',
selectedNetworkClientId,
);
return chainId;
}
finalizeAbandonedFragments(): void {
Object.values(this.state.fragments).forEach((fragment) => {
if (
fragment.timeout &&
fragment.lastUpdated &&
Date.now() - fragment.lastUpdated / 1000 > fragment.timeout
) {
this.processAbandonedFragment(fragment);
}
});
}
generateMetaMetricsId(): string {
return bytesToHex(
keccak256(
Buffer.from(
String(Date.now()) +
String(Math.round(Math.random() * Number.MAX_SAFE_INTEGER)),
),
),
);
}
/**
* Create an event fragment in state and returns the event fragment object.
*
* @param options - Fragment settings and properties to initiate the fragment with.
*/
createEventFragment(
options: Omit<MetaMetricsEventFragment, 'id'>,
): MetaMetricsEventFragment {
if (!options.successEvent) {
throw new Error(
`Must specify success event. Success event was: ${
options.event
// TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31893
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
}. Payload keys were: ${Object.keys(options)}. ${
typeof options.properties === 'object'
? // TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31893
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Payload property keys were: ${Object.keys(options.properties)}`
: ''
}`,
);
}
const { fragments } = this.state;
const id = options.uniqueIdentifier ?? uuidv4();
const fragment = {
id,
...options,
lastUpdated: Date.now(),
};
/**
* HACK: "transaction-submitted-<id>" fragment hack
* A "transaction-submitted-<id>" fragment may exist following the "Transaction Added"
* event to persist accumulated event fragment props to the "Transaction Submitted" event
* which fires after a user confirms a transaction. Rejecting a confirmation does not fire the
* "Transaction Submitted" event. In this case, these abandoned fragments will be deleted
* instead of finalized with canDeleteIfAbandoned set to true.
*/
const hasExistingSubmittedFragment =
options.initialEvent === TransactionMetaMetricsEvent.submitted &&
fragments[id];
const additionalFragmentProps = hasExistingSubmittedFragment
? {
...fragments[id],
canDeleteIfAbandoned: false,
}
: {};
this.update((state) => {
state.fragments[id] = merge({}, additionalFragmentProps, fragment);
});
if (fragment.initialEvent) {
this.trackEvent({
event: fragment.initialEvent,
category: fragment.category,
properties: fragment.properties,
sensitiveProperties: fragment.sensitiveProperties,
page: fragment.page,
referrer: fragment.referrer,
revenue: fragment.revenue,
value: fragment.value,
currency: fragment.currency,
environmentType: fragment.environmentType,
actionId: options.actionId,
uniqueIdentifier: options.uniqueIdentifier,
});
}
return fragment;
}
/**
* Returns the fragment stored in memory with provided id or undefined if it
* does not exist.
*
* @param id - id of fragment to retrieve
*/
getEventFragmentById(id: string): MetaMetricsEventFragment {
return this.state.fragments[id];
}
/**
* Deletes to finalizes event fragment based on the canDeleteIfAbandoned property.
*
* @param fragment
*/
processAbandonedFragment(fragment: MetaMetricsEventFragment): void {
if (fragment.canDeleteIfAbandoned) {
this.deleteEventFragment(fragment.id);
} else {
this.finalizeEventFragment(fragment.id, { abandoned: true });
}
}
/**
* Updates an event fragment in state
*
* @param id - The fragment id to update
* @param payload - Fragment settings and properties to initiate the fragment with.
*/
updateEventFragment(
id: string,
payload: Partial<MetaMetricsEventFragment>,
): void {
const { fragments } = this.state;
const fragment = fragments[id];
/**
* HACK: "transaction-submitted-<id>" fragment hack
* Creates a "transaction-submitted-<id>" fragment if it does not exist to persist
* accumulated event metrics. In the case it is unused, the abandoned fragment will
* eventually be deleted with canDeleteIfAbandoned set to true.
*/
const createIfNotFound = !fragment && id.includes('transaction-submitted-');
if (createIfNotFound) {
this.update((state) => {
state.fragments[id] = {
canDeleteIfAbandoned: true,
category: MetaMetricsEventCategory.Transactions,
successEvent: TransactionMetaMetricsEvent.finalized,
id,
...payload,
lastUpdated: Date.now(),
};
});
return;
} else if (!fragment) {
throw new Error(`Event fragment with id ${id} does not exist.`);
}
this.update((state) => {
state.fragments[id] = merge(state.fragments[id], {
...payload,
lastUpdated: Date.now(),
});
});
}
/**
* Deletes an event fragment from state
*
* @param id - The fragment id to delete
*/
deleteEventFragment(id: string): void {
if (this.state.fragments[id]) {
this.update((state) => {
delete state.fragments[id];
});
}
}
/**
* Finalizes a fragment, tracking either a success event or failure Event
* and then removes the fragment from state.
*
* @param id - UUID of the event fragment to be closed
* @param options
* @param options.abandoned - if true track the failure event instead of the success event
* @param options.page - page the final event occurred on. This will override whatever is set on the fragment
* @param options.referrer - Dapp that originated the fragment. This is for fallback only, the fragment referrer
* property will take precedence.
*/
finalizeEventFragment(
id: string,
{
abandoned = false,
page,
referrer,
}: {
abandoned?: boolean;
page?: MetaMetricsPageObject;
referrer?: MetaMetricsReferrerObject;
} = {},
): void {
const fragment = this.state.fragments[id];
if (!fragment) {
throw new Error(`Funnel with id ${id} does not exist.`);
}
const eventName = abandoned ? fragment.failureEvent : fragment.successEvent;
this.trackEvent({
event: eventName ?? '',
category: fragment.category,
properties: fragment.properties,
sensitiveProperties: fragment.sensitiveProperties,
page: page ?? fragment.page,
referrer: fragment.referrer ?? referrer,
revenue: fragment.revenue,
value: fragment.value,
currency: fragment.currency,
environmentType: fragment.environmentType,
actionId: fragment.actionId,
// We append success or failure to the unique-identifier so that the
// messageId can still be idempotent, but so that it differs from the
// initial event fired. The initial event was preventing new events from
// making it to mixpanel because they were using the same unique ID as
// the events processed in other parts of the fragment lifecycle.
uniqueIdentifier: fragment.uniqueIdentifier
? `${fragment.uniqueIdentifier}-${abandoned ? 'failure' : 'success'}`
: undefined,
});
this.update((state) => {
delete state.fragments[id];
});
}
/**
* Calls this._identify with validated metaMetricsId and user traits if user is participating
* in the MetaMetrics analytics program
*
* @param userTraits
*/
identify(userTraits: Partial<MetaMetricsUserTraits>): void {
const { metaMetricsId, participateInMetaMetrics } = this.state;
if (!participateInMetaMetrics || !metaMetricsId || !userTraits) {
return;
}
if (typeof userTraits !== 'object') {
console.warn(
`MetaMetricsController#identify: userTraits parameter must be an object. Received type: ${typeof userTraits}`,
);
return;
}
const allValidTraits = this.#buildValidTraits(userTraits);
this.#identify(allValidTraits);
}
// It sets an uninstall URL ("Sorry to see you go!" page),
// which is opened if a user uninstalls the extension.
// This method should only be called after the user has made a decision about MetaMetrics participation.
updateExtensionUninstallUrl(
participateInMetaMetrics: boolean,
metaMetricsId: string,
): void {
const query: {
mmi?: string;
env?: string;
av: string;
} = {
av: this.version,
};
if (participateInMetaMetrics) {
// We only want to track these things if a user opted into metrics.
query.mmi = Buffer.from(metaMetricsId).toString('base64');
query.env = this.#environment;
}
const queryString = new URLSearchParams(query);
// this.extension not currently defined in tests
if (this.#extension && this.#extension.runtime) {
this.#extension.runtime.setUninstallURL(
// TODO: Fix in https://github.com/MetaMask/metamask-extension/issues/31893
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`${EXTENSION_UNINSTALL_URL}?${queryString}`,
);
}
}
/**
* Setter for the `participateInMetaMetrics` property
*
* @param participateInMetaMetrics - Whether or not the user wants to participate in MetaMetrics if not set
* @returns The string of the new metametrics id, or null
*/
async setParticipateInMetaMetrics(
participateInMetaMetrics: boolean | null,
): Promise<string | null> {
const { metaMetricsId: existingMetaMetricsId } = this.state;
const metaMetricsId =
participateInMetaMetrics && !existingMetaMetricsId
? this.generateMetaMetricsId()
: existingMetaMetricsId;
this.update((state) => {
state.participateInMetaMetrics = participateInMetaMetrics;
state.metaMetricsId = metaMetricsId;
});
if (participateInMetaMetrics) {
this.trackEventsAfterMetricsOptIn();
this.clearEventsAfterMetricsOptIn();
this.trackTracesAfterMetricsOptIn();
this.clearTracesAfterMetricsOptIn();
} else if (this.state.marketingCampaignCookieId) {
this.setMarketingCampaignCookieId(null);
}
///: BEGIN:ONLY_INCLUDE_IF(build-main)
if (
this.#environment !== ENVIRONMENT.DEVELOPMENT &&
metaMetricsId !== null &&
participateInMetaMetrics !== null
) {
this.updateExtensionUninstallUrl(participateInMetaMetrics, metaMetricsId);
}
///: END:ONLY_INCLUDE_IF
return metaMetricsId;
}
setDataCollectionForMarketing(
dataCollectionForMarketing: boolean,
): MetaMetricsControllerState['metaMetricsId'] {
const { metaMetricsId } = this.state;
this.update((state) => {
state.dataCollectionForMarketing = dataCollectionForMarketing;
});
if (!dataCollectionForMarketing && this.state.marketingCampaignCookieId) {
this.setMarketingCampaignCookieId(null);
}
return metaMetricsId;
}
setMarketingCampaignCookieId(marketingCampaignCookieId: string | null): void {
this.update((state) => {
state.marketingCampaignCookieId = marketingCampaignCookieId;
});
}
/**
* track a page view with Segment
*
* @param payload - details of the page viewed.
* @param options - options for handling the page view.
*/
trackPage(
payload: MetaMetricsPagePayload,
options?: MetaMetricsPageOptions,
): void {
try {
if (this.state.participateInMetaMetrics === false) {
return;
}
if (
this.state.participateInMetaMetrics === null &&
!options?.isOptInPath
) {
return;
}