-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathNavigation.tsx
More file actions
968 lines (863 loc) · 30.8 KB
/
Navigation.tsx
File metadata and controls
968 lines (863 loc) · 30.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
/* eslint-disable react-hooks/exhaustive-deps */
import React, {
ReactElement,
memo,
useRef,
useEffect,
useContext,
useCallback,
useState,
} from 'react';
import {Linking, AppState, useColorScheme} from 'react-native';
import {AppStorageContext} from './class/storageContext';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {
NavigationContainer,
createNavigationContainerRef,
DefaultTheme,
LinkingOptions,
StackActions,
} from '@react-navigation/native';
import Toast from 'react-native-toast-message';
import {
_BREEZ_SDK_API_KEY_,
_GL_CUSTOM_NOBODY_CERT_,
_GL_CUSTOM_NOBODY_KEY_,
} from './modules/env';
import {
BreezEvent,
mnemonicToSeed,
NodeConfig,
nodeInfo,
NodeConfigVariant,
defaultConfig,
EnvironmentType,
connect,
BreezEventVariant,
ConnectRequest,
} from '@breeztech/react-native-breez-sdk';
import {checkNetworkIsReachable, getXPub256} from './modules/wallet-utils';
import Color from './constants/Color';
import {useRenderCount} from './modules/hooks';
import {checkClipboardContents} from './modules/clipboard';
import {capitalizeFirst} from './modules/transform';
import {useTranslation} from 'react-i18next';
import {actionAlert} from './components/alert';
import Home from './screens/Home';
import PayInvoice from './screens/wallet/PayInvoice';
import TransactionList from './screens/wallet/TransactionsList';
// Biometrics Screen
import LockScreen from './components/lock';
// Wallet screens
import Add from './screens/wallet/Add';
import RestoreActions from './screens/wallet/RestoreActions';
import CreateActions from './screens/wallet/CreateActions';
import Mnemonic from './screens/wallet/Mnemonic';
import WalletViewScreen from './screens/wallet/Wallet';
import Receive from './screens/wallet/Receive';
import Info from './screens/wallet/Info';
import Backup from './screens/wallet/Backup';
import Ownership from './screens/wallet/AddressOwnership';
import RequestAmount from './screens/wallet/RequestAmount';
import FeeSelection from './screens/wallet/FeeSelection';
import TransactionExported from './screens/wallet/TransactionExported';
import Send from './screens/wallet/Send';
import SendAmount from './screens/wallet/SendAmount';
import SendLN from './screens/wallet/SendLN';
import BoltNFC from './screens/wallet/BoltNFC';
import Xpub from './screens/wallet/Xpub';
// Swap screens
import SwapAmount from './screens/wallet/SwapAmount';
import SwapIn from './screens/wallet/SwapIn';
import SwapOut from './screens/wallet/SwapOut';
// Transaction details screen
import TransactionDetails from './screens/wallet/TransactionDetails';
import TransactionStatus from './screens/wallet/TransactionStatus';
import LNTransactionStatus from './screens/wallet/LNTransactionStatus';
// QR Code Scan screen
import Scan from './screens/Scan';
// Main app settings screens
import Settings from './screens/settings/Settings';
import Language from './screens/settings/Language';
import Currency from './screens/settings/Currency';
import Wallet from './screens/settings/Wallet';
import Network from './screens/settings/Network';
// PIN screens
import PINManager from './screens/settings/pin/PIN';
import ChangePIN from './screens/settings/pin/ChangePIN';
import SetPIN from './screens/settings/pin/SetPIN';
import WelcomePIN from './screens/settings/pin/Welcome';
import ConfirmPIN from './screens/settings/pin/ConfirmPIN';
import DonePIN from './screens/settings/pin/Done';
import SetBiometrics from './screens/settings/pin/SetBiometrics';
import ResetPIN from './screens/settings/pin/ResetPIN';
import MnemonicTest from './screens/settings/pin/MnemonicTest';
import ExtKeyTest from './screens/settings/pin/ExtKeyTest';
// Settings Tools
import SettingsTools from './screens/settings/tools/Index';
import ExtendedKey from './screens/settings/tools/ExtendedKey';
import MnemonicTool from './screens/settings/tools/MnemonicTool';
import About from './screens/settings/About';
import License from './screens/settings/License';
import {
TTransaction,
TMiniWallet,
TInvoiceData,
TBreezPaymentDetails,
TLnManualPayloadType,
TSwapInfo,
} from './types/wallet';
import {ENet, EBreezDetails, SwapType} from './types/enums';
import {hasOpenedModals} from './modules/shared';
import {
LnInvoice,
GreenlightCredentials,
} from '@breeztech/react-native-breez-sdk';
import netInfo from '@react-native-community/netinfo';
// Make sure this is updated to match all screen routes below
const modalRoutes = [
'WalletBackup',
'AddressOwnership',
'TransactionDetails',
'TransactionStatus',
'TransactionExported',
'WalletXpub',
// 'addWalletRoot', Screen not necessary as before wallet created
'License',
'XKeyTool',
'MnemonicTool',
];
// Root Param List for Home Screen
export type InitStackParamList = {
HomeScreen: {
restoreMeta: null | {
title: string;
message: string;
load: boolean;
};
};
PayInvoice: {
invoice: string;
};
AddWalletRoot: {
onboarding: boolean;
};
WalletRoot: undefined;
SettingsRoot: undefined;
ScanRoot: undefined;
TransactionList: undefined;
LNTransactionStatus: {
status: boolean;
details: TBreezPaymentDetails;
detailsType: EBreezDetails;
};
Mnemonic: undefined;
};
// Settings Param List for screens
export type SettingsParamList = {
Settings: undefined;
Currency: undefined;
Language: undefined;
Wallet: undefined;
Network: undefined;
About: undefined;
PINManager: undefined;
ChangePIN: undefined;
WelcomePIN: undefined;
SetPIN: {
isChangePIN?: boolean;
isPINReset?: boolean;
};
ConfirmPIN: {
pin: string;
isChangePIN?: boolean;
isPINReset?: boolean;
};
DonePIN: {
isChangePIN?: boolean;
isPINReset?: boolean;
};
SetBiometrics: {
standalone: boolean;
};
ResetPIN: {
isPINReset: boolean;
isChangePIN?: boolean;
};
MnemonicTest: {
isPINReset: boolean;
isChangePIN: boolean;
};
ExtKeyTest: {
isPINReset: boolean;
isChangePIN: boolean;
};
SettingsTools: undefined;
License: undefined;
XKeyTool: undefined;
MnemonicTool: undefined;
};
// Add Wallet Param List for screens
export type AddWalletParamList = {
Add: {
onboarding: boolean;
};
RestoreActions: {
onboarding: boolean;
};
CreateActions: undefined;
};
// Root Param List for screens
export type WalletParamList = {
Receive: {
amount: string;
sats: string;
fiat: string;
lnDescription?: string;
breezServicesNotInitialized: boolean;
};
FeeSelection: {
invoiceData: TInvoiceData;
wallet: TMiniWallet;
};
Send: {
feeRate: number;
dummyPsbtVSize: number;
invoiceData: TInvoiceData;
wallet?: TMiniWallet;
bolt11?: LnInvoice;
};
SwapAmount: {
swapType: SwapType;
swapMeta: TSwapInfo;
};
SwapIn: {
feeRate?: number;
onchainBalance: number;
invoiceData: TInvoiceData;
swapMeta: TSwapInfo;
};
SwapOut: {
lnBalance: number;
swapMeta: TSwapInfo;
satsAmount: number;
maxed: boolean;
};
WalletView: {
reload: boolean;
};
WalletInfo: undefined;
WalletBackup: undefined;
AddressOwnership: {
wallet: TMiniWallet;
};
RequestAmount: {
boltNFCMode?: boolean; // from BoltNFC Quick Action
};
SendAmount: {
invoiceData: any;
wallet: TMiniWallet;
isLightning?: boolean;
isLnManual?: boolean;
lnManualPayload?: TLnManualPayloadType;
};
SendLN: {
lnManualPayload?: TLnManualPayloadType;
};
TransactionDetails: {
tx: TTransaction;
source: string;
walletId: string;
};
TransactionExported: {
status: boolean;
fname: string;
errorMsg: string;
};
TransactionStatus: {
unsignedPsbt: string;
wallet: TMiniWallet;
network: string;
};
BoltNFC: {
amountMsat: number;
description: string;
fromQuickActions: boolean;
satsUnit: boolean; // Whether amount was in sats or fiat
};
WalletXpub: undefined;
};
export type ScanParamList = {
Scan: {
screen: string;
wallet: TMiniWallet;
};
};
const SettingsStack = createNativeStackNavigator<SettingsParamList>();
const SettingsRoot = () => {
return (
<SettingsStack.Navigator screenOptions={{headerShown: false}}>
<SettingsStack.Screen name="Settings" component={Settings} />
<SettingsStack.Screen name="Currency" component={Currency} />
<SettingsStack.Screen name="Language" component={Language} />
<SettingsStack.Screen name="Wallet" component={Wallet} />
<SettingsStack.Screen name="Network" component={Network} />
<SettingsStack.Screen name="About" component={About} />
{/* Set PIN */}
<SettingsStack.Screen name="PINManager" component={PINManager} />
<SettingsStack.Screen name="ChangePIN" component={ChangePIN} />
<SettingsStack.Screen name="WelcomePIN" component={WelcomePIN} />
<SettingsStack.Screen name="SetPIN" component={SetPIN} />
<SettingsStack.Screen name="ConfirmPIN" component={ConfirmPIN} />
<SettingsStack.Screen name="DonePIN" component={DonePIN} />
<SettingsStack.Screen
name="SetBiometrics"
component={SetBiometrics}
/>
<SettingsStack.Screen name="ResetPIN" component={ResetPIN} />
<SettingsStack.Screen
name="MnemonicTest"
component={MnemonicTest}
/>
<SettingsStack.Screen name="ExtKeyTest" component={ExtKeyTest} />
<SettingsStack.Screen
name="SettingsTools"
component={SettingsTools}
/>
<SettingsStack.Group screenOptions={{presentation: 'modal'}}>
<SettingsStack.Screen name="License" component={License} />
<SettingsStack.Screen name="XKeyTool" component={ExtendedKey} />
<SettingsStack.Screen
name="MnemonicTool"
component={MnemonicTool}
/>
</SettingsStack.Group>
</SettingsStack.Navigator>
);
};
const ScanStack = createNativeStackNavigator<ScanParamList>();
const ScanRoot = () => {
return (
<ScanStack.Navigator screenOptions={{headerShown: false}}>
<ScanStack.Screen name="Scan" component={Scan} />
</ScanStack.Navigator>
);
};
const WalletStack = createNativeStackNavigator<WalletParamList>();
const WalletRoot = () => {
return (
<WalletStack.Navigator screenOptions={{headerShown: false}}>
<WalletStack.Screen
name="WalletView"
component={WalletViewScreen}
/>
<WalletStack.Screen name="WalletInfo" component={Info} />
<WalletStack.Screen name="Send" component={Send} />
<WalletStack.Screen name="SendLN" component={SendLN} />
<WalletStack.Screen name="SendAmount" component={SendAmount} />
<WalletStack.Screen name="FeeSelection" component={FeeSelection} />
<WalletStack.Screen name="Receive" component={Receive} />
<WalletStack.Screen
name="RequestAmount"
component={RequestAmount}
/>
<WalletStack.Screen name="BoltNFC" component={BoltNFC} />
<WalletStack.Group screenOptions={{presentation: 'modal'}}>
<WalletStack.Screen name="WalletBackup" component={Backup} />
<WalletStack.Screen
name="AddressOwnership"
component={Ownership}
/>
<WalletStack.Screen
name="TransactionDetails"
component={TransactionDetails}
/>
<WalletStack.Screen
name="TransactionStatus"
component={TransactionStatus}
/>
<WalletStack.Screen
name="TransactionExported"
component={TransactionExported}
/>
<WalletStack.Screen name="WalletXpub" component={Xpub} />
<WalletStack.Screen name="SwapAmount" component={SwapAmount} />
<WalletStack.Screen name="SwapIn" component={SwapIn} />
<WalletStack.Screen name="SwapOut" component={SwapOut} />
</WalletStack.Group>
</WalletStack.Navigator>
);
};
const AddWalletStack = createNativeStackNavigator<AddWalletParamList>();
export const AddWalletRoot = () => {
return (
<AddWalletStack.Navigator screenOptions={{headerShown: false}}>
<AddWalletStack.Screen name="Add" component={Add} />
<AddWalletStack.Screen
name="RestoreActions"
component={RestoreActions}
/>
<AddWalletStack.Screen
name="CreateActions"
component={CreateActions}
/>
</AddWalletStack.Navigator>
);
};
// Create a navigation container reference
export const navigationRef = createNavigationContainerRef<InitStackParamList>();
export const rootNavigation = {
navigate<RouteName extends keyof InitStackParamList>(
...args: RouteName extends unknown
? undefined extends InitStackParamList[RouteName]
?
| [screen: RouteName]
| [
screen: RouteName,
params: InitStackParamList[RouteName],
]
: [screen: RouteName, params: InitStackParamList[RouteName]]
: never
): void {
if (navigationRef.isReady()) {
// Close any outstanding modals first
const currentRoute = navigationRef.current?.getCurrentRoute();
if (hasOpenedModals(currentRoute, modalRoutes)) {
navigationRef.current?.dispatch(StackActions.popToTop());
}
navigationRef.current?.navigate(...args);
} else {
// If navigation not ready
console.log('Navigation not ready');
}
},
};
const InitScreenStack = createNativeStackNavigator<InitStackParamList>();
const RootNavigator = (): ReactElement => {
const appState = useRef(AppState.currentState);
const renderCount = useRenderCount();
const {
onboarding,
wallets,
setOnboarding,
isAdvancedMode,
getWalletData,
currentWalletID,
isWalletInitialized,
mempoolInfo,
setBreezEvent,
setMempoolInfo,
} = useContext(AppStorageContext);
const walletState = useRef(wallets);
const onboardingState = useRef(onboarding);
const wallet = getWalletData(currentWalletID);
const BreezSub = useRef<any>(null);
const [triggerClipboardCheck, setTriggerClipboardCheck] = useState(false);
const [isAuth, setIsAuth] = useState(false);
const mempoolRef = useRef(
new WebSocket('wss://mempool.space/api/v1/ws'),
).current;
const {t} = useTranslation('wallet');
const ColorScheme = Color(useColorScheme());
let Theme = {
dark: ColorScheme.isDarkMode,
colors: {
...DefaultTheme.colors,
...ColorScheme.NavigatorTheme.colors,
},
};
// Clipboard check
const checkAndSetClipboard = async () => {
// We only display dialogs if content is not empty and valid invoice
const clipboardResult = await checkClipboardContents();
let clipboardMessage!: string;
// Set clipboard message
if (clipboardResult.invoiceType === 'lightning') {
clipboardMessage = t('read_clipboard_lightning_text', {
spec: clipboardResult.spec,
});
}
if (clipboardResult.invoiceType === ENet.Bitcoin) {
clipboardMessage = t('read_clipboard_bitcoin_text');
}
// Only check if clippy content exists, supported invoice type, & not in BoltNFC screen (scan trigger)
const currentRoute = navigationRef.current?.getCurrentRoute();
// If clipboard has contents, display dialog
if (
clipboardResult.hasContents &&
clipboardResult.invoiceType !== 'unsupported' &&
currentRoute?.name !== 'BoltNFC'
) {
actionAlert(
capitalizeFirst(t('clipboard')),
clipboardMessage,
capitalizeFirst(t('pay')),
capitalizeFirst(t('cancel')),
() => {
rootNavigation.navigate('PayInvoice', {
invoice: clipboardResult.content,
});
},
);
}
};
// Deep linking
// Triggers while app still open
const linking: LinkingOptions<{}> = {
prefixes: ['bitcoin', 'lightning'],
config: {
screens: {
PayInvoice: '',
},
},
subscribe(listener): () => void {
// Deep linking when app open
const onReceiveLink = ({url}: {url: string}) => {
if (!onboardingState.current && isAuth) {
rootNavigation.navigate('PayInvoice', {
invoice: url,
});
}
return listener(url);
};
// Listen to incoming links from deep linking
const subscription = Linking.addEventListener('url', onReceiveLink);
return () => {
// Clean up the event listeners
subscription?.remove();
};
},
};
// Check deep link & clipboard if app newly launched if app previously unopened
const checkDeepLinkAndClipboard = async (): Promise<void> => {
// Check deep link
const url = await Linking.getInitialURL();
const currentRoute = navigationRef.current?.getCurrentRoute();
// only check if url exists & not in BoltNFC screen (scan trigger)
if (url && currentRoute?.name !== 'BoltNFC') {
rootNavigation.navigate('PayInvoice', {invoice: url});
return;
}
// Check clipboard
checkAndSetClipboard();
};
const handleAuthSuccess = useCallback(() => {
if (triggerClipboardCheck) {
// Call clipboard
checkDeepLinkAndClipboard();
}
setIsAuth(true);
setTriggerClipboardCheck(false);
}, [triggerClipboardCheck]);
// Fetch and set Swap Info here
const initMempoolSock = async () => {
// Check network
const _netState = await netInfo.fetch();
if (!checkNetworkIsReachable(_netState)) {
return;
}
if (mempoolInfo.connected) {
console.log('[Mempool] WebSocket already connected');
return;
}
mempoolRef.onopen = () => {
console.log('[Mempool] WebSocket connected');
mempoolRef.send(
JSON.stringify({
action: 'want',
data: ['stats'],
}),
);
};
mempoolRef.onmessage = (error: any) => {
const _mempoolInfo = JSON.parse(error.data.toString()).mempoolInfo;
const _fees = JSON.parse(error.data.toString()).fees;
const mempoolUsage = _mempoolInfo?.usage;
const mempoolMax = _mempoolInfo?.maxmempool;
const feeEnv = _fees?.fastestFee
? _fees?.fastestFee
: mempoolInfo.fastestFee;
setMempoolInfo({
mempoolCongested: mempoolUsage / mempoolMax >= 2.5,
mempoolHighFeeEnv: feeEnv >= 150,
economyFee: _fees?.economyFee
? _fees?.economyFee
: mempoolInfo.economyFee,
fastestFee: _fees?.fastestFee
? _fees?.fastestFee
: mempoolInfo.fastestFee,
minimumFee: _fees?.minimumFee
? _fees?.minimumFee
: mempoolInfo.minimumFee,
hourFee: _fees?.hourFee ? _fees?.hourFee : mempoolInfo.hourFee,
halfHourFee: _fees?.halfHourFee
? _fees?.halfHourFee
: mempoolInfo.halfHourFee,
connected: true,
});
};
mempoolRef.onerror = (error: any) => {
console.log('[Mempool] (error)', error.message);
if (error.message.includes('not connected')) {
setMempoolInfo({
mempoolCongested: mempoolInfo.mempoolCongested,
mempoolHighFeeEnv: mempoolInfo.mempoolHighFeeEnv,
economyFee: mempoolInfo.economyFee,
fastestFee: mempoolInfo.fastestFee,
minimumFee: mempoolInfo.minimumFee,
hourFee: mempoolInfo.hourFee,
halfHourFee: mempoolInfo.halfHourFee,
connected: true,
});
}
};
};
// Breez startup
const initNode = async () => {
// Init LN connection
// No point putting in any effort if mnemonic missing
if (
wallet?.mnemonic.length === 0 &&
isWalletInitialized &&
wallet.type === 'unified' &&
onboarding
) {
return;
}
let restore_only = wallet.payments.length > 0 ? true : false;
// Get node info
try {
const info = await nodeInfo();
if (info?.id) {
console.log('[Breez SDK] Services already connected');
return;
}
} catch (error: any) {
if (process.env.NODE_ENV === 'development' && isAdvancedMode) {
Toast.show({
topOffset: 54,
type: 'Liberal',
text1: t('Breez SDK'),
text2: error.message,
visibilityTime: 2000,
});
}
}
// SDK events listener
const onBreezEvent = (event: BreezEvent) => {
if (event.type === BreezEventVariant.NEW_BLOCK) {
console.log('[Breez SDK] New Block');
}
if (event.type === BreezEventVariant.SYNCED) {
console.log('[Breez SDK] Synced');
}
if (event.type === BreezEventVariant.BACKUP_STARTED) {
if (process.env.NODE_ENV === 'development' && isAdvancedMode) {
Toast.show({
topOffset: 54,
type: 'Liberal',
text1: t('Breez SDK'),
text2: t('breez_backup_started'),
visibilityTime: 1750,
});
}
}
if (event.type === BreezEventVariant.BACKUP_SUCCEEDED) {
if (process.env.NODE_ENV === 'development' && isAdvancedMode) {
console.log('[Breez SDK] Backup succeeded');
Toast.show({
topOffset: 54,
type: 'Liberal',
text1: t('Breez SDK'),
text2: t('breez_backup_success'),
visibilityTime: 1750,
});
}
}
if (event.type === BreezEventVariant.BACKUP_FAILED) {
console.log('[Breez SDK] Backup Failed: ', event.details);
Toast.show({
topOffset: 54,
type: 'Liberal',
text1: t('Breez SDK'),
text2: t('breez_backup_failed'),
visibilityTime: 1750,
});
}
if (event.type === BreezEventVariant.INVOICE_PAID) {
console.log(
'[Breez SDK] Invoice Paid (Received Payment): ',
event.details,
);
// Handle navigation to LNTransactionStatus in Wallet Receive screen
setBreezEvent(event);
}
if (event.type === BreezEventVariant.PAYMENT_FAILED) {
console.log('[Breez SDK] Payment Failed: ', event.details);
// Handle navigation to LNTransactionStatus in Wallet Receive & Send screen
setBreezEvent(event);
}
if (event.type === BreezEventVariant.PAYMENT_SUCCEED) {
console.log('[Breez SDK] Payment Sent: ', event.details);
// Handle navigation to LNTransactionStatus in Wallet Send screen
setBreezEvent(event);
}
};
// Create the default config
const seed = await mnemonicToSeed(wallet.mnemonic);
// Breez SDK Greenlight credentials
// The key and cert are stored as hex strings in the .env file
// Then converted to byte arrays
const developerKey: number[] = Array.from(
Buffer.from(_GL_CUSTOM_NOBODY_KEY_, 'hex'),
);
const developerCert: number[] = Array.from(
Buffer.from(_GL_CUSTOM_NOBODY_CERT_, 'hex'),
);
const greenlightCredentials: GreenlightCredentials = {
developerKey,
developerCert,
};
const nodeConfig: NodeConfig = {
type: NodeConfigVariant.GREENLIGHT,
config: {
partnerCredentials: greenlightCredentials,
},
};
const config = await defaultConfig(
EnvironmentType.PRODUCTION,
_BREEZ_SDK_API_KEY_,
nodeConfig,
);
// Set directory for the wallet
const xpub256 = getXPub256(wallet.xpub);
config.workingDir = config.workingDir + `/volt/${xpub256}`;
const connectionRequest: ConnectRequest = {
config,
seed,
restoreOnly: restore_only,
};
try {
// Connect to the Breez SDK make it ready for use
BreezSub.current = await connect(connectionRequest, onBreezEvent);
console.log('[Breez SDK] Connected to services');
} catch (error: any) {
if (process.env.NODE_ENV === 'development' && isAdvancedMode) {
Toast.show({
topOffset: 54,
type: 'Liberal',
text1: t('Breez SDK'),
text2: error.message,
visibilityTime: 2000,
});
}
}
};
useEffect(() => {
// Block if newly onboarded
if (walletState.current.length === 0) {
return;
}
// Update if newly onboarded so we can check clippy and deep links later
if (onboarding) {
setOnboarding(false);
}
// Check for deep link if app newly launched
// Ensure that we have wallets before checking
if (renderCount <= 2 && !onboardingState.current) {
// Call on trigger for Lock comp
setTriggerClipboardCheck(true);
}
const appStateSub = AppState.addEventListener(
'change',
async (incomingState): Promise<void> => {
const currentRoute = navigationRef.current?.getCurrentRoute();
// Check whether we are in the pay invoice screen (i.e. handling deep link)
// and block clipboard check;
const isDeepLinkScreen = currentRoute?.name === 'PayInvoice';
// Check and run clipboard fn if app is active in foreground
// Ensure that we have wallets before checking
if (
appState.current.match(/background/) &&
incomingState === 'active' &&
!isDeepLinkScreen &&
!onboardingState.current
) {
checkAndSetClipboard();
}
// Update app state
appState.current = incomingState;
},
);
// Init LN services
// Call mempool
initNode();
initMempoolSock();
// Net event listener
// Subscribe
const NetInfoSub = netInfo.addEventListener(state => {
// fetch and set mempool info
// and Breez SDK connection
if (checkNetworkIsReachable(state)) {
console.log(
'[NetInfo] Attempt to (Re)connect to Breez & Mempool',
);
initNode();
initMempoolSock();
}
});
return () => {
// Kill subscription
BreezSub?.current?.remove();
appStateSub?.remove();
mempoolRef.close();
NetInfoSub();
};
}, []);
return (
<NavigationContainer
ref={navigationRef}
linking={linking}
theme={Theme}>
<InitScreenStack.Navigator
screenOptions={{headerShown: false}}
initialRouteName={'HomeScreen'}>
<InitScreenStack.Screen name="HomeScreen" component={Home} />
<InitScreenStack.Screen name="ScanRoot" component={ScanRoot} />
<InitScreenStack.Screen
name="LNTransactionStatus"
component={LNTransactionStatus}
/>
<InitScreenStack.Screen
name="PayInvoice"
component={PayInvoice}
/>
<InitScreenStack.Screen
name="AddWalletRoot"
component={AddWalletRoot}
options={{headerShown: false, presentation: 'modal'}}
/>
<InitScreenStack.Screen
name="WalletRoot"
component={WalletRoot}
/>
<InitScreenStack.Screen
name="SettingsRoot"
component={SettingsRoot}
/>
<InitScreenStack.Group screenOptions={{presentation: 'modal'}}>
<InitScreenStack.Screen
name="Mnemonic"
component={Mnemonic}
/>
<InitScreenStack.Screen
name="TransactionList"
component={TransactionList}
/>
</InitScreenStack.Group>
</InitScreenStack.Navigator>
{!isAuth && <LockScreen onSuccess={handleAuthSuccess} />}
</NavigationContainer>
);
};
export default memo(RootNavigator);