BlueWallet/screen/wallets/Add.tsx

536 lines
17 KiB
TypeScript
Raw Normal View History

2024-02-24 06:27:17 -05:00
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation } from '@react-navigation/native';
2024-05-31 13:18:01 -04:00
import React, { useEffect, useReducer } from 'react';
import {
ActivityIndicator,
2024-06-01 14:48:22 +01:00
Alert,
Keyboard,
KeyboardAvoidingView,
2024-04-03 12:24:31 -04:00
LayoutAnimation,
Platform,
2024-02-24 06:27:17 -05:00
ScrollView,
StyleSheet,
2024-02-24 06:27:17 -05:00
Text,
TextInput,
2021-09-27 13:18:06 -04:00
useColorScheme,
2024-05-20 10:54:13 +01:00
View,
} from 'react-native';
2024-03-15 23:05:15 +03:00
2024-05-20 10:54:13 +01:00
import A from '../../blue_modules/analytics';
2024-02-24 06:27:17 -05:00
import triggerHapticFeedback, { HapticFeedbackTypes } from '../../blue_modules/hapticFeedback';
2024-05-20 10:54:13 +01:00
import { BlueButtonLink, BlueFormLabel, BlueSpacing20, BlueSpacing40, BlueText } from '../../BlueComponents';
import { BlueApp, HDSegwitBech32Wallet, HDSegwitP2SHWallet, LightningCustodianWallet, SegwitP2SHWallet } from '../../class';
import presentAlert from '../../components/Alert';
2023-11-15 08:07:54 -04:00
import Button from '../../components/Button';
2023-12-16 17:44:35 -04:00
import ListItem from '../../components/ListItem';
2024-02-24 06:27:17 -05:00
import { useTheme } from '../../components/themes';
2024-05-20 10:54:13 +01:00
import WalletButton from '../../components/WalletButton';
2024-02-24 06:27:17 -05:00
import loc from '../../loc';
import { Chain } from '../../models/bitcoinUnits';
2024-05-31 13:18:01 -04:00
import { useStorage } from '../../hooks/context/useStorage';
import { useSettings } from '../../hooks/context/useSettings';
2023-12-14 14:40:43 -04:00
enum ButtonSelected {
// @ts-ignore: Return later to update
ONCHAIN = Chain.ONCHAIN,
// @ts-ignore: Return later to update
OFFCHAIN = Chain.OFFCHAIN,
VAULT = 'VAULT',
}
interface State {
isLoading: boolean;
walletBaseURI: string;
selectedIndex: number;
label: string;
selectedWalletType: ButtonSelected;
backdoorPressed: number;
2024-06-01 14:48:22 +01:00
entropy: Buffer | undefined;
2023-12-14 14:40:43 -04:00
entropyButtonText: string;
}
2023-12-16 15:08:53 -04:00
const ActionTypes = {
SET_LOADING: 'SET_LOADING',
SET_WALLET_BASE_URI: 'SET_WALLET_BASE_URI',
SET_SELECTED_INDEX: 'SET_SELECTED_INDEX',
SET_LABEL: 'SET_LABEL',
SET_SELECTED_WALLET_TYPE: 'SET_SELECTED_WALLET_TYPE',
INCREMENT_BACKDOOR_PRESSED: 'INCREMENT_BACKDOOR_PRESSED',
SET_ENTROPY: 'SET_ENTROPY',
SET_ENTROPY_BUTTON_TEXT: 'SET_ENTROPY_BUTTON_TEXT',
2023-12-16 15:09:12 -04:00
} as const;
2023-12-16 15:08:53 -04:00
type ActionTypes = (typeof ActionTypes)[keyof typeof ActionTypes];
2023-12-14 14:40:43 -04:00
interface Action {
2023-12-16 15:08:53 -04:00
type: ActionTypes;
2023-12-14 14:40:43 -04:00
payload?: any;
}
const initialState: State = {
isLoading: true,
walletBaseURI: '',
selectedIndex: 0,
label: '',
selectedWalletType: ButtonSelected.ONCHAIN,
backdoorPressed: 1,
entropy: undefined,
entropyButtonText: loc.wallets.add_entropy_provide,
};
2023-12-14 14:40:43 -04:00
const walletReducer = (state: State, action: Action): State => {
switch (action.type) {
2023-12-16 15:08:53 -04:00
case ActionTypes.SET_LOADING:
return { ...state, isLoading: action.payload };
2023-12-16 15:08:53 -04:00
case ActionTypes.SET_WALLET_BASE_URI:
return { ...state, walletBaseURI: action.payload };
2023-12-16 15:08:53 -04:00
case ActionTypes.SET_SELECTED_INDEX:
return { ...state, selectedIndex: action.payload };
2023-12-16 15:08:53 -04:00
case ActionTypes.SET_LABEL:
return { ...state, label: action.payload };
2023-12-16 15:08:53 -04:00
case ActionTypes.SET_SELECTED_WALLET_TYPE:
return { ...state, selectedWalletType: action.payload };
2023-12-16 15:08:53 -04:00
case ActionTypes.INCREMENT_BACKDOOR_PRESSED:
return { ...state, backdoorPressed: state.backdoorPressed + 1 };
2023-12-16 15:08:53 -04:00
case ActionTypes.SET_ENTROPY:
return { ...state, entropy: action.payload };
2023-12-16 15:08:53 -04:00
case ActionTypes.SET_ENTROPY_BUTTON_TEXT:
return { ...state, entropyButtonText: action.payload };
default:
return state;
}
};
2023-12-14 14:40:43 -04:00
const WalletsAdd: React.FC = () => {
const { colors } = useTheme();
// State
const [state, dispatch] = useReducer(walletReducer, initialState);
const isLoading = state.isLoading;
const walletBaseURI = state.walletBaseURI;
const selectedIndex = state.selectedIndex;
const label = state.label;
const selectedWalletType = state.selectedWalletType;
const entropy = state.entropy;
const entropyButtonText = state.entropyButtonText;
//
2023-10-20 11:15:54 -04:00
const colorScheme = useColorScheme();
const { addWallet, saveToDisk } = useStorage();
2024-04-17 21:05:48 -04:00
const { isAdvancedModeEnabled } = useSettings();
2023-10-20 11:15:54 -04:00
const { navigate, goBack, setOptions } = useNavigation();
const stylesHook = {
advancedText: {
color: colors.feeText,
},
label: {
borderColor: colors.formBorder,
borderBottomColor: colors.formBorder,
backgroundColor: colors.inputBackgroundColor,
},
noPadding: {
backgroundColor: colors.elevated,
},
root: {
backgroundColor: colors.elevated,
},
lndUri: {
borderColor: colors.formBorder,
borderBottomColor: colors.formBorder,
backgroundColor: colors.inputBackgroundColor,
},
2019-05-19 20:49:42 +01:00
};
useEffect(() => {
2024-04-15 21:53:44 +01:00
AsyncStorage.getItem(BlueApp.LNDHUB)
2023-12-14 14:40:43 -04:00
.then(url => (url ? setWalletBaseURI(url) : setWalletBaseURI('')))
2023-12-14 12:52:15 -04:00
.catch(() => setWalletBaseURI(''))
.finally(() => setIsLoading(false));
}, []);
2018-01-30 22:42:38 +00:00
2023-10-20 11:15:54 -04:00
useEffect(() => {
setOptions({
statusBarStyle: Platform.select({ ios: 'light', default: colorScheme === 'dark' ? 'light' : 'dark' }),
});
}, [colorScheme, setOptions]);
2024-06-01 14:48:22 +01:00
const entropyGenerated = (newEntropy: Buffer) => {
2020-06-29 15:58:43 +03:00
let entropyTitle;
if (!newEntropy) {
2020-07-20 16:38:46 +03:00
entropyTitle = loc.wallets.add_entropy_provide;
2020-06-29 15:58:43 +03:00
} else {
2024-06-01 14:48:22 +01:00
entropyTitle = loc.formatString(loc.wallets.add_entropy_bytes, {
bytes: newEntropy.length,
2020-06-29 15:58:43 +03:00
});
}
setEntropy(newEntropy);
setEntropyButtonText(entropyTitle);
};
2018-07-14 19:54:27 +01:00
2023-12-14 14:40:43 -04:00
const setIsLoading = (value: boolean) => {
dispatch({ type: 'SET_LOADING', payload: value });
};
2023-12-14 14:40:43 -04:00
const setWalletBaseURI = (value: string) => {
dispatch({ type: 'SET_WALLET_BASE_URI', payload: value });
};
2023-12-14 14:40:43 -04:00
const setSelectedIndex = (value: number) => {
dispatch({ type: 'SET_SELECTED_INDEX', payload: value });
};
2023-12-14 14:40:43 -04:00
const setLabel = (value: string) => {
dispatch({ type: 'SET_LABEL', payload: value });
};
2023-12-14 14:40:43 -04:00
const setSelectedWalletType = (value: ButtonSelected) => {
dispatch({ type: 'SET_SELECTED_WALLET_TYPE', payload: value });
};
2023-12-14 14:40:43 -04:00
const setBackdoorPressed = (value: number) => {
dispatch({ type: 'INCREMENT_BACKDOOR_PRESSED', payload: value });
};
2024-06-01 14:48:22 +01:00
const setEntropy = (value: Buffer) => {
dispatch({ type: 'SET_ENTROPY', payload: value });
};
2023-12-14 14:40:43 -04:00
const setEntropyButtonText = (value: string) => {
dispatch({ type: 'SET_ENTROPY_BUTTON_TEXT', payload: value });
};
const createWallet = async () => {
setIsLoading(true);
2020-08-07 07:31:01 -04:00
if (selectedWalletType === ButtonSelected.OFFCHAIN) {
2023-12-14 14:40:43 -04:00
createLightningWallet();
} else if (selectedWalletType === ButtonSelected.ONCHAIN) {
2023-12-14 14:40:43 -04:00
let w: HDSegwitBech32Wallet | SegwitP2SHWallet | HDSegwitP2SHWallet;
if (selectedIndex === 2) {
// zero index radio - HD segwit
w = new HDSegwitP2SHWallet();
w.setLabel(label || loc.wallets.details_title);
} else if (selectedIndex === 1) {
// btc was selected
// index 1 radio - segwit single address
w = new SegwitP2SHWallet();
w.setLabel(label || loc.wallets.details_title);
} else {
// btc was selected
// index 2 radio - hd bip84
w = new HDSegwitBech32Wallet();
w.setLabel(label || loc.wallets.details_title);
}
if (selectedWalletType === ButtonSelected.ONCHAIN) {
if (entropy) {
try {
await w.generateFromEntropy(entropy);
2023-12-14 14:40:43 -04:00
} catch (e: any) {
console.log(e.toString());
presentAlert({ message: e.toString() });
goBack();
return;
}
} else {
await w.generate();
}
addWallet(w);
await saveToDisk();
A(A.ENUM.CREATED_WALLET);
triggerHapticFeedback(HapticFeedbackTypes.NotificationSuccess);
if (w.type === HDSegwitP2SHWallet.type || w.type === HDSegwitBech32Wallet.type) {
2023-12-14 14:40:43 -04:00
// @ts-ignore: Return later to update
navigate('PleaseBackup', {
2020-10-29 05:26:39 -04:00
walletID: w.getID(),
});
} else {
goBack();
}
}
} else if (selectedWalletType === ButtonSelected.VAULT) {
setIsLoading(false);
2023-12-14 14:40:43 -04:00
// @ts-ignore: Return later to update
2021-01-09 23:43:40 -05:00
navigate('WalletsAddMultisig', { walletLabel: label.trim().length > 0 ? label : loc.multisig.default_label });
}
};
2023-12-14 14:40:43 -04:00
const createLightningWallet = async () => {
const wallet = new LightningCustodianWallet();
wallet.setLabel(label || loc.wallets.details_title);
try {
2021-07-08 13:39:03 -04:00
const lndhub = walletBaseURI?.trim();
if (lndhub) {
const isValidNodeAddress = await LightningCustodianWallet.isValidNodeAddress(lndhub);
if (isValidNodeAddress) {
wallet.setBaseURI(lndhub);
await wallet.init();
} else {
throw new Error('The provided node address is not valid LNDHub node.');
}
}
await wallet.createAccount();
await wallet.authorize();
2023-12-14 14:40:43 -04:00
} catch (Err: any) {
setIsLoading(false);
console.warn('lnd create failure', Err);
if (Err.message) {
return presentAlert({ message: Err.message });
} else {
return presentAlert({ message: loc.wallets.add_lndhub_error });
}
// giving app, not adding anything
}
A(A.ENUM.CREATED_LIGHTNING_WALLET);
await wallet.generate();
addWallet(wallet);
await saveToDisk();
A(A.ENUM.CREATED_WALLET);
triggerHapticFeedback(HapticFeedbackTypes.NotificationSuccess);
2023-12-14 14:40:43 -04:00
// @ts-ignore: Return later to update
navigate('PleaseBackupLNDHub', {
2020-12-02 20:36:48 -05:00
walletID: wallet.getID(),
});
};
2020-08-07 07:31:01 -04:00
const navigateToEntropy = () => {
2024-06-01 14:48:22 +01:00
Alert.alert(
loc.wallets.add_wallet_seed_length,
loc.wallets.add_wallet_seed_length_message,
[
{
text: loc._.cancel,
onPress: () => {},
style: 'default',
},
{
text: loc.wallets.add_wallet_seed_length_12,
onPress: () => {
// @ts-ignore: Return later to update
navigate('ProvideEntropy', { onGenerated: entropyGenerated, words: 12 });
},
style: 'default',
},
{
text: loc.wallets.add_wallet_seed_length_24,
onPress: () => {
// @ts-ignore: Return later to update
navigate('ProvideEntropy', { onGenerated: entropyGenerated, words: 24 });
},
style: 'default',
},
],
{ cancelable: true },
);
};
2020-08-07 07:31:01 -04:00
const navigateToImportWallet = () => {
2023-12-14 14:40:43 -04:00
// @ts-ignore: Return later to update
navigate('ImportWallet');
};
const handleOnVaultButtonPressed = () => {
2024-04-03 12:24:31 -04:00
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
2020-12-07 22:25:00 +00:00
Keyboard.dismiss();
setSelectedWalletType(ButtonSelected.VAULT);
};
const handleOnBitcoinButtonPressed = () => {
2024-04-03 12:24:31 -04:00
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
Keyboard.dismiss();
setSelectedWalletType(ButtonSelected.ONCHAIN);
};
2020-08-07 07:31:01 -04:00
const handleOnLightningButtonPressed = () => {
2024-04-03 12:24:31 -04:00
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
2023-12-14 14:40:43 -04:00
// @ts-ignore: Return later to update
setBackdoorPressed((prevState: number) => {
2021-09-09 12:00:11 +01:00
return prevState + 1;
});
Keyboard.dismiss();
setSelectedWalletType(ButtonSelected.OFFCHAIN);
};
return (
2023-11-22 00:25:37 -04:00
<ScrollView style={stylesHook.root} testID="ScrollView">
<BlueSpacing20 />
2023-12-14 14:40:43 -04:00
<KeyboardAvoidingView enabled behavior={Platform.OS === 'ios' ? 'padding' : undefined} keyboardVerticalOffset={62}>
<BlueFormLabel>{loc.wallets.add_wallet_name}</BlueFormLabel>
<View style={[styles.label, stylesHook.label]}>
<TextInput
testID="WalletNameInput"
value={label}
placeholderTextColor="#81868e"
2021-10-17 10:59:02 -04:00
placeholder={loc.wallets.add_placeholder}
onChangeText={setLabel}
style={styles.textInputCommon}
editable={!isLoading}
underlineColorAndroid="transparent"
/>
</View>
<BlueFormLabel>{loc.wallets.add_wallet_type}</BlueFormLabel>
<View style={styles.buttons}>
2024-04-03 12:24:31 -04:00
<WalletButton
buttonType="Bitcoin"
testID="ActivateBitcoinButton"
active={selectedWalletType === ButtonSelected.ONCHAIN}
onPress={handleOnBitcoinButtonPressed}
2024-04-03 12:24:31 -04:00
size={styles.button}
/>
2024-04-03 12:24:31 -04:00
<WalletButton
buttonType="Lightning"
active={selectedWalletType === ButtonSelected.OFFCHAIN}
onPress={handleOnLightningButtonPressed}
2024-04-03 12:24:31 -04:00
size={styles.button}
/>
2024-04-03 12:24:31 -04:00
<WalletButton
buttonType="Vault"
testID="ActivateVaultButton"
active={selectedWalletType === ButtonSelected.VAULT}
onPress={handleOnVaultButtonPressed}
2024-04-03 12:24:31 -04:00
size={styles.button}
/>
</View>
<View style={styles.advanced}>
{(() => {
2024-04-17 21:05:48 -04:00
if (selectedWalletType === ButtonSelected.ONCHAIN && isAdvancedModeEnabled) {
return (
<View>
<BlueSpacing20 />
<Text style={[styles.advancedText, stylesHook.advancedText]}>{loc.settings.advanced_options}</Text>
2023-12-16 17:44:35 -04:00
<ListItem
containerStyle={[styles.noPadding, stylesHook.noPadding]}
bottomDivider={false}
onPress={() => setSelectedIndex(0)}
title={HDSegwitBech32Wallet.typeReadable}
checkmark={selectedIndex === 0}
/>
2023-12-16 17:44:35 -04:00
<ListItem
containerStyle={[styles.noPadding, stylesHook.noPadding]}
bottomDivider={false}
onPress={() => setSelectedIndex(1)}
title={SegwitP2SHWallet.typeReadable}
checkmark={selectedIndex === 1}
/>
2023-12-16 17:44:35 -04:00
<ListItem
containerStyle={[styles.noPadding, stylesHook.noPadding]}
bottomDivider={false}
onPress={() => setSelectedIndex(2)}
title={HDSegwitP2SHWallet.typeReadable}
checkmark={selectedIndex === 2}
/>
</View>
);
2021-07-08 13:39:03 -04:00
} else if (selectedWalletType === ButtonSelected.OFFCHAIN) {
return (
<>
<BlueSpacing20 />
2020-09-21 21:53:28 -04:00
<Text style={[styles.advancedText, stylesHook.advancedText]}>{loc.settings.advanced_options}</Text>
<BlueSpacing20 />
2020-12-21 21:27:49 +03:00
<BlueText>{loc.wallets.add_lndhub}</BlueText>
<View style={[styles.lndUri, stylesHook.lndUri]}>
<TextInput
value={walletBaseURI}
onChangeText={setWalletBaseURI}
onSubmitEditing={Keyboard.dismiss}
2020-12-21 21:27:49 +03:00
placeholder={loc.wallets.add_lndhub_placeholder}
clearButtonMode="while-editing"
autoCapitalize="none"
textContentType="URL"
autoCorrect={false}
placeholderTextColor="#81868e"
style={styles.textInputCommon}
editable={!isLoading}
underlineColorAndroid="transparent"
/>
</View>
</>
);
}
})()}
2024-04-17 21:05:48 -04:00
{isAdvancedModeEnabled === true && selectedWalletType === ButtonSelected.ONCHAIN && !isLoading && (
2020-11-29 23:18:54 -05:00
<BlueButtonLink style={styles.import} title={entropyButtonText} onPress={navigateToEntropy} />
)}
2020-11-05 12:38:04 +01:00
<BlueSpacing20 />
{!isLoading ? (
<>
2023-11-15 08:07:54 -04:00
<Button
2021-07-08 13:39:03 -04:00
testID="Create"
title={loc.wallets.add_create}
2023-12-14 14:40:43 -04:00
disabled={
!selectedWalletType || (selectedWalletType === ButtonSelected.OFFCHAIN && (walletBaseURI ?? '').trim().length === 0)
}
2021-07-08 13:39:03 -04:00
onPress={createWallet}
/>
<BlueButtonLink
testID="ImportWallet"
style={styles.import}
title={loc.wallets.add_import_wallet}
onPress={navigateToImportWallet}
/>
<BlueSpacing40 />
</>
) : (
<ActivityIndicator />
)}
</View>
</KeyboardAvoidingView>
</ScrollView>
);
};
2018-03-18 02:48:23 +00:00
const styles = StyleSheet.create({
label: {
flexDirection: 'row',
borderWidth: 1,
borderBottomWidth: 0.5,
minHeight: 44,
height: 44,
marginHorizontal: 20,
alignItems: 'center',
marginVertical: 16,
borderRadius: 4,
},
textInputCommon: {
flex: 1,
marginHorizontal: 8,
color: '#81868e',
},
buttons: {
flexDirection: 'column',
marginHorizontal: 20,
marginTop: 16,
borderWidth: 0,
minHeight: 100,
},
button: {
width: '100%',
height: 'auto',
},
advanced: {
marginHorizontal: 20,
},
advancedText: {
fontWeight: '500',
},
lndUri: {
flexDirection: 'row',
borderWidth: 1,
borderBottomWidth: 0.5,
minHeight: 44,
height: 44,
alignItems: 'center',
marginVertical: 16,
borderRadius: 4,
},
import: {
marginVertical: 24,
},
noPadding: {
paddingHorizontal: 0,
},
});
export default WalletsAdd;