Use configured coin type for creating accounts (#100)

* Use configured coin type for creating accounts

* Resolve eslint warnings
This commit is contained in:
shreerang6921 2024-04-17 16:11:09 +05:30 committed by Nabarun Gogoi
parent 2adfffba55
commit b947dd1151
12 changed files with 55 additions and 50 deletions

View File

@ -203,6 +203,7 @@ const App = (): React.JSX.Element => {
name="Laconic" name="Laconic"
component={HomeScreen} component={HomeScreen}
options={{ options={{
// eslint-disable-next-line react/no-unstable-nested-components
headerTitle: () => <Text variant="titleLarge">Laconic Wallet</Text>, headerTitle: () => <Text variant="titleLarge">Laconic Wallet</Text>,
headerBackVisible: false, headerBackVisible: false,
}} }}
@ -211,6 +212,7 @@ const App = (): React.JSX.Element => {
name="SignMessage" name="SignMessage"
component={SignMessage} component={SignMessage}
options={{ options={{
// eslint-disable-next-line react/no-unstable-nested-components
headerTitle: () => <Text variant="titleLarge">Sign Message</Text>, headerTitle: () => <Text variant="titleLarge">Sign Message</Text>,
}} }}
/> />
@ -218,6 +220,7 @@ const App = (): React.JSX.Element => {
name="SignRequest" name="SignRequest"
component={SignRequest} component={SignRequest}
options={{ options={{
// eslint-disable-next-line react/no-unstable-nested-components
headerTitle: () => <Text variant="titleLarge">Sign Request</Text>, headerTitle: () => <Text variant="titleLarge">Sign Request</Text>,
}} }}
/> />
@ -225,6 +228,7 @@ const App = (): React.JSX.Element => {
name="InvalidPath" name="InvalidPath"
component={InvalidPath} component={InvalidPath}
options={{ options={{
// eslint-disable-next-line react/no-unstable-nested-components
headerTitle: () => <Text variant="titleLarge">Bad Request</Text>, headerTitle: () => <Text variant="titleLarge">Bad Request</Text>,
headerBackVisible: false, headerBackVisible: false,
}} }}
@ -233,7 +237,9 @@ const App = (): React.JSX.Element => {
name="WalletConnect" name="WalletConnect"
component={WalletConnect} component={WalletConnect}
options={{ options={{
// eslint-disable-next-line react/no-unstable-nested-components
headerTitle: () => <Text variant="titleLarge">WalletConnect</Text>, headerTitle: () => <Text variant="titleLarge">WalletConnect</Text>,
// eslint-disable-next-line react/no-unstable-nested-components
headerRight: () => ( headerRight: () => (
<Button <Button
onPress={() => { onPress={() => {

View File

@ -14,7 +14,6 @@ import AccountDetails from './AccountDetails';
import { useAccounts } from '../context/AccountsContext'; import { useAccounts } from '../context/AccountsContext';
import { web3wallet } from '../utils/wallet-connect/WalletConnectUtils'; import { web3wallet } from '../utils/wallet-connect/WalletConnectUtils';
import { useNetworks } from '../context/NetworksContext'; import { useNetworks } from '../context/NetworksContext';
import { EIP155 } from '../utils/constants';
import ConfirmDialog from './ConfirmDialog'; import ConfirmDialog from './ConfirmDialog';
import { getNamespaces } from '../utils/wallet-connect/helpers'; import { getNamespaces } from '../utils/wallet-connect/helpers';
@ -145,12 +144,7 @@ const Accounts = ({ currentIndex, updateIndex }: AccountsProps) => {
mode="contained" mode="contained"
onPress={() => { onPress={() => {
setHdDialog(true); setHdDialog(true);
// TODO: Use coin type while adding from HD path setPathCode(`m/44'/${selectedNetwork.coinType}'/`);
setPathCode(
selectedNetwork!.namespace === EIP155
? "m/44'/60'/"
: "m/44'/118'/",
);
}}> }}>
Add Account from HD path Add Account from HD path
</Button> </Button>

View File

@ -11,9 +11,9 @@ const NetworkDropdown = ({ updateNetwork }: NetworkDropdownProps) => {
const [expanded, setExpanded] = useState<boolean>(false); const [expanded, setExpanded] = useState<boolean>(false);
const handleNetworkPress = (networksData: NetworksDataState) => { const handleNetworkPress = (networkData: NetworksDataState) => {
updateNetwork(networksData); updateNetwork(networkData);
setSelectedNetwork(networksData); setSelectedNetwork(networkData);
setExpanded(false); setExpanded(false);
}; };

View File

@ -172,7 +172,7 @@ const PairingModal = ({
return ( return (
<Modal visible={visible} animationType="slide" transparent> <Modal visible={visible} animationType="slide" transparent>
<View style={{ flex: 1 }}> <View style={styles.modalOuterContainer}>
<View style={styles.modalContentContainer}> <View style={styles.modalContentContainer}>
<ScrollView showsVerticalScrollIndicator={true}> <ScrollView showsVerticalScrollIndicator={true}>
<View style={styles.container}> <View style={styles.container}>

View File

@ -156,7 +156,6 @@ const AddNetwork = () => {
}, [namespace, reset]); }, [namespace, reset]);
return ( return (
// TODO: get form data from json file
<ScrollView contentContainerStyle={styles.signPage}> <ScrollView contentContainerStyle={styles.signPage}>
<SelectNetworkType updateNetworkType={updateNetworkType} /> <SelectNetworkType updateNetworkType={updateNetworkType} />
@ -171,7 +170,7 @@ const AddNetwork = () => {
value={value} value={value}
label="Chain ID" label="Chain ID"
onBlur={onBlur} onBlur={onBlur}
onChangeText={value => onChange(value)} onChangeText={textValue => onChange(textValue)}
/> />
<HelperText type="error">{errors.chainId?.message}</HelperText> <HelperText type="error">{errors.chainId?.message}</HelperText>
</> </>
@ -188,7 +187,7 @@ const AddNetwork = () => {
label="Network Name" label="Network Name"
value={value} value={value}
onBlur={onBlur} onBlur={onBlur}
onChangeText={value => onChange(value)} onChangeText={textValue => onChange(textValue)}
/> />
<HelperText type="error">{errors.networkName?.message}</HelperText> <HelperText type="error">{errors.networkName?.message}</HelperText>
</> </>
@ -205,7 +204,7 @@ const AddNetwork = () => {
label="New RPC URL" label="New RPC URL"
onBlur={onBlur} onBlur={onBlur}
value={value} value={value}
onChangeText={value => onChange(value)} onChangeText={textValue => onChange(textValue)}
/> />
<HelperText type="error">{errors.rpcUrl?.message}</HelperText> <HelperText type="error">{errors.rpcUrl?.message}</HelperText>
</> </>
@ -223,7 +222,7 @@ const AddNetwork = () => {
value={value} value={value}
label="Block Explorer URL (Optional)" label="Block Explorer URL (Optional)"
onBlur={onBlur} onBlur={onBlur}
onChangeText={value => onChange(value)} onChangeText={textValue => onChange(textValue)}
/> />
<HelperText type="error"> <HelperText type="error">
{errors.blockExplorerUrl?.message} {errors.blockExplorerUrl?.message}
@ -260,7 +259,7 @@ const AddNetwork = () => {
value={value} value={value}
label="Currency Symbol" label="Currency Symbol"
onBlur={onBlur} onBlur={onBlur}
onChangeText={value => onChange(value)} onChangeText={textValue => onChange(textValue)}
/> />
<HelperText type="error"> <HelperText type="error">
{errors.currencySymbol?.message} {errors.currencySymbol?.message}
@ -281,7 +280,7 @@ const AddNetwork = () => {
value={value} value={value}
label="Native Denom" label="Native Denom"
onBlur={onBlur} onBlur={onBlur}
onChangeText={value => onChange(value)} onChangeText={textValue => onChange(textValue)}
/> />
<HelperText type="error"> <HelperText type="error">
{errors.nativeDenom?.message} {errors.nativeDenom?.message}
@ -300,7 +299,7 @@ const AddNetwork = () => {
value={value} value={value}
label="Address Prefix" label="Address Prefix"
onBlur={onBlur} onBlur={onBlur}
onChangeText={value => onChange(value)} onChangeText={textValue => onChange(textValue)}
/> />
<HelperText type="error"> <HelperText type="error">
{errors.addressPrefix?.message} {errors.addressPrefix?.message}

View File

@ -102,7 +102,7 @@ const AddSession = () => {
value={currentWCURI} value={currentWCURI}
numberOfLines={4} numberOfLines={4}
multiline={true} multiline={true}
style={{ padding: 10 }} style={styles.walletConnectUriText}
/> />
<View style={styles.signButton}> <View style={styles.signButton}>

View File

@ -175,7 +175,10 @@ const ApproveTransaction = ({ route }: SignRequestProps) => {
}; };
useEffect(() => { useEffect(() => {
const getAccountBalance = async (account: Account) => { const getAccountBalance = async () => {
if (!account) {
return;
}
if (namespace === EIP155) { if (namespace === EIP155) {
const fetchedBalance = const fetchedBalance =
provider && (await provider.getBalance(account.address)); provider && (await provider.getBalance(account.address));
@ -191,9 +194,7 @@ const ApproveTransaction = ({ route }: SignRequestProps) => {
} }
}; };
if (account) { getAccountBalance();
getAccountBalance(account);
}
}, [account, provider, namespace, cosmosStargateClient, requestedChain]); }, [account, provider, namespace, cosmosStargateClient, requestedChain]);
useEffect(() => { useEffect(() => {

View File

@ -22,7 +22,7 @@ import { useNetworks } from '../context/NetworksContext';
const WCLogo = () => { const WCLogo = () => {
return ( return (
<Image <Image
style={{ width: 24, height: 15, margin: 0 }} style={styles.walletConnectLogo}
source={require('../assets/WalletConnect-Icon-Blueberry.png')} source={require('../assets/WalletConnect-Icon-Blueberry.png')}
/> />
); );
@ -40,6 +40,7 @@ const HomeScreen = () => {
useEffect(() => { useEffect(() => {
if (accounts.length > 0) { if (accounts.length > 0) {
navigation.setOptions({ navigation.setOptions({
// eslint-disable-next-line react/no-unstable-nested-components
headerRight: () => ( headerRight: () => (
<Button onPress={() => navigation.navigate('WalletConnect')}> <Button onPress={() => navigation.navigate('WalletConnect')}>
{<WCLogo />} {<WCLogo />}
@ -107,8 +108,8 @@ const HomeScreen = () => {
hideResetDialog(); hideResetDialog();
}; };
const updateNetwork = (networksData: NetworksDataState) => { const updateNetwork = (networkData: NetworksDataState) => {
setSelectedNetwork(networksData); setSelectedNetwork(networkData);
setCurrentIndex(0); setCurrentIndex(0);
}; };

View File

@ -106,12 +106,12 @@ const SignRequest = ({ route }: SignRequestProps) => {
const regex = /^\/sign\/(eip155|cosmos)\/(.+)\/(.+)\/(.+)$/; const regex = /^\/sign\/(eip155|cosmos)\/(.+)\/(.+)\/(.+)$/;
const match = path.match(regex); const match = path.match(regex);
if (match) { if (match) {
const [, namespace, chainId, address, message] = match; const [, pathNamespace, pathChainId, pathAddress, pathMessage] = match;
return { return {
namespace, namespace: pathNamespace,
chainId, chainId: pathChainId,
address, address: pathAddress,
message, message: pathMessage,
}; };
} else { } else {
navigation.navigate('InvalidPath'); navigation.navigate('InvalidPath');

View File

@ -31,18 +31,19 @@ export default function WalletConnect() {
<View> <View>
{Object.keys(activeSessions).length > 0 ? ( {Object.keys(activeSessions).length > 0 ? (
<> <>
<View style={{ marginLeft: 12, marginTop: 12 }}> <View style={styles.sessionsContainer}>
<Text variant="titleMedium">Active Sessions</Text> <Text variant="titleMedium">Active Sessions</Text>
</View> </View>
<List.Section> <List.Section>
{Object.entries(activeSessions).map(([sessionId, session]) => ( {Object.entries(activeSessions).map(([sessionId, session]) => (
<List.Item <List.Item
style={{ paddingLeft: 12, borderBottomWidth: 0.5 }} style={styles.sessionItem}
key={sessionId} key={sessionId}
title={`${session.peer.metadata.name}`} title={`${session.peer.metadata.name}`}
descriptionNumberOfLines={7} descriptionNumberOfLines={7}
//TODO: Refactor
description={`${sessionId} \n\n${session.peer.metadata.url}\n\n${session.peer.metadata.description}`} description={`${sessionId} \n\n${session.peer.metadata.url}\n\n${session.peer.metadata.description}`}
// reference: https://github.com/react-navigation/react-navigation/issues/11371#issuecomment-1546543183
// eslint-disable-next-line react/no-unstable-nested-components
left={() => ( left={() => (
<> <>
{session.peer.metadata.icons[0].endsWith('.svg') ? ( {session.peer.metadata.icons[0].endsWith('.svg') ? (
@ -61,10 +62,11 @@ export default function WalletConnect() {
)} )}
</> </>
)} )}
// eslint-disable-next-line react/no-unstable-nested-components
right={() => ( right={() => (
<TouchableOpacity <TouchableOpacity
onPress={() => disconnect(sessionId)} onPress={() => disconnect(sessionId)}
style={{ display: 'flex', justifyContent: 'center' }}> style={styles.disconnectSession}>
<List.Icon icon="close" /> <List.Icon icon="close" />
</TouchableOpacity> </TouchableOpacity>
)} )}
@ -73,7 +75,7 @@ export default function WalletConnect() {
</List.Section> </List.Section>
</> </>
) : ( ) : (
<View style={{ display: 'flex', alignItems: 'center', marginTop: 12 }}> <View style={styles.noActiveSessions}>
<Text>You have no active sessions</Text> <Text>You have no active sessions</Text>
</View> </View>
)} )}

View File

@ -178,6 +178,7 @@ const styles = StyleSheet.create({
backgroundColor: 'white', backgroundColor: 'white',
bottom: 0, bottom: 0,
}, },
modalOuterContainer: { flex: 1 },
dappLogo: { dappLogo: {
width: 50, width: 50,
height: 50, height: 50,
@ -258,6 +259,12 @@ const styles = StyleSheet.create({
balancePadding: { balancePadding: {
padding: 8, padding: 8,
}, },
noActiveSessions: { display: 'flex', alignItems: 'center', marginTop: 12 },
disconnectSession: { display: 'flex', justifyContent: 'center' },
sessionItem: { paddingLeft: 12, borderBottomWidth: 0.5 },
sessionsContainer: { paddingLeft: 12, borderBottomWidth: 0.5 },
walletConnectUriText: { padding: 10 },
walletConnectLogo: { width: 24, height: 15, margin: 0 },
}); });
export default styles; export default styles;

View File

@ -97,10 +97,7 @@ const addAccountFromHDPath = async (
networkData: NetworksDataState, networkData: NetworksDataState,
): Promise<Account | undefined> => { ): Promise<Account | undefined> => {
try { try {
const account = await accountInfoFromHDPath( const account = await accountInfoFromHDPath(hdPath, networkData);
hdPath,
networkData.addressPrefix,
);
if (!account) { if (!account) {
throw new Error('Error while creating account'); throw new Error('Error while creating account');
} }
@ -243,7 +240,7 @@ const resetWallet = async () => {
const accountInfoFromHDPath = async ( const accountInfoFromHDPath = async (
hdPath: string, hdPath: string,
prefix: string = COSMOS, networkData: NetworksDataState,
): Promise< ): Promise<
{ privKey: string; pubKey: string; address: string } | undefined { privKey: string; pubKey: string; address: string } | undefined
> => { > => {
@ -259,18 +256,16 @@ const accountInfoFromHDPath = async (
const privKey = node.privateKey; const privKey = node.privateKey;
const pubKey = node.publicKey; const pubKey = node.publicKey;
const parts = hdPath.split('/');
const coinType = parts[2];
let address: string; let address: string;
switch (coinType) { switch (networkData.namespace) {
case "60'": case EIP155:
address = node.address; address = node.address;
break; break;
case "118'": case COSMOS:
address = (await getCosmosAccounts(mnemonic, hdPath, prefix)).data address = (
.address; await getCosmosAccounts(mnemonic, hdPath, networkData.addressPrefix)
).data.address;
break; break;
default: default:
throw new Error('Invalid wallet type'); throw new Error('Invalid wallet type');