-
-
Notifications
You must be signed in to change notification settings - Fork 287
Expand file tree
/
Copy pathNotificationServicesController.test.ts
More file actions
2126 lines (1846 loc) · 69.6 KB
/
Copy pathNotificationServicesController.test.ts
File metadata and controls
2126 lines (1846 loc) · 69.6 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 type {
AuthenticatedUserStorageServiceGetNotificationPreferencesAction,
AuthenticatedUserStorageServicePutNotificationPreferencesAction,
NotificationPreferences,
} from '@metamask/authenticated-user-storage';
import { deriveStateFromMetadata } from '@metamask/base-controller';
import * as ControllerUtils from '@metamask/controller-utils';
import { KeyringTypes } from '@metamask/keyring-controller';
import type {
KeyringControllerGetStateAction,
KeyringControllerState,
} from '@metamask/keyring-controller';
import { Messenger, MOCK_ANY_NAMESPACE } from '@metamask/messenger';
import type {
MessengerActions,
MessengerEvents,
MockAnyNamespace,
} from '@metamask/messenger';
import { AuthenticationController } from '@metamask/profile-sync-controller';
import log from 'loglevel';
import type nock from 'nock';
import type {
NotificationServicesPushControllerAddPushNotificationLinksAction,
NotificationServicesPushControllerDisablePushNotificationsAction,
NotificationServicesPushControllerDeletePushNotificationLinksAction,
NotificationServicesPushControllerEnablePushNotificationsAction,
NotificationServicesPushControllerSubscribeToPushNotificationsAction,
} from '../NotificationServicesPushController';
import { ADDRESS_1, ADDRESS_2, ADDRESS_3 } from './__fixtures__/mockAddresses';
import {
mockGetOnChainNotificationsConfig,
mockGetAPINotifications,
mockFetchFeatureAnnouncementNotifications,
mockMarkNotificationsAsRead,
mockCreatePerpNotification,
} from './__fixtures__/mockServices';
import { waitFor } from './__fixtures__/test-utils';
import { TRIGGER_TYPES } from './constants';
import { createMockSnapNotification } from './mocks';
import {
createMockFeatureAnnouncementAPIResult,
createMockFeatureAnnouncementRaw,
} from './mocks/mock-feature-announcements';
import { createMockNotificationEthSent } from './mocks/mock-raw-notifications';
import {
DEFAULT_PERPS_PREFERENCES,
DEFAULT_SOCIAL_AI_PREFERENCES,
NotificationServicesController,
ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS,
defaultState,
} from './NotificationServicesController';
import type {
NotificationServicesControllerMessenger,
NotificationServicesControllerState,
} from './NotificationServicesController';
import { processFeatureAnnouncement } from './processors';
import { processNotification } from './processors/process-notifications';
import { processSnapNotification } from './processors/process-snap-notifications';
import { notificationsConfigCache } from './services/notification-config-cache';
import type { INotification, OrderInput } from './types';
// Mock type used for testing purposes
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type MockVar = any;
const featureAnnouncementsEnv = {
spaceId: ':space_id',
accessToken: ':access_token',
platform: 'extension' as const,
};
// Testing util to clean up verbose logs when testing errors
const mockErrorLog = (): jest.SpyInstance =>
jest.spyOn(log, 'error').mockImplementation(jest.fn());
const mockWarnLog = (): jest.SpyInstance =>
jest.spyOn(log, 'warn').mockImplementation(jest.fn());
// Removing caches to avoid interference
const clearAPICache = (): void => {
notificationsConfigCache.clear();
};
const prefsFromAddresses = (
accounts: { address: string; enabled: boolean }[],
): NotificationPreferences => ({
walletActivity: {
inAppNotificationsEnabled: true,
pushNotificationsEnabled: true,
accounts: accounts.map((a) => ({
address: a.address.toLowerCase() as `0x${string}`,
enabled: a.enabled,
})),
},
marketing: {
inAppNotificationsEnabled: false,
pushNotificationsEnabled: false,
},
perps: {
inAppNotificationsEnabled: true,
pushNotificationsEnabled: true,
},
socialAI: {
inAppNotificationsEnabled: true,
pushNotificationsEnabled: true,
mutedTraderProfileIds: [],
},
});
describe('NotificationServicesController', () => {
afterEach(() => {
clearAPICache();
});
describe('constructor', () => {
it('initializes state & override state', () => {
const controller1 = new NotificationServicesController({
messenger: mockNotificationMessenger().messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
expect(controller1.state).toStrictEqual(defaultState);
const controller2 = new NotificationServicesController({
messenger: mockNotificationMessenger().messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
state: {
...defaultState,
isFeatureAnnouncementsEnabled: true,
isNotificationServicesEnabled: true,
},
});
expect(controller2.state.isFeatureAnnouncementsEnabled).toBe(true);
expect(controller2.state.isNotificationServicesEnabled).toBe(true);
});
});
describe('init', () => {
const arrangeMocks = (): ReturnType<typeof mockNotificationMessenger> => {
const messengerMocks = mockNotificationMessenger();
jest
.spyOn(ControllerUtils, 'toChecksumHexAddress')
.mockImplementation((address) => address);
return messengerMocks;
};
const actPublishKeyringStateChange = async (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
messenger: any,
accounts: string[] = ['0x111', '0x222'],
): Promise<void> => {
messenger.publish(
'KeyringController:stateChange',
{
keyrings: [{ accounts }],
} as KeyringControllerState,
[],
);
};
describe('KeyringController:stateChange (debounced)', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
const arrangeActAssertKeyringTest = async (
controllerState?: Partial<NotificationServicesControllerState>,
): Promise<{
act: (addresses: string[], assertion: () => void) => Promise<void>;
actMultiple: (
addressesEvents: string[][],
assertion: () => void,
) => Promise<void>;
mockEnable: jest.SpyInstance;
mockDisable: jest.SpyInstance;
}> => {
const mocks = arrangeMocks();
const { messenger, globalMessenger, mockKeyringControllerGetState } =
mocks;
mockKeyringControllerGetState.mockReturnValue({
isUnlocked: true,
keyrings: [
{
accounts: [],
type: KeyringTypes.hd,
metadata: {
id: '123',
name: '',
},
},
],
});
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
state: {
isNotificationServicesEnabled: true,
subscriptionAccountsSeen: [],
...controllerState,
},
});
controller.init();
await jest.advanceTimersByTimeAsync(ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS);
const mockEnable = jest
.spyOn(controller, 'enableAccounts')
.mockResolvedValue();
const mockDisable = jest
.spyOn(controller, 'disableAccounts')
.mockResolvedValue();
const mockKeyringState = (addresses: string[]): void => {
mockKeyringControllerGetState.mockReturnValue({
isUnlocked: true,
keyrings: [
{
accounts: addresses,
type: KeyringTypes.hd,
},
],
});
};
const cleanup = (): void => {
mockEnable.mockClear();
mockDisable.mockClear();
};
const act = async (
addresses: string[],
assertion: () => void,
): Promise<void> => {
mockKeyringState(addresses);
await actPublishKeyringStateChange(globalMessenger, addresses);
await jest.advanceTimersByTimeAsync(ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS);
assertion();
// Cleanup mocks for next act/assert
cleanup();
};
const actMultiple = async (
addressesEvents: string[][],
assertion: () => void,
): Promise<void> => {
for (const addresses of addressesEvents) {
mockKeyringState(addresses);
await actPublishKeyringStateChange(globalMessenger, addresses);
}
await jest.advanceTimersByTimeAsync(ACCOUNTS_UPDATE_DEBOUNCE_TIME_MS);
assertion();
// Cleanup mocks for next act/assert
cleanup();
};
return { act, actMultiple, mockEnable, mockDisable };
};
it('event KeyringController:stateChange will not add or remove triggers when feature is disabled', async () => {
const { act, mockEnable, mockDisable } =
await arrangeActAssertKeyringTest({
isNotificationServicesEnabled: false,
});
// listAccounts has a new address
await act([ADDRESS_1, ADDRESS_2], () => {
expect(mockEnable).not.toHaveBeenCalled();
expect(mockDisable).not.toHaveBeenCalled();
});
});
it('event KeyringController:stateChange will update notification triggers when keyring accounts change', async () => {
const { act, mockEnable, mockDisable } =
await arrangeActAssertKeyringTest({
subscriptionAccountsSeen: [ADDRESS_1],
});
// Act - if list accounts has been seen, then will not update
await act([ADDRESS_1], () => {
expect(mockEnable).not.toHaveBeenCalled();
expect(mockDisable).not.toHaveBeenCalled();
});
// Act - if a new address in list, then will update
await act([ADDRESS_1, ADDRESS_2], () => {
expect(mockEnable).toHaveBeenCalled();
expect(mockDisable).not.toHaveBeenCalled();
});
// Act - if the list doesn't have an address, then we need to delete
await act([ADDRESS_2], () => {
expect(mockEnable).not.toHaveBeenCalled();
expect(mockDisable).toHaveBeenCalled();
});
// If the address is added back to the list, we will perform an update
await act([ADDRESS_1, ADDRESS_2], () => {
expect(mockEnable).toHaveBeenCalled();
expect(mockDisable).not.toHaveBeenCalled();
});
});
it('event KeyringController:stateChange will update only once when if the number of keyring accounts do not change', async () => {
const { act, mockEnable, mockDisable } =
await arrangeActAssertKeyringTest();
// Act - First list of items, so will update
await act([ADDRESS_1, ADDRESS_2], () => {
expect(mockEnable).toHaveBeenCalled();
expect(mockDisable).not.toHaveBeenCalled();
});
// Act - Since number of addresses in keyring has not changed, will not update
await act([ADDRESS_1, ADDRESS_2], () => {
expect(mockEnable).not.toHaveBeenCalled();
expect(mockDisable).not.toHaveBeenCalled();
});
});
it('event KeyringController:stateChange will only update notifications once when the number of keyring accounts changes multiple times', async () => {
const { actMultiple, mockEnable, mockDisable } =
await arrangeActAssertKeyringTest();
await actMultiple(
[
// Event 1
[ADDRESS_1],
// Event 2
[ADDRESS_1, ADDRESS_2],
// Event 3
[ADDRESS_1, ADDRESS_2, ADDRESS_3],
],
() => {
expect(mockEnable).toHaveBeenCalledTimes(1);
expect(mockEnable).toHaveBeenCalledWith([
ADDRESS_1,
ADDRESS_2,
ADDRESS_3,
]);
expect(mockDisable).not.toHaveBeenCalled();
},
);
});
});
const arrangeActInitialisePushNotifications = (
modifications?: (mocks: ReturnType<typeof arrangeMocks>) => void,
): ReturnType<typeof arrangeMocks> & {
mockAPIGetNotificationConfig: jest.Mock;
} => {
// Arrange
const mocks = arrangeMocks();
const mockAPIGetNotificationConfig = mocks.mockGetNotificationPreferences;
modifications?.(mocks);
// Act
const controller = new NotificationServicesController({
messenger: mocks.messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
state: { isNotificationServicesEnabled: true },
});
controller.init();
return { ...mocks, mockAPIGetNotificationConfig };
};
it('initialises push notifications', async () => {
const { mockEnablePushNotifications } =
arrangeActInitialisePushNotifications();
await waitFor(() => {
expect(mockEnablePushNotifications).toHaveBeenCalled();
});
});
it('does not initialise push notifications if the wallet is locked', async () => {
const { mockEnablePushNotifications, mockSubscribeToPushNotifications } =
arrangeActInitialisePushNotifications((mocks) => {
mocks.mockKeyringControllerGetState.mockReturnValue({
isUnlocked: false, // Wallet Locked
} as MockVar);
});
await waitFor(() => {
expect(mockEnablePushNotifications).not.toHaveBeenCalled();
});
await waitFor(() => {
expect(mockSubscribeToPushNotifications).toHaveBeenCalled();
});
});
it('should re-initialise push notifications if wallet was locked, and then is unlocked', async () => {
// Test Wallet Lock
const {
globalMessenger,
mockEnablePushNotifications,
mockSubscribeToPushNotifications,
mockKeyringControllerGetState,
} = arrangeActInitialisePushNotifications((mocks) => {
mocks.mockKeyringControllerGetState.mockReturnValue({
isUnlocked: false, // Wallet Locked
keyrings: [],
});
});
await waitFor(() => {
expect(mockEnablePushNotifications).not.toHaveBeenCalled();
});
await waitFor(() => {
expect(mockSubscribeToPushNotifications).toHaveBeenCalled();
});
// Test Wallet Unlock
jest.clearAllMocks();
mockKeyringControllerGetState.mockReturnValue({
isUnlocked: true,
keyrings: [
{
accounts: ['0xde55a0F2591d7823486e211710f53dADdb173Cee'],
type: KeyringTypes.hd,
},
] as MockVar,
});
globalMessenger.publish('KeyringController:unlock');
await waitFor(() => {
expect(mockEnablePushNotifications).toHaveBeenCalled();
});
await waitFor(() => {
expect(mockSubscribeToPushNotifications).not.toHaveBeenCalled();
});
});
});
// See /utils for more in-depth testing
describe('checkAccountsPresence', () => {
it('returns Record with accounts that have notifications enabled', async () => {
const mocks = mockNotificationMessenger();
mocks.mockGetNotificationPreferences.mockResolvedValueOnce(
prefsFromAddresses([
{ address: ADDRESS_1, enabled: true },
{ address: ADDRESS_2, enabled: false },
]),
);
const controller = new NotificationServicesController({
messenger: mocks.messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
const result = await controller.checkAccountsPresence([
ADDRESS_1,
ADDRESS_2,
]);
expect(mocks.mockGetNotificationPreferences).toHaveBeenCalled();
expect(result).toStrictEqual({
[ADDRESS_1]: true,
[ADDRESS_2]: false,
});
});
});
describe('setFeatureAnnouncementsEnabled', () => {
it('flips state when the method is called', async () => {
const { messenger, mockIsSignedIn } = mockNotificationMessenger();
mockIsSignedIn.mockReturnValue(true);
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
state: { ...defaultState, isFeatureAnnouncementsEnabled: false },
});
await controller.setFeatureAnnouncementsEnabled(true);
expect(controller.state.isFeatureAnnouncementsEnabled).toBe(true);
});
});
describe('createOnChainTriggers', () => {
const arrangeMocks = (overrides?: {
configurePrefs?: (mock: jest.Mock) => void;
}): ReturnType<typeof mockNotificationMessenger> & {
mockGetConfig: jest.Mock;
mockUpdateNotifications: jest.Mock;
} => {
const messengerMocks = mockNotificationMessenger();
const mockGetConfig = messengerMocks.mockGetNotificationPreferences;
const mockUpdateNotifications =
messengerMocks.mockPutNotificationPreferences;
overrides?.configurePrefs?.(mockGetConfig);
return {
...messengerMocks,
mockGetConfig,
mockUpdateNotifications,
};
};
describe('when AUS preferences are not initialized (preferences are null)', () => {
it('writes a fresh preferences blob using hardcoded defaults, current Trigger API wallet account state, and supplied marketing flags', async () => {
const {
messenger,
mockEnablePushNotifications,
mockGetConfig,
mockUpdateNotifications,
mockKeyringControllerGetState,
} = arrangeMocks({
configurePrefs: (mock) => mock.mockResolvedValueOnce(null),
});
mockKeyringControllerGetState.mockReturnValue({
isUnlocked: true,
keyrings: [
{
accounts: [ADDRESS_1, ADDRESS_2],
type: KeyringTypes.hd,
metadata: { id: 'srp-1', name: 'SRP 1' },
},
],
});
const mockTriggerQuery = mockGetOnChainNotificationsConfig({
status: 200,
body: [
{ address: ADDRESS_1.toLowerCase(), enabled: true },
{ address: ADDRESS_2.toLowerCase(), enabled: false },
],
});
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
await controller.createOnChainTriggers({
hasMarketingConsent: true,
productAnnouncementEnabled: false,
});
expect(mockGetConfig).toHaveBeenCalled();
expect(mockTriggerQuery.isDone()).toBe(true);
expect(mockUpdateNotifications).toHaveBeenCalledTimes(1);
const [writtenPrefs, writtenPlatform] =
mockUpdateNotifications.mock.calls[0];
expect(writtenPlatform).toBe(featureAnnouncementsEnv.platform);
expect(writtenPrefs).toStrictEqual({
walletActivity: {
inAppNotificationsEnabled: true,
pushNotificationsEnabled: true,
accounts: [
{
address: ADDRESS_1.toLowerCase(),
enabled: true,
},
{
address: ADDRESS_2.toLowerCase(),
enabled: false,
},
],
},
marketing: {
inAppNotificationsEnabled: false,
pushNotificationsEnabled: true,
},
perps: { ...DEFAULT_PERPS_PREFERENCES },
socialAI: { ...DEFAULT_SOCIAL_AI_PREFERENCES },
});
expect(mockEnablePushNotifications).toHaveBeenCalledWith([
ADDRESS_1.toLowerCase(),
]);
});
it('skips push registration when registerPushNotifications is false', async () => {
const {
messenger,
mockEnablePushNotifications,
mockGetConfig,
mockUpdateNotifications,
mockKeyringControllerGetState,
} = arrangeMocks({
configurePrefs: (mock) => mock.mockResolvedValueOnce(null),
});
mockKeyringControllerGetState.mockReturnValue({
isUnlocked: true,
keyrings: [
{
accounts: [ADDRESS_1],
type: KeyringTypes.hd,
metadata: { id: 'srp-1', name: 'SRP 1' },
},
],
});
const mockTriggerQuery = mockGetOnChainNotificationsConfig();
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
await controller.createOnChainTriggers({
registerPushNotifications: false,
});
expect(mockGetConfig).toHaveBeenCalled();
expect(mockTriggerQuery.isDone()).toBe(true);
expect(mockUpdateNotifications).toHaveBeenCalled();
expect(controller.state.isNotificationServicesEnabled).toBe(true);
expect(mockEnablePushNotifications).not.toHaveBeenCalled();
});
it('enables all wallet-activity accounts when Trigger API has no enabled accounts for first-time setup', async () => {
const {
messenger,
mockEnablePushNotifications,
mockUpdateNotifications,
mockKeyringControllerGetState,
} = arrangeMocks({
configurePrefs: (mock) => mock.mockResolvedValueOnce(null),
});
mockKeyringControllerGetState.mockReturnValue({
isUnlocked: true,
keyrings: [
{
accounts: [ADDRESS_1, ADDRESS_2],
type: KeyringTypes.hd,
metadata: { id: 'srp-1', name: 'SRP 1' },
},
],
});
const mockTriggerQuery = mockGetOnChainNotificationsConfig({
status: 200,
body: [
{ address: ADDRESS_1.toLowerCase(), enabled: false },
{ address: ADDRESS_2.toLowerCase(), enabled: false },
],
});
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
await controller.createOnChainTriggers();
expect(mockTriggerQuery.isDone()).toBe(true);
const [writtenPrefs] = mockUpdateNotifications.mock.calls[0];
expect(writtenPrefs.walletActivity.accounts).toStrictEqual([
{ address: ADDRESS_1.toLowerCase(), enabled: true },
{ address: ADDRESS_2.toLowerCase(), enabled: true },
]);
expect(mockEnablePushNotifications).toHaveBeenCalledWith([
ADDRESS_1.toLowerCase(),
ADDRESS_2.toLowerCase(),
]);
});
it('defaults marketing notifications to disabled when no consent is supplied', async () => {
const { messenger, mockUpdateNotifications } = arrangeMocks({
configurePrefs: (mock) => mock.mockResolvedValueOnce(null),
});
mockGetOnChainNotificationsConfig();
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
await controller.createOnChainTriggers();
const [writtenPrefs] = mockUpdateNotifications.mock.calls[0];
expect(writtenPrefs.marketing).toStrictEqual({
inAppNotificationsEnabled: false,
pushNotificationsEnabled: false,
});
});
it('enables marketing in-app notifications when product announcements are enabled', async () => {
const { messenger, mockUpdateNotifications } = arrangeMocks({
configurePrefs: (mock) => mock.mockResolvedValueOnce(null),
});
mockGetOnChainNotificationsConfig();
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
await controller.createOnChainTriggers({
productAnnouncementEnabled: true,
});
const [writtenPrefs] = mockUpdateNotifications.mock.calls[0];
expect(writtenPrefs.marketing).toStrictEqual({
inAppNotificationsEnabled: true,
pushNotificationsEnabled: false,
});
});
it('tracks accounts from all keyrings when creating triggers', async () => {
const {
messenger,
mockGetConfig,
mockUpdateNotifications,
mockKeyringControllerGetState,
} = arrangeMocks({
configurePrefs: (mock) => mock.mockResolvedValueOnce(null),
});
mockKeyringControllerGetState.mockReturnValue({
isUnlocked: true,
keyrings: [
{
accounts: [ADDRESS_1],
type: KeyringTypes.hd,
metadata: { id: 'srp-1', name: 'SRP 1' },
},
{
accounts: [ADDRESS_2],
type: KeyringTypes.hd,
metadata: { id: 'srp-2', name: 'SRP 2' },
},
],
});
const mockTriggerQuery = mockGetOnChainNotificationsConfig({
status: 200,
body: [
{ address: ADDRESS_1.toLowerCase(), enabled: true },
{ address: ADDRESS_2.toLowerCase(), enabled: true },
],
});
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
await controller.createOnChainTriggers();
expect(mockGetConfig).toHaveBeenCalled();
expect(mockTriggerQuery.isDone()).toBe(true);
expect(mockUpdateNotifications).toHaveBeenCalled();
expect(controller.state.subscriptionAccountsSeen).toStrictEqual([
ADDRESS_1,
ADDRESS_2,
]);
});
it('deduplicates and filters non-Ethereum accounts when creating triggers', async () => {
const {
messenger,
mockGetConfig,
mockUpdateNotifications,
mockKeyringControllerGetState,
} = arrangeMocks({
configurePrefs: (mock) => mock.mockResolvedValueOnce(null),
});
mockKeyringControllerGetState.mockReturnValue({
isUnlocked: true,
keyrings: [
{
accounts: [ADDRESS_1, ADDRESS_1.toLowerCase(), 'NotAnAddress'],
type: KeyringTypes.hd,
metadata: { id: 'srp-1', name: 'SRP 1' },
},
{
accounts: [
ADDRESS_2,
'7xKXtg2CW6y7J2wMmkf8VbM8dYb6u3H3V8bLxT64d4oR',
],
type: KeyringTypes.hd,
metadata: { id: 'srp-2', name: 'SRP 2' },
},
],
});
const mockTriggerQuery = mockGetOnChainNotificationsConfig({
status: 200,
body: [
{ address: ADDRESS_1.toLowerCase(), enabled: true },
{ address: ADDRESS_2.toLowerCase(), enabled: true },
],
});
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
await controller.createOnChainTriggers();
expect(mockGetConfig).toHaveBeenCalled();
expect(mockTriggerQuery.isDone()).toBe(true);
expect(mockUpdateNotifications).toHaveBeenCalled();
expect(controller.state.subscriptionAccountsSeen).toStrictEqual([
ADDRESS_1,
ADDRESS_2,
]);
});
it('normalizes non-checksummed mixed-case addresses before filtering', async () => {
const {
messenger,
mockGetConfig,
mockUpdateNotifications,
mockKeyringControllerGetState,
} = arrangeMocks({
configurePrefs: (mock) => mock.mockResolvedValueOnce(null),
});
const nonChecksummedMixedCaseAddress =
'0xd8Da6bf26964af9d7eeD9e03E53415D37aa96045';
mockKeyringControllerGetState.mockReturnValue({
isUnlocked: true,
keyrings: [
{
accounts: [nonChecksummedMixedCaseAddress],
type: KeyringTypes.hd,
metadata: { id: 'srp-1', name: 'SRP 1' },
},
],
});
const mockTriggerQuery = mockGetOnChainNotificationsConfig({
status: 200,
body: [{ address: ADDRESS_1.toLowerCase(), enabled: true }],
});
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
await controller.createOnChainTriggers();
expect(mockGetConfig).toHaveBeenCalled();
expect(mockTriggerQuery.isDone()).toBe(true);
expect(mockUpdateNotifications).toHaveBeenCalled();
expect(controller.state.subscriptionAccountsSeen).toStrictEqual([
ADDRESS_1,
]);
});
});
describe('when AUS preferences are fully initialized', () => {
it('does not register notifications when notifications already exist and not resetting (however does update push registrations)', async () => {
const {
messenger,
mockEnablePushNotifications,
mockGetConfig,
mockUpdateNotifications,
} = arrangeMocks({
configurePrefs: (mock) =>
mock.mockResolvedValueOnce(
prefsFromAddresses([{ address: ADDRESS_1, enabled: true }]),
),
});
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
await controller.createOnChainTriggers();
expect(mockGetConfig).toHaveBeenCalled();
expect(mockUpdateNotifications).not.toHaveBeenCalled();
expect(mockEnablePushNotifications).toHaveBeenCalled();
});
it('preserves user preferences when re-subscribing using enableMetamaskNotifications', async () => {
const {
messenger,
mockEnablePushNotifications,
mockGetConfig,
mockUpdateNotifications,
} = arrangeMocks({
configurePrefs: (mock) =>
mock.mockResolvedValueOnce(
prefsFromAddresses([{ address: ADDRESS_1, enabled: true }]),
),
});
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
state: {
isNotificationServicesEnabled: true,
isFeatureAnnouncementsEnabled: false,
},
});
await controller.enableMetamaskNotifications();
expect(controller.state.isFeatureAnnouncementsEnabled).toBe(false);
expect(controller.state.isNotificationServicesEnabled).toBe(true);
expect(mockGetConfig).toHaveBeenCalled();
expect(mockUpdateNotifications).not.toHaveBeenCalled();
expect(mockEnablePushNotifications).toHaveBeenCalled();
});
});
it('throws if not given a valid auth & bearer token', async () => {
const mocks = arrangeMocks();
mockErrorLog();
const controller = new NotificationServicesController({
messenger: mocks.messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
const testScenarios = {
...arrangeFailureAuthAssertions(mocks),
};
for (const mockFailureAction of Object.values(testScenarios)) {
mockFailureAction();
await expect(controller.createOnChainTriggers()).rejects.toThrow(
expect.any(Error),
);
}
});
});
describe('disableAccounts', () => {
const arrangeMocks = (): ReturnType<typeof mockNotificationMessenger> & {
mockUpdateNotifications: jest.Mock;
} => {
const messengerMocks = mockNotificationMessenger();
const mockUpdateNotifications =
messengerMocks.mockPutNotificationPreferences;
return { ...messengerMocks, mockUpdateNotifications };
};
it('disables notifications for given accounts', async () => {
const {
messenger,
mockUpdateNotifications,
mockDeletePushNotificationLinks,
} = arrangeMocks();
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
await controller.disableAccounts([ADDRESS_1]);
expect(mockUpdateNotifications).toHaveBeenCalled();
expect(mockDeletePushNotificationLinks).toHaveBeenCalledWith([ADDRESS_1]);
});
it('throws errors when invalid auth', async () => {
const mocks = arrangeMocks();
mockErrorLog();
const controller = new NotificationServicesController({
messenger: mocks.messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },
});
const testScenarios = {
...arrangeFailureAuthAssertions(mocks),
};
for (const mockFailureAction of Object.values(testScenarios)) {
mockFailureAction();
await expect(controller.disableAccounts([ADDRESS_1])).rejects.toThrow(
expect.any(Error),
);
}
});
});
describe('enableAccounts', () => {
const arrangeMocks = (): ReturnType<typeof mockNotificationMessenger> & {
mockUpdateNotifications: jest.Mock;
} => {
const messengerMocks = mockNotificationMessenger();
const mockUpdateNotifications =
messengerMocks.mockPutNotificationPreferences;
return { ...messengerMocks, mockUpdateNotifications };
};
it('enables notifications for given accounts', async () => {
const {
messenger,
mockAddPushNotificationLinks,
mockUpdateNotifications,
} = arrangeMocks();
const controller = new NotificationServicesController({
messenger,
env: { featureAnnouncements: featureAnnouncementsEnv },