-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathApp.tsx
More file actions
896 lines (879 loc) · 27.2 KB
/
App.tsx
File metadata and controls
896 lines (879 loc) · 27.2 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
// App.tsx
import React, {useCallback, useEffect, useState} from 'react';
import {NavigationContainer} from '@react-navigation/native';
import type {BottomTabHeaderProps} from '@react-navigation/bottom-tabs';
import type {NativeStackHeaderProps} from '@react-navigation/native-stack';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {enableScreens} from 'react-native-screens';
import {Image} from 'react-native';
import ShowcaseScreen from './screens/ShowcaseScreen';
import WalletHome from './screens/WalletHome';
import MempoolPlaygroundScreen from './screens/MempoolPlaygroundScreen';
import UtxosScreen from './screens/UtxosScreen';
import AddressesScreen from './screens/AddressesScreen';
import PSBTScreen from './screens/PSBTScreen';
import DeviceScreen from './screens/DeviceScreen';
import LoadingScreen from './screens/LoadingScreen';
import Zeroconf, {ImplType} from 'react-native-zeroconf';
import ReactNativeBiometrics, {BiometryTypes} from 'react-native-biometrics';
import DeviceInfo from 'react-native-device-info';
import {ThemeProvider, useTheme} from './theme';
import {WalletProvider} from './context/WalletContext';
import {UserProvider, useUser} from './context/UserContext';
import {
SafeAreaProvider,
useSafeAreaInsets,
} from 'react-native-safe-area-context';
import {initializeHaptics} from './utils';
import database from './services/Database';
import {runMigrationIfNeeded} from './services/LocalCacheMigration';
import ErrorBoundary from './components/ErrorBoundary';
import {
Alert,
EmitterSubscription,
NativeEventEmitter,
Platform,
DeviceEventEmitter,
View,
Text,
StyleSheet,
type GestureResponderEvent,
} from 'react-native';
import AppPressable from './components/AppPressable';
import WalletSettings from './screens/WalletSettings';
import {NativeModules} from 'react-native';
import {dbg, pinRemoteIP, getPinnedRemoteIPs, getKeyshareMetadata} from './utils';
import MobilesPairing from './screens/MobilesPairing';
import MobileNostrPairing from './screens/MobileNostrPairing';
import UserPreferenceScreen from './screens/UserPreferenceScreen';
import {CustomHeader} from './components/Header';
import Toast from 'react-native-toast-message';
import {createToastConfig} from './utils/toastConfig';
// Initialize react-native-screens for Fabric compatibility
enableScreens(true);
const {BBMTLibNativeModule} = NativeModules;
const Stack = createNativeStackNavigator();
const Tab = createBottomTabNavigator();
// Debug logging state (session-only, not persisted)
// Default: false (logs suppressed even in __DEV__)
// This is a module-level variable that can be set from WalletSettings
let debugLoggingEnabledRef = {current: false};
// Store original console methods before they get disabled
const originalConsole = {
log: console.log,
warn: console.warn,
error: console.error,
debug: console.debug,
info: console.info,
trace: console.trace,
};
// Export functions to control debug logging from other modules
export const setDebugLoggingEnabled = (enabled: boolean) => {
debugLoggingEnabledRef.current = enabled;
};
export const isDebugLoggingEnabled = () => {
return debugLoggingEnabledRef.current;
};
const rnBiometrics = new ReactNativeBiometrics({allowDeviceCredentials: true});
const zeroconf = new Zeroconf();
const zeroOut = new Zeroconf();
/** Tab + stack headers both pass props here; CustomHeader is typed for native stack only. */
type AppNavigationHeaderProps =
| NativeStackHeaderProps
| BottomTabHeaderProps;
const renderAppHeader =
(height: number) => (props: AppNavigationHeaderProps) => (
<CustomHeader {...(props as NativeStackHeaderProps)} height={height} />
);
// Custom header components with configurable height
const HomeHeader = renderAppHeader(60);
const PSBTHeader = renderAppHeader(60);
const SettingsHeader = renderAppHeader(60);
const WelcomeHeader = renderAppHeader(60);
const DevicesPairingHeader = renderAppHeader(60);
const NostrConnectHeader = renderAppHeader(60);
const DeviceHeader = renderAppHeader(60);
const TAB_BAR_ICON_SIZE = 22;
const tabBarIcons = {
Device: require('./assets/key-icon.png'),
Wallet: require('./assets/wallet-icon.png'),
Playground: require('./assets/mempool-icon.png'),
Utxos: require('./assets/utxo-icon.png'),
Addresses: require('./assets/addresses-icon.png'),
PSBT: require('./assets/cosign-icon.png'),
Settings: require('./assets/settings-icon.png'),
};
const TabBarIcon = ({
name,
color,
size = TAB_BAR_ICON_SIZE,
}: {
name: keyof typeof tabBarIcons;
color: string;
size?: number;
}) => {
const inset = 1;
const iconSize = size - inset * 2;
return (
<View style={tabBarStyles.tabBarIconInner}>
<Image
source={tabBarIcons[name]}
style={{width: iconSize, height: iconSize, tintColor: color}}
resizeMode="contain"
/>
</View>
);
};
const TabBarIconDevice = (props: {color: string; size?: number}) => (
<TabBarIcon
name="Device"
color={props.color}
size={props.size ?? TAB_BAR_ICON_SIZE}
/>
);
const TabBarIconWallet = (props: {color: string; size?: number}) => (
<TabBarIcon
name="Wallet"
color={props.color}
size={props.size ?? TAB_BAR_ICON_SIZE}
/>
);
const TabBarIconPlayground = (props: {color: string; size?: number}) => (
<TabBarIcon
name="Playground"
color={props.color}
size={props.size ?? TAB_BAR_ICON_SIZE}
/>
);
const TabBarIconUtxos = (props: {color: string; size?: number}) => (
<TabBarIcon
name="Utxos"
color={props.color}
size={props.size ?? TAB_BAR_ICON_SIZE}
/>
);
const TabBarIconAddresses = (props: {color: string; size?: number}) => (
<TabBarIcon
name="Addresses"
color={props.color}
size={props.size ?? TAB_BAR_ICON_SIZE}
/>
);
const TabBarIconPSBT = (props: {color: string; size?: number}) => (
<TabBarIcon
name="PSBT"
color={props.color}
size={props.size ?? TAB_BAR_ICON_SIZE}
/>
);
const TabBarIconSettings = (props: {color: string; size?: number}) => (
<TabBarIcon
name="Settings"
color={props.color}
size={props.size ?? TAB_BAR_ICON_SIZE}
/>
);
const TAB_BAR_BUTTON_BORDER_RADIUS = 12;
const tabBarStyles = StyleSheet.create({
mainTabsContainer: {flex: 1},
tabBarButtonInner: {
flex: 1,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
borderRadius: TAB_BAR_BUTTON_BORDER_RADIUS,
overflow: 'hidden',
padding: 12,
},
activeTabBgLight: {backgroundColor: 'rgba(0,0,0,0.06)'},
activeTabBgDark: {backgroundColor: 'rgba(255,255,255,0.08)'},
tabBarIcon: {
width: TAB_BAR_ICON_SIZE,
height: TAB_BAR_ICON_SIZE,
marginBottom: 2,
overflow: 'visible' as const,
},
tabBarIconInner: {
width: TAB_BAR_ICON_SIZE,
height: TAB_BAR_ICON_SIZE,
alignItems: 'center',
justifyContent: 'center',
},
tabBarLabel: {
textAlign: 'center',
},
tabBarLabelWrapper: {
flex: 1,
width: '100%',
alignItems: 'center',
justifyContent: 'center',
minWidth: 0,
},
tabBarLabelText: {
width: '100%',
textAlign: 'center',
},
tabBarItem: {
alignItems: 'center',
justifyContent: 'center',
},
});
const TabBarLabel = ({color, children}: {color: string; children: string}) => {
const {theme} = useTheme();
const labelTypography = {
fontSize: theme.fontSizes?.xs || 10,
fontFamily: theme.fontFamilies?.medium,
color,
};
return (
<View style={tabBarStyles.tabBarLabelWrapper}>
<Text
style={[
tabBarStyles.tabBarLabel,
tabBarStyles.tabBarLabelText,
labelTypography,
]}
numberOfLines={1}
adjustsFontSizeToFit
minimumFontScale={0.5}>
{children}
</Text>
</View>
);
};
type TabBarButtonProps = Record<string, unknown> & {isDarkMode?: boolean};
const TabBarButton = (props: TabBarButtonProps) => {
const {style, accessibilityState, isDarkMode, onPress, ...rest} = props;
const selected = (accessibilityState as {selected?: boolean})?.selected;
const activeBg =
isDarkMode === true
? tabBarStyles.activeTabBgDark
: tabBarStyles.activeTabBgLight;
const handlePress = useCallback(
(e: GestureResponderEvent) => {
(onPress as (e: GestureResponderEvent) => void)?.(e);
},
[onPress],
);
return (
<View style={[style as object, selected && activeBg]}>
<AppPressable
{...(rest as object)}
onPress={handlePress}
style={tabBarStyles.tabBarButtonInner}
/>
</View>
);
};
const MainTabs = () => {
const {theme} = useTheme();
const insets = useSafeAreaInsets();
const isDarkMode = theme.colors.background !== '#ffffff';
const lockFabOverlayStyle = {
position: 'absolute' as const,
right: 0,
bottom: 0,
left: 0,
top: 0,
zIndex: 999,
elevation: 8,
backgroundColor: 'transparent',
pointerEvents: 'box-none' as const,
};
const lockFabPosition = {
position: 'absolute' as const,
right: 30 + insets.right,
bottom: 80 + insets.bottom,
zIndex: 1000,
};
const lockFabSize = 48; // 15% smaller than 56
const lockFabShape = {
width: lockFabSize,
height: lockFabSize,
borderRadius: lockFabSize / 2,
alignItems: 'center' as const,
justifyContent: 'center' as const,
backgroundColor: isDarkMode
? theme.colors.cardBackground
: theme.colors.primaryOverlay95,
borderWidth: Platform.OS === 'android' ? 0 : 1,
borderColor: isDarkMode
? theme.colors.border + '80'
: theme.colors.blackOverlay10,
};
const lockFabStyle =
Platform.OS === 'android'
? {
...lockFabShape,
position: 'absolute' as const,
top: 0,
left: 0,
overflow: 'hidden' as const,
elevation: 0,
}
: {
...lockFabPosition,
...lockFabShape,
shadowColor: theme.colors.shadowColor || '#000',
shadowOffset: {width: 0, height: 2},
shadowOpacity: 0.15,
shadowRadius: 4,
elevation: 4,
};
const lockFabWrapperStyle =
Platform.OS === 'android'
? {
...lockFabPosition,
width: lockFabSize,
height: lockFabSize,
}
: undefined;
const lockFabShadowStyle =
Platform.OS === 'android'
? {
position: 'absolute' as const,
top: -1,
left: -1,
width: lockFabSize + 2,
height: lockFabSize + 2,
borderRadius: lockFabSize / 2 + 1,
backgroundColor: 'rgba(255, 255, 255, 0.2)',
}
: undefined;
const lockFabIconStyle = {
width: 20,
height: 20,
tintColor: theme.colors.textOnPrimary,
opacity: 0.9,
resizeMode: 'contain' as const,
};
const renderTabBarButton = useCallback(
(props: Record<string, unknown>) => (
<TabBarButton {...props} isDarkMode={isDarkMode} />
),
[isDarkMode],
);
const {
activeNetwork,
showMempoolPlayground,
showUtxosTab,
showAddressesTab,
showPsbtTab,
showWalletTab,
} = useUser();
const showPlayTab = activeNetwork === 'mainnet' && showMempoolPlayground;
const initialTab = showWalletTab ? 'Wallet' : showPsbtTab ? 'PSBT' : 'Device';
return (
<View style={tabBarStyles.mainTabsContainer}>
<Tab.Navigator
initialRouteName={initialTab}
screenOptions={{
headerShown: true,
headerLeft: () => null,
headerTitle: '',
headerTitleAlign: 'left',
tabBarStyle: {
backgroundColor: theme.colors.background,
borderTopWidth: 1,
borderTopColor: isDarkMode
? theme.colors.border + 'CC'
: theme.colors.border + '60',
},
tabBarActiveTintColor: isDarkMode
? theme.colors.text
: theme.colors.primary || theme.colors.text,
tabBarInactiveTintColor: theme.colors.textSecondary,
tabBarIconStyle: tabBarStyles.tabBarIcon,
tabBarLabelStyle: tabBarStyles.tabBarLabel,
tabBarItemStyle: tabBarStyles.tabBarItem,
tabBarAllowFontScaling: false,
tabBarButton: renderTabBarButton,
tabBarLabel: TabBarLabel,
}}>
<Tab.Screen
name="Device"
component={DeviceScreen}
options={{
header: DeviceHeader,
tabBarLabel: 'Device',
tabBarIcon: TabBarIconDevice,
}}
/>
{showPsbtTab && (
<Tab.Screen
name="PSBT"
component={PSBTScreen}
options={{
header: PSBTHeader,
tabBarLabel: 'PSBT',
tabBarIcon: TabBarIconPSBT,
}}
/>
)}
{showWalletTab && (
<Tab.Screen
name="Wallet"
component={WalletHome}
options={{
header: HomeHeader,
tabBarLabel: 'Wallet',
tabBarIcon: TabBarIconWallet,
}}
/>
)}
{showPlayTab && (
<Tab.Screen
name="Playground"
component={MempoolPlaygroundScreen}
options={{
header: HomeHeader,
tabBarLabel: 'Play',
tabBarIcon: TabBarIconPlayground,
}}
/>
)}
{showUtxosTab && (
<Tab.Screen
name="Utxos"
component={UtxosScreen}
options={{
header: HomeHeader,
tabBarLabel: 'UTXOs',
tabBarIcon: TabBarIconUtxos,
}}
/>
)}
{showAddressesTab && (
<Tab.Screen
name="Addresses"
component={AddressesScreen}
options={{
header: HomeHeader,
tabBarLabel: 'Addresses',
tabBarIcon: TabBarIconAddresses,
}}
/>
)}
<Tab.Screen
name="Settings"
component={WalletSettings}
options={{
header: SettingsHeader,
tabBarLabel: 'Settings',
tabBarIcon: TabBarIconSettings,
}}
/>
</Tab.Navigator>
<View style={lockFabOverlayStyle}>
{Platform.OS === 'android' &&
lockFabWrapperStyle &&
lockFabShadowStyle ? (
<View style={lockFabWrapperStyle}>
<View style={lockFabShadowStyle} pointerEvents="none" />
<AppPressable
style={lockFabStyle}
onPress={() => {
DeviceEventEmitter.emit('app:reload');
}}
accessible={true}
accessibilityRole="button"
accessibilityLabel="Lock wallet"
accessibilityHint="Double tap to lock the wallet">
<Image
source={require('./assets/locker-icon.png')}
style={lockFabIconStyle}
/>
</AppPressable>
</View>
) : (
<AppPressable
style={lockFabStyle}
onPress={() => {
DeviceEventEmitter.emit('app:reload');
}}
accessible={true}
accessibilityRole="button"
accessibilityLabel="Lock wallet"
accessibilityHint="Double tap to lock the wallet">
<Image
source={require('./assets/locker-icon.png')}
style={lockFabIconStyle}
/>
</AppPressable>
)}
</View>
</View>
);
};
const App = () => {
const [initialRoute, setInitialRoute] = useState<string | null>(null);
const [isAuthenticated, setIsAuthenticated] = useState(false);
// Used to force-remount providers/contexts on "app:reload"
const [appResetKey, setAppResetKey] = useState(0);
// Initialize debug logging state from module-level ref
const [debugLoggingEnabled, setDebugLoggingEnabledState] = useState(
debugLoggingEnabledRef.current,
);
useEffect(() => {
const sub = DeviceEventEmitter.addListener('app:reload', async () => {
//dbg('App: Received app:reload event');
setIsAuthenticated(false);
setAppResetKey(k => k + 1);
// Update debug logging state from ref
setDebugLoggingEnabledState(debugLoggingEnabledRef.current);
// Re-check wallet state after reload to ensure correct initial route
try {
const meta = await getKeyshareMetadata();
const route = meta ? 'MainTabs' : 'Welcome';
setInitialRoute(route);
} catch {
setInitialRoute('Welcome');
}
});
return () => sub.remove();
}, []);
useEffect(() => {
initializeHaptics();
const checkWallet = async () => {
// Open SQLite database and run one-time LocalCache → SQLite migration.
// Wrapped in try/catch so a DB failure never blocks app startup.
try {
await database.open();
dbg('App: SQLite database ready');
await runMigrationIfNeeded();
} catch (dbErr) {
dbg('App: Database init error (non-fatal):', dbErr);
}
try {
const meta = await getKeyshareMetadata();
dbg('initializeApp keyshare found', !!meta);
const route = meta ? 'MainTabs' : 'Welcome';
dbg('Setting initial route to:', route);
setInitialRoute(route);
} catch (error) {
dbg('Error in initializeApp:', error);
setInitialRoute('Welcome');
}
};
checkWallet();
}, []);
useEffect(() => {
try {
dbg('publishing service...');
const deviceID = DeviceInfo.getUniqueIdSync();
if (!deviceID || deviceID.trim() === '') {
dbg('Warning: deviceID is empty, skipping service publication');
return;
}
dbg('deviceID:', deviceID);
zeroOut.publishService(
'http', // Fixed with underscore
'tcp',
'local.',
'bbw_scan',
55056,
{txt: 'bbw_scan', id: deviceID},
ImplType.NSD,
);
dbg('service bbw_scan published');
return () => {
try {
zeroOut.unpublishService('bbw_scan', ImplType.NSD);
zeroOut.stop();
dbg('service publish stopped');
} catch (e: any) {
dbg('error stopping service', e);
}
};
} catch (e: any) {
dbg('error publishing service', e);
}
}, []);
useEffect(() => {
try {
dbg('scanning for mDNS Services');
const deviceID = DeviceInfo.getUniqueIdSync();
// Validate deviceID before scanning
if (!deviceID || deviceID.trim() === '') {
dbg('Warning: deviceID is empty, skipping mDNS scan');
return;
}
zeroconf.scan('http', 'tcp', 'local.');
zeroconf.on('resolved', service => {
dbg('Service Found:', service.fullName);
if (
service.txt &&
service.txt.txt === 'bbw_scan' &&
service.txt.id &&
service.txt.id !== deviceID
) {
let addresses = service.addresses || [];
for (const address of addresses) {
if (address && address.split('.').length === 4) {
pinRemoteIP(address);
}
}
const pinned = getPinnedRemoteIPs();
if (pinned.length) {
dbg('Pinned remote IPv4 addresses:', pinned.join(', '));
}
}
});
zeroconf.on('error', err => {
dbg('Zeroconf error:', String(err));
});
return () => {
try {
dbg('service scanning stopped');
zeroconf.removeAllListeners();
zeroconf.stop();
} catch (e: any) {
dbg('error stopping mDNS scan', e);
}
};
} catch (e: any) {
dbg('error scanning mDNS', e);
}
}, []);
useEffect(() => {
let subscription: EmitterSubscription | undefined;
// Sync ref with state to ensure consistency
debugLoggingEnabledRef.current = debugLoggingEnabled;
// Always disable logging by default (even in __DEV__)
// Only enable if explicitly toggled via debug setting
if (!__DEV__ && !debugLoggingEnabled) {
BBMTLibNativeModule.disableLogging('ok')
.then((feedback: any) => {
if (feedback === 'ok') {
// Restore console methods temporarily to log the message
console.log = originalConsole.log;
console.log('[DEBUG] Logging disabled');
// Now disable console methods
console.log = () => {};
console.warn = () => {};
console.error = () => {};
console.debug = () => {};
console.info = () => {};
console.trace = () => {};
} else {
console.warn('could not disable logging');
}
})
.catch((e: Error) => {
// Restore console.log temporarily to log the error
console.log = originalConsole.log;
console.log('error while disabling logging', e);
// Disable again
console.log = () => {};
});
} else {
// Restore original console methods first (they might be disabled from previous state)
console.log = originalConsole.log;
console.warn = originalConsole.warn;
console.error = originalConsole.error;
console.debug = originalConsole.debug;
console.info = originalConsole.info;
console.trace = originalConsole.trace;
// Now we can log the enabled message
console.log('[DEBUG] Logging enabled');
// Debug logging enabled - set up native log listeners
const logEmitter = new NativeEventEmitter(BBMTLibNativeModule);
if (Platform.OS === 'android') {
logEmitter.removeAllListeners('BBMT_DROID');
subscription = logEmitter.addListener('BBMT_DROID', async log => {
dbg('BBMT_DROID', log.tag, log.message);
});
}
if (Platform.OS === 'ios') {
logEmitter.removeAllListeners('BBMT_APPLE');
subscription = logEmitter.addListener('BBMT_APPLE', async log => {
dbg('BBMT_APPLE', log);
});
}
}
return () => {
subscription?.remove();
};
}, [debugLoggingEnabled]);
const authenticateUser = async () => {
try {
dbg('Starting authentication...');
const {available, biometryType} = await rnBiometrics.isSensorAvailable();
dbg('Biometric available:', available, 'Type:', biometryType);
if (!available) {
dbg('No biometric available, skipping authentication');
setIsAuthenticated(true);
return;
}
if (
available &&
(biometryType === BiometryTypes.TouchID ||
biometryType === BiometryTypes.FaceID ||
biometryType === BiometryTypes.Biometrics)
) {
dbg('Using biometric authentication');
const {success} = await rnBiometrics.simplePrompt({
promptMessage: 'Authenticate to access your wallet',
fallbackPromptMessage: 'Use your device passcode to unlock',
});
if (success) {
dbg('Biometric authentication successful');
setIsAuthenticated(true);
} else {
dbg('Biometric authentication failed');
Alert.alert(
'Authentication Failed',
'Unable to authenticate. Please try again.',
[
{
text: 'Retry',
onPress: () => {
authenticateUser();
},
},
],
{cancelable: false},
);
}
} else {
dbg('Using device passcode authentication');
const {success} = await rnBiometrics.simplePrompt({
promptMessage: 'Enter your device passcode to unlock',
});
if (success) {
dbg('Device passcode authentication successful');
setIsAuthenticated(true);
} else {
dbg('Device passcode authentication failed');
Alert.alert(
'Authentication Failed',
'Unable to authenticate. Please try again.',
[
{
text: 'Retry',
onPress: () => {
authenticateUser();
},
},
],
{cancelable: false},
);
}
}
} catch (error) {
dbg('Authentication Error:', error);
if (__DEV__) {
dbg('Development mode: skipping authentication due to error');
setIsAuthenticated(true);
} else {
Alert.alert('Error', 'Authentication failed. Please try again.');
}
}
};
const handleRetryAuthentication = async () => {
setIsAuthenticated(false);
await authenticateUser();
};
dbg(
'Rendering - initialRoute:',
initialRoute,
'isAuthenticated:',
isAuthenticated,
);
return (
<ErrorBoundary>
<SafeAreaProvider>
<ThemeProvider>
<UserProvider key={`user-${appResetKey}`}>
{initialRoute === null || !isAuthenticated ? (
<LoadingScreen onRetry={handleRetryAuthentication} />
) : (
<AppContent key={`content-${appResetKey}`} initialRoute={initialRoute} />
)}
</UserProvider>
</ThemeProvider>
</SafeAreaProvider>
</ErrorBoundary>
);
};
const AppContent = ({initialRoute}: {initialRoute: string | null}) => {
const {theme} = useTheme();
const dynamicStyles = {
navigationContainer: {
...styles.navigationContainer,
backgroundColor: theme.colors.background,
},
};
return (
<WalletProvider>
<View style={dynamicStyles.navigationContainer}>
<NavigationContainer>
<Stack.Navigator
initialRouteName={initialRoute || undefined}
screenOptions={{
headerShown: false,
headerTitleAlign: 'left',
}}>
<Stack.Screen
name="MainTabs"
component={MainTabs}
options={{headerShown: false}}
/>
<Stack.Screen
name="Welcome"
component={ShowcaseScreen}
options={{
header: WelcomeHeader,
title: 'Welcome',
}}
/>
<Stack.Screen
name="Devices Pairing"
component={MobilesPairing}
options={{
headerShown: true,
header: DevicesPairingHeader,
title: 'Devices Pairing',
}}
/>
<Stack.Screen
name="Nostr Connect"
component={MobileNostrPairing}
options={{
headerShown: true,
header: NostrConnectHeader,
title: 'Nostr Connect',
}}
/>
<Stack.Screen
name="User Preferences"
component={UserPreferenceScreen}
options={{
headerShown: false,
title: 'User Preferences',
}}
/>
</Stack.Navigator>
</NavigationContainer>
<View style={styles.toastWrapper}>
<Toast config={createToastConfig(theme)} />
</View>
</View>
</WalletProvider>
);
};
const styles = StyleSheet.create({
navigationContainer: {
flex: 1,
overflow: 'visible',
// backgroundColor will be set dynamically based on theme
},
toastWrapper: {
...StyleSheet.absoluteFillObject,
zIndex: 99999,
elevation: 99999,
pointerEvents: 'box-none',
},
});
export default App;