-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathindex.tsx
More file actions
1147 lines (1063 loc) · 38.1 KB
/
index.tsx
File metadata and controls
1147 lines (1063 loc) · 38.1 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 React, {
useState,
useEffect,
useMemo,
useRef,
useCallback,
useContext,
} from 'react';
import {
ActivityIndicator,
BackHandler,
ScrollView,
InteractionManager,
Animated,
Easing,
Platform,
} from 'react-native';
import { captureException } from '@sentry/react-native';
import { colors as importedColors } from '../../../styles/common';
import { strings } from '../../../../locales/i18n';
import { useSelector, useDispatch } from 'react-redux';
import FadeOutOverlay from '../../UI/FadeOutOverlay';
import Device from '../../../util/device';
import BaseNotification from '../../UI/Notification/BaseNotification';
import ElevatedView from 'react-native-elevated-view';
import { loadingSet, loadingUnset } from '../../../actions/user';
import {
saveOnboardingEvent as saveEvent,
setAccountType,
clearSeedlessOnboarding,
setIosGoogleWarningSheetLastDismissedAt,
} from '../../../actions/onboarding';
import {
AccountType,
getSocialAccountType,
} from '../../../constants/onboarding';
import {
storePrivacyPolicyClickedOrClosed as storePrivacyPolicyClickedOrClosedAction,
storePna25Acknowledged as storePna25AcknowledgedAction,
} from '../../../actions/legalNotices';
import { selectGoogleLoginIosUnsupportedBlockingEnabled } from '../../../selectors/featureFlagController/googleLoginIosUnsupportedBlocking';
import PreventScreenshot from '../../../core/PreventScreenshot';
import { PREVIOUS_SCREEN, ONBOARDING } from '../../../constants/navigation';
import { MetaMetricsEvents } from '../../../core/Analytics';
import { Authentication } from '../../../core';
import { getVaultFromBackup } from '../../../core/BackupVault';
import Logger from '../../../util/Logger';
import FilesystemStorage from 'redux-persist-filesystem-storage';
import { MIGRATION_ERROR_HAPPENED } from '../../../constants/storage';
import {
markMetricsOptInUISeen,
resetMetricsOptInUISeen,
} from '../../../util/metrics/metricsOptInUIUtils';
import { ThemeContext } from '../../../util/theme';
import { isE2E } from '../../../util/test/utils';
import { OnboardingSelectorIDs } from './Onboarding.testIds';
import Routes from '../../../constants/navigation/Routes';
import { selectExistingUser } from '../../../reducers/user/selectors';
import trackOnboarding from '../../../util/metrics/TrackOnboarding/trackOnboarding';
import { fetch as netInfoFetch } from '@react-native-community/netinfo';
import {
useNavigation,
useRoute,
RouteProp,
StackActions,
} from '@react-navigation/native';
import {
TraceName,
TraceOperation,
TraceContext,
endTrace,
trace,
hasMetricsConsent,
discardBufferedTraces,
} from '../../../util/trace';
import { getTraceTags } from '../../../util/sentry/tags';
import { store } from '../../../store';
import type { RootState } from '../../../reducers';
import { MetricsEventBuilder } from '../../../core/Analytics/MetricsEventBuilder';
import {
IMetaMetricsEvent,
ITrackingEvent,
} from '../../../core/Analytics/MetaMetrics.types';
import { JsonMap } from '@segment/analytics-react-native';
import { SEEDLESS_ONBOARDING_ENABLED } from '../../../core/OAuthService/OAuthLoginHandlers/constants';
import OAuthLoginService from '../../../core/OAuthService/OAuthService';
import { OAuthError, OAuthErrorType } from '../../../core/OAuthService/error';
import { createLoginHandler } from '../../../core/OAuthService/OAuthLoginHandlers';
import { AuthConnection } from '../../../core/OAuthService/OAuthInterface';
import { useAnalytics } from '../../hooks/useAnalytics/useAnalytics';
import { setupSentry } from '../../../util/sentry/utils';
import ErrorBoundary from '../ErrorBoundary';
import FastOnboarding from './FastOnboarding';
import {
presentIosGoogleLoginUnsupportedBlockingSheet,
presentIosGoogleLoginUnsupportedBlockingSheetRehydration,
presentIosGoogleLoginVersionWarningSheet,
} from './OnboardingIosPrompt';
import { SafeAreaView } from 'react-native-safe-area-context';
import { getWalletSetupCompletedAttributionProperties } from '../../../util/analytics/getWalletSetupCompletedAttributionProperties';
import FoxAnimation from '../../UI/FoxAnimation/FoxAnimation';
import OnboardingAnimation from '../../UI/OnboardingAnimation/OnboardingAnimation';
import {
Box,
BoxAlignItems,
BoxJustifyContent,
Button,
ButtonSize,
ButtonVariant,
Text,
TextVariant,
} from '@metamask/design-system-react-native';
import {
Theme,
ThemeProvider,
useTailwind,
} from '@metamask/design-system-twrnc-preset';
import { getBuildNumber, getVersion } from 'react-native-device-info';
import { AppNavigationProp } from '../../../core/NavigationService/types';
interface OnboardingState {
warningModalVisible: boolean;
loading: boolean;
existingUser: boolean;
createWallet: boolean;
existingWallet: boolean;
errorSheetVisible: boolean;
errorToThrow: Error | null;
startOnboardingAnimation: boolean;
startFoxAnimation: 'Start' | 'Loader' | undefined;
}
interface OAuthLoginResult {
type: 'success' | 'error';
existingUser: boolean;
accountName?: string;
error?: Error;
}
interface OnboardingRouteParams {
[PREVIOUS_SCREEN]: string;
delete_wallet_toast_visible?: boolean;
delete?: string;
showErrorReportSentToast?: boolean;
}
const Onboarding = () => {
const navigation = useNavigation<AppNavigationProp>();
const onboardingVersion = useMemo(
() => `${getVersion()} (${getBuildNumber()})`,
[],
);
const route =
useRoute<RouteProp<{ params: OnboardingRouteParams }, 'params'>>();
const dispatch = useDispatch();
const metrics = useAnalytics();
const passwordSet = useSelector((state: RootState) => state.user.passwordSet);
const existingUserProp = useSelector(selectExistingUser);
const loading = useSelector((state: RootState) => state.user.loadingSet);
const loadingMsg = useSelector(
(state: RootState) => state.user.loadingMsg || '',
);
const isGoogleLoginIosUnsupportedBlockingEnabled = useSelector(
selectGoogleLoginIosUnsupportedBlockingEnabled,
);
const setLoading = useCallback(
(msg?: string) => dispatch(loadingSet(msg || '')),
[dispatch],
);
const unsetLoading = useCallback(() => dispatch(loadingUnset()), [dispatch]);
const disableNewPrivacyPolicyToast = useCallback(
() => dispatch(storePrivacyPolicyClickedOrClosedAction()),
[dispatch],
);
const saveOnboardingEvent = useCallback(
(...eventArgs: [ITrackingEvent]) => dispatch(saveEvent(eventArgs)),
[dispatch],
);
const storePna25Acknowledged = useCallback(
() => dispatch(storePna25AcknowledgedAction()),
[dispatch],
);
const themeContext = useContext(ThemeContext);
const tw = useTailwind();
const [state, setState] = useState<OnboardingState>({
warningModalVisible: false,
loading: false,
existingUser: false,
createWallet: false,
existingWallet: false,
errorSheetVisible: false,
errorToThrow: null,
startOnboardingAnimation: false,
startFoxAnimation: undefined,
});
const notificationAnimated = useRef(new Animated.Value(100)).current;
const onboardingTraceCtx = useRef<TraceContext>(undefined);
const socialLoginTraceCtx = useRef<TraceContext>(undefined);
const mounted = useRef<boolean>(false);
const hasCheckedVaultBackup = useRef<boolean>(false);
const warningCallback = useRef<() => boolean>(() => true);
const notificationTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const animatedTimingStart = useCallback(
(animatedRef: Animated.Value, toValue: number): void => {
Animated.timing(animatedRef, {
toValue,
duration: 500,
easing: Easing.linear,
useNativeDriver: true,
}).start();
},
[],
);
const disableBackPress = useCallback((): void => {
// Disable back press
const hardwareBackPress = () => true;
BackHandler.addEventListener('hardwareBackPress', hardwareBackPress);
}, []);
const showNotification = useCallback((): void => {
animatedTimingStart(notificationAnimated, 0);
notificationTimer.current = setTimeout(() => {
animatedTimingStart(notificationAnimated, 200);
}, 4000);
disableBackPress();
}, [animatedTimingStart, notificationAnimated, disableBackPress]);
const updateNavBar = useCallback((): void => {
navigation.setOptions({
headerShown: false,
});
}, [navigation]);
const checkIfExistingUser = useCallback(async (): Promise<void> => {
// Read from Redux state instead of MMKV storage
if (existingUserProp) {
setState((prevState) => ({ ...prevState, existingUser: true }));
}
}, [existingUserProp]);
const toggleWarningModal = useCallback((): void => {
setState((prevState) => ({
...prevState,
warningModalVisible: !prevState.warningModalVisible,
}));
}, []);
const alertExistingUser = useCallback(
(callback: () => void | Promise<void>): void => {
warningCallback.current = () => {
Promise.resolve(callback()).catch((error) => {
console.error('alertExistingUser callback failed:', error);
});
toggleWarningModal();
return true;
};
toggleWarningModal();
},
[toggleWarningModal],
);
/**
* Check for migration failure scenario and vault backup availability
* This detects when a migration has failed and left the user with a corrupted state
* but a valid vault backup still exists in the secure keychain
*/
const checkForMigrationFailureAndVaultBackup =
useCallback(async (): Promise<void> => {
// Prevent multiple checks - only run once per instance
if (hasCheckedVaultBackup.current) {
return;
}
hasCheckedVaultBackup.current = true;
// Skip check in E2E test environment
// E2E tests start with fresh state but may have vault backups from fixtures/previous runs
// This would trigger false positive vault recovery redirects and break onboarding tests
if (isE2E) {
return;
}
// Skip check if this is an intentional wallet reset
// (route.params.delete is set when user explicitly resets their wallet)
if (route?.params?.delete) {
return;
}
try {
// Check for migration error flag
// Using FilesystemStorage (excluded from iCloud backup) for reliability
const migrationErrorFlag = await FilesystemStorage.getItem(
MIGRATION_ERROR_HAPPENED,
);
if (migrationErrorFlag === 'true') {
// Migration failed, check if vault backup exists
const vaultBackupResult = await getVaultFromBackup();
if (vaultBackupResult.success && vaultBackupResult.vault) {
// Both migration error and vault backup exist - trigger recovery
navigation.reset({
routes: [{ name: Routes.VAULT_RECOVERY.RESTORE_WALLET }],
});
}
}
} catch (error) {
Logger.error(
error as Error,
'Failed to check for migration failure and vault backup',
);
}
}, [navigation, route]);
const handleExistingUser = useCallback(
async (action: () => void | Promise<void>): Promise<void> => {
if (state.existingUser) {
alertExistingUser(action);
} else {
await action();
}
},
[state.existingUser, alertExistingUser],
);
const track = useCallback(
(event: IMetaMetricsEvent, properties: JsonMap = {}): void => {
trackOnboarding(
MetricsEventBuilder.createEventBuilder(event)
.addProperties(properties)
.build(),
saveOnboardingEvent,
);
},
[saveOnboardingEvent],
);
const onPressCreate = useCallback(async (): Promise<void> => {
if (SEEDLESS_ONBOARDING_ENABLED) {
OAuthLoginService.resetOauthState();
}
// Reset metrics opt-in UI flag so the user sees the consent screen again.
// This ensures users starting a new wallet flow are prompted to make a fresh choice.
await resetMetricsOptInUISeen();
await metrics.enable(false);
// need to call hasMetricConset to update the cached consent state
await hasMetricsConsent();
trace({ name: TraceName.OnboardingCreateWallet });
const action = () => {
trace({
name: TraceName.OnboardingNewSrpCreateWallet,
op: TraceOperation.OnboardingUserJourney,
tags: getTraceTags(store.getState()),
parentContext: onboardingTraceCtx.current,
});
navigation.navigate('ChoosePassword', {
[PREVIOUS_SCREEN]: ONBOARDING,
onboardingTraceCtx: onboardingTraceCtx.current,
});
dispatch(
setAccountType({
accountType: AccountType.Metamask,
onboardingVersion,
}),
);
track(MetaMetricsEvents.WALLET_SETUP_STARTED, {
account_type: AccountType.Metamask,
});
};
handleExistingUser(action);
endTrace({ name: TraceName.OnboardingCreateWallet });
}, [
metrics,
navigation,
track,
handleExistingUser,
dispatch,
onboardingVersion,
]);
const onPressImport = useCallback(async (): Promise<void> => {
if (SEEDLESS_ONBOARDING_ENABLED) {
OAuthLoginService.resetOauthState();
}
// Reset metrics opt-in UI flag so the user sees the consent screen again.
// This ensures users starting a new wallet flow are prompted to make a fresh choice.
await resetMetricsOptInUISeen();
await metrics.enable(false);
await hasMetricsConsent();
const action = async () => {
trace({
name: TraceName.OnboardingExistingSrpImport,
op: TraceOperation.OnboardingUserJourney,
tags: getTraceTags(store.getState()),
parentContext: onboardingTraceCtx.current,
});
navigation.navigate(
Routes.ONBOARDING.IMPORT_FROM_SECRET_RECOVERY_PHRASE,
{
[PREVIOUS_SCREEN]: ONBOARDING,
onboardingTraceCtx: onboardingTraceCtx.current,
},
);
dispatch(
setAccountType({
accountType: AccountType.Imported,
onboardingVersion,
}),
);
track(MetaMetricsEvents.WALLET_IMPORT_STARTED, {
account_type: AccountType.Imported,
});
};
handleExistingUser(action);
}, [
metrics,
navigation,
track,
handleExistingUser,
dispatch,
onboardingVersion,
]);
const handlePostSocialLogin = useCallback(
(
result: OAuthLoginResult,
createWallet: boolean,
provider: string,
): void => {
const isIOS = Platform.OS === 'ios';
if (socialLoginTraceCtx.current) {
endTrace({ name: TraceName.OnboardingSocialLoginAttempt });
socialLoginTraceCtx.current = undefined;
}
// Error case (result.type !== 'success') is not handled here because
// OAuthService.handleOAuthLogin() throws on failure, and the error is
// caught by the try/catch in onPressContinueWithSocialLogin, which calls
// handleLoginError → handleOAuthLoginError → captureException (Sentry).
if (result.type !== 'success') {
return;
}
const accountType = getSocialAccountType(provider, result.existingUser);
dispatch(setAccountType({ accountType, onboardingVersion }));
track(MetaMetricsEvents.SOCIAL_LOGIN_COMPLETED, {
account_type: accountType,
...getWalletSetupCompletedAttributionProperties(store.getState()),
});
if (createWallet) {
if (result.existingUser) {
navigation.navigate('AccountAlreadyExists', {
accountName: result.accountName,
oauthLoginSuccess: true,
onboardingTraceCtx: onboardingTraceCtx.current,
provider,
});
} else {
trace({
name: TraceName.OnboardingNewSocialCreateWallet,
op: TraceOperation.OnboardingUserJourney,
tags: getTraceTags(store.getState()),
parentContext: onboardingTraceCtx.current,
});
if (isIOS) {
// Navigate to SocialLoginSuccess screen first, then ChoosePassword
navigation.navigate(
Routes.ONBOARDING.SOCIAL_LOGIN_SUCCESS_NEW_USER,
{
accountName: result.accountName,
oauthLoginSuccess: true,
onboardingTraceCtx: onboardingTraceCtx.current,
provider,
},
);
} else {
// Direct navigation to ChoosePassword for Android
navigation.navigate('ChoosePassword', {
[PREVIOUS_SCREEN]: ONBOARDING,
oauthLoginSuccess: true,
onboardingTraceCtx: onboardingTraceCtx.current,
provider,
});
}
}
} else if (result.existingUser) {
trace({
name: TraceName.OnboardingExistingSocialLogin,
op: TraceOperation.OnboardingUserJourney,
tags: getTraceTags(store.getState()),
parentContext: onboardingTraceCtx.current,
});
isIOS
? navigation.navigate(
Routes.ONBOARDING.SOCIAL_LOGIN_SUCCESS_EXISTING_USER,
{
[PREVIOUS_SCREEN]: ONBOARDING,
oauthLoginSuccess: true,
onboardingTraceCtx: onboardingTraceCtx.current,
provider,
},
)
: navigation.navigate(Routes.ONBOARDING.ONBOARDING_OAUTH_REHYDRATE, {
[PREVIOUS_SCREEN]: ONBOARDING,
oauthLoginSuccess: true,
onboardingTraceCtx: onboardingTraceCtx.current,
});
} else {
navigation.navigate('AccountNotFound', {
accountName: result.accountName,
oauthLoginSuccess: true,
onboardingTraceCtx: onboardingTraceCtx.current,
provider,
});
}
},
[navigation, track, dispatch, onboardingVersion],
);
const handleOAuthLoginError = useCallback(
(error: OAuthError, provider: string, isFallback: boolean): void => {
const platform = Platform.OS;
const errorCode = String(error.code);
if (metrics.isEnabled()) {
captureException(error, {
tags: {
view: 'Onboarding',
context: 'OAuth login failed - user consented to analytics',
oauth_platform: platform,
oauth_provider: provider,
oauth_error_code: errorCode,
oauth_is_fallback: String(isFallback),
},
fingerprint: ['oauth-login-error', platform, provider, errorCode],
});
} else {
setState((prevState) => ({
...prevState,
loading: false,
errorToThrow: new Error(`OAuth login failed: ${error.message}`),
}));
}
},
[metrics],
);
const handleLoginError = useCallback(
async (
error: Error,
socialConnectionType: string,
createWallet: boolean,
): Promise<void> => {
if (error instanceof OAuthError) {
// For OAuth API failures (excluding user cancellation/dismissal), handle based on analytics consent
if (
error.code === OAuthErrorType.UserCancelled ||
error.code === OAuthErrorType.UserDismissed ||
error.code === OAuthErrorType.GoogleLoginError ||
error.code === OAuthErrorType.AppleLoginError
) {
// QA: do not show error sheet if user cancelled
return;
} else if (
error.code === OAuthErrorType.GoogleLoginNoCredential ||
error.code === OAuthErrorType.GoogleLoginNoMatchingCredential ||
// GoogleLoginUserDisabledOneTapFeature: User has disabled One Tap in their Google
// account settings. While this is a user preference, we still offer browser-based
// login as an alternative since the user's intent is to sign in - they just prefer
// not to use the One Tap UI. Browser OAuth provides a familiar login experience.
error.code === OAuthErrorType.GoogleLoginUserDisabledOneTapFeature ||
error.code === OAuthErrorType.GoogleLoginOneTapFailure ||
// GoogleLoginNoProviderDependencies: The Android Credential Manager cannot find
// required provider dependencies. Fallback to browser-based OAuth.
error.code === OAuthErrorType.GoogleLoginNoProviderDependencies ||
(error.code === OAuthErrorType.UnknownError &&
Platform.OS === 'android' &&
socialConnectionType === 'google')
) {
// For Android Google, try browser fallback instead of showing error.
// Note: We intentionally call handleOAuthLoginError (not handleLoginError) in the
// fallback catch block to prevent nested fallback attempts. The browser-based
// fallback handler won't throw ACM-specific errors, but this pattern ensures
// we don't accidentally create infinite fallback loops if the code is refactored.
if (Platform.OS === 'android' && socialConnectionType === 'google') {
try {
setLoading();
const fallbackHandler = createLoginHandler(
Platform.OS,
AuthConnection.Google,
true, // Use browser fallback
);
const result = await OAuthLoginService.handleOAuthLogin(
fallbackHandler,
!createWallet,
);
handlePostSocialLogin(
result as OAuthLoginResult,
createWallet,
socialConnectionType,
);
// delay unset loading to avoid flash of loading state
setTimeout(() => {
unsetLoading();
}, 1000);
return;
} catch (fallbackError) {
unsetLoading();
if (
fallbackError instanceof OAuthError &&
(fallbackError.code === OAuthErrorType.UserCancelled ||
fallbackError.code === OAuthErrorType.UserDismissed)
) {
return;
}
// Handle both OAuthError and unexpected errors from browser fallback
if (fallbackError instanceof OAuthError) {
handleOAuthLoginError(
fallbackError,
socialConnectionType,
true,
);
} else {
// Wrap unexpected errors as OAuthError to ensure they're properly handled
const wrappedError = new OAuthError(
fallbackError instanceof Error
? fallbackError.message
: 'Browser fallback failed with unknown error',
OAuthErrorType.UnknownError,
);
handleOAuthLoginError(wrappedError, socialConnectionType, true);
}
return;
}
}
return;
}
// Show error sheet for auth server or seedless controller errors
if (
error.code === OAuthErrorType.AuthServerError ||
error.code === OAuthErrorType.LoginError
) {
handleOAuthLoginError(error, socialConnectionType, false);
navigation.navigate(Routes.MODAL.ROOT_MODAL_FLOW, {
screen: Routes.SHEET.SUCCESS_ERROR_SHEET,
params: {
title: strings('error_sheet.oauth_error_title'),
description: strings('error_sheet.oauth_error_description'),
descriptionAlign: 'center',
buttonLabel: strings('error_sheet.oauth_error_button'),
type: 'error',
},
});
return;
}
// unexpected oauth login error
handleOAuthLoginError(error, socialConnectionType, false);
return;
}
const errorMessage = 'oauth_error';
trace({
name: TraceName.OnboardingSocialLoginError,
op: TraceOperation.OnboardingError,
tags: { provider: socialConnectionType, errorMessage },
parentContext: onboardingTraceCtx.current,
});
endTrace({ name: TraceName.OnboardingSocialLoginError });
if (socialLoginTraceCtx.current) {
endTrace({
name: TraceName.OnboardingSocialLoginAttempt,
data: { success: false },
});
socialLoginTraceCtx.current = undefined;
}
navigation.navigate(Routes.MODAL.ROOT_MODAL_FLOW, {
screen: Routes.SHEET.SUCCESS_ERROR_SHEET,
params: {
title: strings(`error_sheet.${errorMessage}_title`),
description: strings(`error_sheet.${errorMessage}_description`),
descriptionAlign: 'center',
buttonLabel: strings(`error_sheet.${errorMessage}_button`),
type: 'error',
},
});
},
[
navigation,
handleOAuthLoginError,
setLoading,
unsetLoading,
handlePostSocialLogin,
],
);
const onPressContinueWithSocialLogin = useCallback(
async (createWallet: boolean, provider: AuthConnection): Promise<void> => {
// check for internet connection
try {
const netState = await netInfoFetch();
if (!netState.isConnected || netState.isInternetReachable === false) {
navigation.dispatch(
StackActions.replace(Routes.MODAL.ROOT_MODAL_FLOW, {
screen: Routes.SHEET.SUCCESS_ERROR_SHEET,
params: {
title: strings(`error_sheet.no_internet_connection_title`),
description: strings(
`error_sheet.no_internet_connection_description`,
),
descriptionAlign: 'left',
buttonLabel: strings(
`error_sheet.no_internet_connection_button`,
),
primaryButtonLabel: strings(
`error_sheet.no_internet_connection_button`,
),
closeOnPrimaryButtonPress: true,
type: 'error',
},
}),
);
return;
}
} catch (error) {
console.warn('Network check failed:', error);
}
// Continue with the social login flow
navigation.navigate('Onboarding');
// Enable metrics for OAuth users
await metrics.enable(true);
discardBufferedTraces();
await setupSentry();
const accountType = getSocialAccountType(provider, !createWallet);
metrics.trackEvent(
metrics
.createEventBuilder(MetaMetricsEvents.METRICS_OPT_IN)
.addProperties({
updated_after_onboarding: false,
location: 'onboarding_social_login',
account_type: accountType,
})
.build(),
);
// use new trace instead of buffered trace for social login
onboardingTraceCtx.current = trace({
name: TraceName.OnboardingJourneyOverall,
op: TraceOperation.OnboardingUserJourney,
tags: getTraceTags(store.getState()),
});
if (createWallet) {
track(MetaMetricsEvents.WALLET_SETUP_STARTED, {
account_type: accountType,
});
} else {
track(MetaMetricsEvents.WALLET_IMPORT_STARTED, {
account_type: accountType,
});
}
const action = async () => {
// prompt for ios google login not supported below iOS 17.4
if (
provider === AuthConnection.Google &&
Device.isIos() &&
Device.comparePlatformVersionTo('17.4') < 0
) {
if (isGoogleLoginIosUnsupportedBlockingEnabled) {
if (createWallet) {
await presentIosGoogleLoginUnsupportedBlockingSheet(navigation);
} else {
await presentIosGoogleLoginUnsupportedBlockingSheetRehydration(
navigation,
);
}
track(MetaMetricsEvents.WALLET_GOOGLE_IOS_ERROR_VIEWED, {
account_type: accountType,
});
return;
}
await presentIosGoogleLoginVersionWarningSheet(navigation);
track(MetaMetricsEvents.WALLET_GOOGLE_IOS_WARNING_VIEWED, {
account_type: accountType,
location: 'onboarding_social_login',
action: createWallet ? 'create' : 'import',
});
dispatch(setIosGoogleWarningSheetLastDismissedAt(Date.now()));
}
socialLoginTraceCtx.current = trace({
name: TraceName.OnboardingSocialLoginAttempt,
op: TraceOperation.OnboardingUserJourney,
tags: { ...getTraceTags(store.getState()), provider },
parentContext: onboardingTraceCtx.current,
});
setLoading();
const loginHandler = createLoginHandler(Platform.OS, provider);
try {
const result = await OAuthLoginService.handleOAuthLogin(
loginHandler,
!createWallet,
);
handlePostSocialLogin(
result as OAuthLoginResult,
createWallet,
provider,
);
// Mark metrics opt-in UI as seen since OAuth users auto-consent to metrics.
// Set AFTER OAuth succeeds to avoid marking as seen if the flow fails.
await markMetricsOptInUISeen();
// delay unset loading to avoid flash of loading state
setTimeout(() => {
unsetLoading();
}, 1000);
} catch (error) {
unsetLoading();
await handleLoginError(error as Error, provider, createWallet);
}
};
handleExistingUser(action);
},
[
navigation,
metrics,
track,
dispatch,
setLoading,
unsetLoading,
handleLoginError,
handlePostSocialLogin,
handleExistingUser,
isGoogleLoginIosUnsupportedBlockingEnabled,
],
);
const onPressContinueWithApple = useCallback(
async (createWallet: boolean): Promise<void> =>
onPressContinueWithSocialLogin(createWallet, AuthConnection.Apple),
[onPressContinueWithSocialLogin],
);
const onPressContinueWithGoogle = useCallback(
async (createWallet: boolean): Promise<void> =>
onPressContinueWithSocialLogin(createWallet, AuthConnection.Google),
[onPressContinueWithSocialLogin],
);
const handleCtaActions = useCallback(
async (actionType: string): Promise<void> => {
if (SEEDLESS_ONBOARDING_ENABLED) {
dispatch(clearSeedlessOnboarding());
navigation.navigate(Routes.MODAL.ROOT_MODAL_FLOW, {
screen: Routes.SHEET.ONBOARDING_SHEET,
params: {
onPressCreate,
onPressImport,
onPressContinueWithGoogle,
onPressContinueWithApple,
createWallet: actionType === 'create',
},
});
} else if (actionType === 'create') {
await onPressCreate();
} else {
await onPressImport();
}
},
[
navigation,
onPressCreate,
onPressImport,
onPressContinueWithGoogle,
onPressContinueWithApple,
dispatch,
],
);
const setStartFoxAnimation = useCallback((): void => {
setState((prevState) => ({ ...prevState, startFoxAnimation: 'Start' }));
}, []);
const renderLoader = useCallback(
(): React.ReactElement => (
<Box
alignItems={BoxAlignItems.Center}
justifyContent={BoxJustifyContent.Center}
twClassName="flex-1 gap-y-8 mb-40"
>
<Box justifyContent={BoxJustifyContent.Center}>
<ActivityIndicator size="small" />
<Text
variant={TextVariant.BodyMd}
style={tw.style('mt-[30px] text-center text-default')}
>
{loadingMsg}
</Text>
</Box>
</Box>
),
[loadingMsg, tw],
);
const renderContent = useCallback(
(): React.ReactElement => (
<Box
justifyContent={BoxJustifyContent.Between}
alignItems={BoxAlignItems.Center}
twClassName={`flex-1 w-full px-5 ${Device.isMediumDevice() ? 'gap-y-4' : 'gap-y-6'}`}
>
<OnboardingAnimation
startOnboardingAnimation={state.startOnboardingAnimation}
setStartFoxAnimation={setStartFoxAnimation}
>
{/*
* These onboarding buttons are intentionally pinned to specific themes regardless of the user's
* system theme setting: the "Create" button is always dark (black bg, white text) and the
* "Import" button is always light (white bg, black text). This design choice ensures both
* buttons remain visually distinct and accessible against the purple onboarding background
* in all theme contexts.
*/}
<ThemeProvider
theme={Theme.Dark} // Keep this button in dark mode regardless of theme
>
<Button
variant={ButtonVariant.Primary}
onPress={() => handleCtaActions('create')}
testID={OnboardingSelectorIDs.NEW_WALLET_BUTTON}
isFullWidth
size={Device.isMediumDevice() ? ButtonSize.Md : ButtonSize.Lg}
>
{strings('onboarding.start_exploring_now')}
</Button>
</ThemeProvider>
<ThemeProvider
theme={Theme.Light} // Keep this button in light mode regardless of theme
>
<Button
variant={ButtonVariant.Primary}
onPress={() => handleCtaActions('existing')}
testID={OnboardingSelectorIDs.EXISTING_WALLET_BUTTON}
isFullWidth
size={Device.isMediumDevice() ? ButtonSize.Md : ButtonSize.Lg}
>
{SEEDLESS_ONBOARDING_ENABLED
? strings('onboarding.import_using_srp_social_login')
: strings('onboarding.import_using_srp')}
</Button>
</ThemeProvider>
</OnboardingAnimation>
</Box>
),
[state.startOnboardingAnimation, setStartFoxAnimation, handleCtaActions],
);
const handleSimpleNotification =
useCallback((): React.ReactElement | null => {
if (!route?.params?.delete && !route?.params?.showErrorReportSentToast)
return null;
const notificationData = route?.params?.showErrorReportSentToast
? {
title: strings('wallet_creation_error.error_report_sent_title'),
description: strings(
'wallet_creation_error.error_report_sent_description',
),
}
: {
title: strings('onboarding.success'),
description: strings('onboarding.your_wallet'),
};