forked from cerc-io/laconic-wallet
Refactor code for WalletConnect Integration (#59)
* Disconnect pairing request when app is reset * Move files to respective folders * Add comments to describe flow * Add new line * remove request session context * Fix imports * Move hook to folder * Add undefined type * Move types to src * Move util functions to correct files * Remove typeroots from tsconfig --------- Co-authored-by: Adw8 <adwait@deepstacksoft.com>
This commit is contained in:
parent
63faa74e2c
commit
8ed4c33beb
@ -4,7 +4,7 @@
|
||||
|
||||
import 'react-native';
|
||||
import React from 'react';
|
||||
import App from '../App';
|
||||
import App from '../src/App';
|
||||
|
||||
// Note: import explicitly to use the types shipped with jest.
|
||||
import {it} from '@jest/globals';
|
||||
|
6
index.js
6
index.js
@ -5,9 +5,9 @@ import { PaperProvider } from 'react-native-paper';
|
||||
|
||||
import { NavigationContainer } from '@react-navigation/native';
|
||||
|
||||
import App from './App';
|
||||
import { AccountsProvider } from './context/AccountsContext';
|
||||
import { WalletConnectProvider } from './context/WalletConnectContext';
|
||||
import App from './src/App';
|
||||
import { AccountsProvider } from './src/context/AccountsContext';
|
||||
import { WalletConnectProvider } from './src/context/WalletConnectContext';
|
||||
import { name as appName } from './app.json';
|
||||
|
||||
export default function Main() {
|
||||
|
@ -9,20 +9,22 @@ import {
|
||||
NativeStackNavigationProp,
|
||||
createNativeStackNavigator,
|
||||
} from '@react-navigation/native-stack';
|
||||
import { getSdkError } from '@walletconnect/utils';
|
||||
import { Web3WalletTypes } from '@walletconnect/web3wallet';
|
||||
|
||||
import SignMessage from './components/SignMessage';
|
||||
import HomeScreen from './components/HomeScreen';
|
||||
import SignRequest from './components/SignRequest';
|
||||
import InvalidPath from './components/InvalidPath';
|
||||
import PairingModal from './components/PairingModal';
|
||||
import AddSession from './components/AddSession';
|
||||
import WalletConnect from './components/WalletConnect';
|
||||
import { useWalletConnect } from './context/WalletConnectContext';
|
||||
import { useAccounts } from './context/AccountsContext';
|
||||
import InvalidPath from './screens/InvalidPath';
|
||||
import SignMessage from './screens/SignMessage';
|
||||
import HomeScreen from './screens/HomeScreen';
|
||||
import SignRequest from './screens/SignRequest';
|
||||
import AddSession from './screens/AddSession';
|
||||
import WalletConnect from './screens/WalletConnect';
|
||||
import { StackParamsList } from './types';
|
||||
import { web3wallet } from './utils/wallet-connect/WalletConnectUtils';
|
||||
import { EIP155_SIGNING_METHODS } from './utils/wallet-connect/EIP155Lib';
|
||||
import { getSignParamsMessage } from './utils/wallet-connect/Helpers';
|
||||
import { useWalletConnect } from './context/WalletConnectContext';
|
||||
|
||||
const Stack = createNativeStackNavigator<StackParamsList>();
|
||||
|
||||
@ -30,9 +32,8 @@ const App = (): React.JSX.Element => {
|
||||
const navigation =
|
||||
useNavigation<NativeStackNavigationProp<StackParamsList>>();
|
||||
|
||||
const { requestSession, setRequestSession, setActiveSessions } =
|
||||
useWalletConnect();
|
||||
|
||||
const { setActiveSessions } = useWalletConnect();
|
||||
const { accounts } = useAccounts();
|
||||
const [modalVisible, setModalVisible] = useState(false);
|
||||
const [toastVisible, setToastVisible] = useState(false);
|
||||
const [currentProposal, setCurrentProposal] = useState<
|
||||
@ -40,11 +41,19 @@ const App = (): React.JSX.Element => {
|
||||
>();
|
||||
|
||||
const onSessionProposal = useCallback(
|
||||
(proposal: SignClientTypes.EventArguments['session_proposal']) => {
|
||||
async (proposal: SignClientTypes.EventArguments['session_proposal']) => {
|
||||
if (!accounts.ethAccounts.length || !accounts.cosmosAccounts.length) {
|
||||
const { id } = proposal;
|
||||
await web3wallet!.rejectSession({
|
||||
id,
|
||||
reason: getSdkError('UNSUPPORTED_ACCOUNTS'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
setModalVisible(true);
|
||||
setCurrentProposal(proposal);
|
||||
},
|
||||
[],
|
||||
[accounts.ethAccounts, accounts.cosmosAccounts],
|
||||
);
|
||||
|
||||
const onSessionRequest = useCallback(
|
||||
@ -53,10 +62,7 @@ const App = (): React.JSX.Element => {
|
||||
const { request } = params;
|
||||
|
||||
const requestSessionData =
|
||||
web3wallet.engine.signClient.session.get(topic);
|
||||
|
||||
setRequestSession(requestSessionData);
|
||||
|
||||
web3wallet!.engine.signClient.session.get(topic);
|
||||
switch (request.method) {
|
||||
case EIP155_SIGNING_METHODS.PERSONAL_SIGN:
|
||||
navigation.navigate('SignRequest', {
|
||||
@ -64,7 +70,7 @@ const App = (): React.JSX.Element => {
|
||||
address: request.params[1],
|
||||
message: getSignParamsMessage(request.params),
|
||||
requestEvent,
|
||||
requestSession,
|
||||
requestSessionData,
|
||||
});
|
||||
|
||||
break;
|
||||
@ -90,7 +96,7 @@ const App = (): React.JSX.Element => {
|
||||
address: request.params.signerAddress,
|
||||
message: JSON.stringify(message, undefined, 2),
|
||||
requestEvent,
|
||||
requestSession,
|
||||
requestSessionData,
|
||||
});
|
||||
|
||||
break;
|
||||
@ -100,7 +106,7 @@ const App = (): React.JSX.Element => {
|
||||
address: request.params.signerAddress,
|
||||
message: request.params.signDoc.memo,
|
||||
requestEvent,
|
||||
requestSession,
|
||||
requestSessionData,
|
||||
});
|
||||
|
||||
break;
|
||||
@ -108,13 +114,13 @@ const App = (): React.JSX.Element => {
|
||||
throw new Error('Invalid method');
|
||||
}
|
||||
},
|
||||
[requestSession, setRequestSession, navigation],
|
||||
[navigation],
|
||||
);
|
||||
|
||||
const onSessionDelete = useCallback(() => {
|
||||
let sessions = web3wallet?.getActiveSessions();
|
||||
const sessions = web3wallet!.getActiveSessions();
|
||||
setActiveSessions(sessions);
|
||||
}, []);
|
||||
}, [setActiveSessions]);
|
||||
|
||||
useEffect(() => {
|
||||
web3wallet?.on('session_proposal', onSessionProposal);
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
@ -54,38 +54,48 @@ const Accounts = ({
|
||||
|
||||
useEffect(() => {
|
||||
const updateSessions = async () => {
|
||||
const sessions = web3wallet?.getActiveSessions() || {};
|
||||
const sessions = (web3wallet && web3wallet.getActiveSessions()) || {};
|
||||
// Iterate through each session
|
||||
|
||||
for (const topic in sessions) {
|
||||
const session = sessions[topic];
|
||||
const requiredNamespaces = session.requiredNamespaces;
|
||||
const namespaces = session.namespaces;
|
||||
|
||||
// Check if EIP155 namespace exists and Ethereum accounts have changed
|
||||
if (
|
||||
namespaces.hasOwnProperty('eip155') &&
|
||||
prevEthAccountsRef !== accounts.ethAccounts
|
||||
) {
|
||||
// Iterate through each chain ID in required EIP155 namespaces
|
||||
requiredNamespaces.eip155.chains?.forEach(chainId => {
|
||||
// Update Ethereum accounts in namespaces with chain prefix
|
||||
namespaces.eip155.accounts = accounts.ethAccounts.map(
|
||||
ethAccount => `${chainId}:${ethAccount.address}`,
|
||||
);
|
||||
});
|
||||
await web3wallet.updateSession({ topic, namespaces });
|
||||
// update session with modified namespace
|
||||
await web3wallet!.updateSession({ topic, namespaces });
|
||||
}
|
||||
|
||||
// Check if Cosmos namespace exists and Cosmos accounts have changed
|
||||
if (
|
||||
namespaces.hasOwnProperty('cosmos') &&
|
||||
prevCosmosAccountsRef !== accounts.cosmosAccounts
|
||||
) {
|
||||
// Iterate through each chain ID in required Cosmos namespaces
|
||||
requiredNamespaces?.cosmos.chains?.forEach(chainId => {
|
||||
// Iterate through each chain ID in required Cosmos namespaces
|
||||
namespaces.cosmos.accounts = accounts.cosmosAccounts.map(
|
||||
cosmosAccount => `${chainId}:${cosmosAccount.address}`,
|
||||
);
|
||||
});
|
||||
await web3wallet.updateSession({ topic, namespaces });
|
||||
// update session with modified namespace
|
||||
await web3wallet!.updateSession({ topic, namespaces });
|
||||
}
|
||||
}
|
||||
};
|
||||
// Call the updateSessions function when the 'accounts' dependency changes
|
||||
updateSessions();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [accounts]);
|
@ -137,13 +137,13 @@ const PairingModal = ({
|
||||
};
|
||||
});
|
||||
|
||||
await web3wallet.approveSession({
|
||||
await web3wallet!.approveSession({
|
||||
id,
|
||||
relayProtocol: relays[0].protocol,
|
||||
namespaces,
|
||||
});
|
||||
|
||||
const sessions = web3wallet.getActiveSessions();
|
||||
const sessions = web3wallet!.getActiveSessions();
|
||||
setActiveSessions(sessions);
|
||||
setModalVisible(false);
|
||||
setToastVisible(true);
|
||||
@ -159,7 +159,7 @@ const PairingModal = ({
|
||||
const handleReject = async () => {
|
||||
if (currentProposal) {
|
||||
const { id } = currentProposal;
|
||||
await web3wallet.rejectSession({
|
||||
await web3wallet!.rejectSession({
|
||||
id,
|
||||
reason: getSdkError('USER_REJECTED_METHODS'),
|
||||
});
|
@ -3,13 +3,10 @@ import React, { createContext, useContext, useEffect, useState } from 'react';
|
||||
import { SessionTypes } from '@walletconnect/types';
|
||||
|
||||
import { WalletConnectContextProps } from '../types';
|
||||
import useInitialization, {
|
||||
web3wallet,
|
||||
} from '../utils/wallet-connect/WalletConnectUtils';
|
||||
import { web3wallet } from '../utils/wallet-connect/WalletConnectUtils';
|
||||
import useInitialization from '../hooks/useInitialization';
|
||||
|
||||
const WalletConnectContext = createContext<WalletConnectContextProps>({
|
||||
requestSession: {},
|
||||
setRequestSession: () => {},
|
||||
activeSessions: {},
|
||||
setActiveSessions: () => {},
|
||||
});
|
||||
@ -23,11 +20,10 @@ const WalletConnectProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
useInitialization();
|
||||
|
||||
useEffect(() => {
|
||||
const sessions = web3wallet?.getActiveSessions() ?? {};
|
||||
const sessions = (web3wallet && web3wallet.getActiveSessions()) || {};
|
||||
setActiveSessions(sessions);
|
||||
}, []);
|
||||
|
||||
const [requestSession, setRequestSession] = useState<any>({});
|
||||
const [activeSessions, setActiveSessions] = useState<
|
||||
Record<string, SessionTypes.Struct>
|
||||
>({});
|
||||
@ -35,8 +31,6 @@ const WalletConnectProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
return (
|
||||
<WalletConnectContext.Provider
|
||||
value={{
|
||||
requestSession,
|
||||
setRequestSession,
|
||||
activeSessions,
|
||||
setActiveSessions,
|
||||
}}>
|
23
src/hooks/useInitialization.ts
Normal file
23
src/hooks/useInitialization.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { createWeb3Wallet } from '../utils/wallet-connect/WalletConnectUtils';
|
||||
|
||||
export default function useInitialization() {
|
||||
const [initialized, setInitialized] = useState(false);
|
||||
|
||||
const onInitialize = useCallback(async () => {
|
||||
try {
|
||||
await createWeb3Wallet();
|
||||
setInitialized(true);
|
||||
} catch (err: unknown) {
|
||||
console.log('Error for initializing', err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialized) {
|
||||
onInitialize();
|
||||
}
|
||||
}, [initialized, onInitialize]);
|
||||
|
||||
return initialized;
|
||||
}
|
@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react';
|
||||
|
||||
export function usePrevious<T>(value: T): T | undefined {
|
||||
const ref = useRef(value);
|
||||
|
||||
useEffect(() => {
|
||||
ref.current = value;
|
||||
}, [value]);
|
@ -7,11 +7,11 @@ import { useNavigation } from '@react-navigation/native';
|
||||
import { getSdkError } from '@walletconnect/utils';
|
||||
|
||||
import { createWallet, resetWallet, retrieveAccounts } from '../utils/accounts';
|
||||
import { DialogComponent } from './Dialog';
|
||||
import { NetworkDropdown } from './NetworkDropdown';
|
||||
import Accounts from './Accounts';
|
||||
import CreateWallet from './CreateWallet';
|
||||
import ResetWalletDialog from './ResetWalletDialog';
|
||||
import { DialogComponent } from '../components/Dialog';
|
||||
import { NetworkDropdown } from '../components/NetworkDropdown';
|
||||
import Accounts from '../components/Accounts';
|
||||
import CreateWallet from '../components/CreateWallet';
|
||||
import ResetWalletDialog from '../components/ResetWalletDialog';
|
||||
import styles from '../styles/stylesheet';
|
||||
import { useAccounts } from '../context/AccountsContext';
|
||||
import { useWalletConnect } from '../context/WalletConnectContext';
|
@ -7,7 +7,7 @@ import { NativeStackScreenProps } from '@react-navigation/native-stack';
|
||||
import { StackParamsList } from '../types';
|
||||
import styles from '../styles/stylesheet';
|
||||
import { signMessage } from '../utils/sign-message';
|
||||
import AccountDetails from './AccountDetails';
|
||||
import AccountDetails from '../components/AccountDetails';
|
||||
|
||||
type SignProps = NativeStackScreenProps<StackParamsList, 'SignMessage'>;
|
||||
|
@ -10,22 +10,20 @@ import {
|
||||
import { getHeaderTitle } from '@react-navigation/elements';
|
||||
|
||||
import { Account, StackParamsList } from '../types';
|
||||
import AccountDetails from './AccountDetails';
|
||||
import AccountDetails from '../components/AccountDetails';
|
||||
import styles from '../styles/stylesheet';
|
||||
import { signMessage } from '../utils/sign-message';
|
||||
import { retrieveSingleAccount } from '../utils/accounts';
|
||||
import {
|
||||
approveWalletConnectRequest,
|
||||
rejectEIP155Request,
|
||||
rejectWalletConnectRequest,
|
||||
} from '../utils/wallet-connect/WalletConnectRequests';
|
||||
import { web3wallet } from '../utils/wallet-connect/WalletConnectUtils';
|
||||
import { useWalletConnect } from '../context/WalletConnectContext';
|
||||
|
||||
type SignRequestProps = NativeStackScreenProps<StackParamsList, 'SignRequest'>;
|
||||
|
||||
const SignRequest = ({ route }: SignRequestProps) => {
|
||||
const { requestSession } = useWalletConnect();
|
||||
|
||||
const requestSession = route.params?.requestSessionData;
|
||||
const requestName = requestSession?.peer?.metadata?.name;
|
||||
const requestIcon = requestSession?.peer?.metadata?.icons[0];
|
||||
const requestURL = requestSession?.peer?.metadata?.url;
|
||||
@ -159,7 +157,7 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
||||
|
||||
const rejectRequestHandler = async () => {
|
||||
if (route.params?.requestEvent) {
|
||||
const response = rejectEIP155Request(route.params?.requestEvent);
|
||||
const response = rejectWalletConnectRequest(route.params?.requestEvent);
|
||||
const { topic } = route.params?.requestEvent;
|
||||
await web3wallet.respondSessionRequest({
|
||||
topic,
|
||||
@ -169,6 +167,7 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
||||
navigation.navigate('Laconic');
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
navigation.setOptions({
|
||||
// eslint-disable-next-line react/no-unstable-nested-components
|
||||
header: ({ options, back }) => {
|
||||
@ -189,6 +188,8 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
||||
);
|
||||
},
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [navigation, route.name]);
|
||||
|
||||
return (
|
||||
<>
|
@ -10,7 +10,7 @@ export type StackParamsList = {
|
||||
address: string;
|
||||
message: string;
|
||||
requestEvent?: Web3WalletTypes.SessionRequest;
|
||||
requestSession?: any;
|
||||
requestSessionData?: SessionTypes.Struct;
|
||||
}
|
||||
| undefined;
|
||||
InvalidPath: undefined;
|
||||
@ -101,17 +101,7 @@ export interface PairingModalProps {
|
||||
setToastVisible: (arg1: boolean) => void;
|
||||
}
|
||||
|
||||
export interface SignModalProps {
|
||||
visible: boolean;
|
||||
setModalVisible: (arg1: boolean) => void;
|
||||
requestSession: any;
|
||||
requestEvent: SignClientTypes.EventArguments['session_request'] | undefined;
|
||||
currentEthAddresses: string[];
|
||||
}
|
||||
|
||||
export interface WalletConnectContextProps {
|
||||
requestSession: any;
|
||||
setRequestSession: (requestSession: any) => void;
|
||||
activeSessions: Record<string, SessionTypes.Struct>;
|
||||
setActiveSessions: (
|
||||
activeSessions: Record<string, SessionTypes.Struct>,
|
@ -12,19 +12,18 @@ import {
|
||||
getInternetCredentials,
|
||||
} from 'react-native-keychain';
|
||||
|
||||
import { Secp256k1HdWallet } from '@cosmjs/amino';
|
||||
import { AccountData } from '@cosmjs/proto-signing';
|
||||
import { stringToPath } from '@cosmjs/crypto';
|
||||
|
||||
import { Account, WalletDetails } from '../types';
|
||||
import {
|
||||
accountInfoFromHDPath,
|
||||
getAddress,
|
||||
getCosmosAccounts,
|
||||
getHDPath,
|
||||
getMnemonic,
|
||||
getNextAccountId,
|
||||
getPathKey,
|
||||
resetKeyServers,
|
||||
updateAccountIndices,
|
||||
updateGlobalCounter,
|
||||
} from './utils';
|
||||
} from './misc';
|
||||
|
||||
const createWallet = async (): Promise<WalletDetails> => {
|
||||
try {
|
||||
@ -240,6 +239,105 @@ const resetWallet = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const accountInfoFromHDPath = async (
|
||||
hdPath: string,
|
||||
): Promise<
|
||||
| { privKey: string; pubKey: string; address: string; network: string }
|
||||
| undefined
|
||||
> => {
|
||||
const mnemonicStore = await getInternetCredentials('mnemonicServer');
|
||||
if (!mnemonicStore) {
|
||||
throw new Error('Mnemonic not found!');
|
||||
}
|
||||
|
||||
const mnemonic = mnemonicStore.password;
|
||||
const hdNode = HDNode.fromMnemonic(mnemonic);
|
||||
const node = hdNode.derivePath(hdPath);
|
||||
|
||||
const privKey = node.privateKey;
|
||||
const pubKey = node.publicKey;
|
||||
|
||||
const parts = hdPath.split('/');
|
||||
const path = parts.slice(-3).join('/');
|
||||
const coinType = parts[2];
|
||||
|
||||
let network: string;
|
||||
let address: string;
|
||||
|
||||
switch (coinType) {
|
||||
case "60'":
|
||||
network = 'eth';
|
||||
address = node.address;
|
||||
break;
|
||||
case "118'":
|
||||
network = 'cosmos';
|
||||
address = (await getCosmosAccounts(mnemonic, path)).data.address;
|
||||
break;
|
||||
default:
|
||||
throw new Error('Invalid wallet type');
|
||||
}
|
||||
return { privKey, pubKey, address, network };
|
||||
};
|
||||
|
||||
const getNextAccountId = async (network: string): Promise<number> => {
|
||||
const idStore = await getInternetCredentials(`${network}:accountIndices`);
|
||||
if (!idStore) {
|
||||
throw new Error('Account id not found');
|
||||
}
|
||||
|
||||
const accountIds = idStore.password;
|
||||
const ids = accountIds.split(',').map(Number);
|
||||
return ids[ids.length - 1] + 1;
|
||||
};
|
||||
|
||||
const updateAccountIndices = async (
|
||||
network: string,
|
||||
id: number,
|
||||
): Promise<void> => {
|
||||
const idStore = await getInternetCredentials(`${network}:accountIndices`);
|
||||
if (!idStore) {
|
||||
throw new Error('Account id not found');
|
||||
}
|
||||
|
||||
const updatedIndices = `${idStore.password},${id.toString()}`;
|
||||
await resetInternetCredentials(`${network}:accountIndices`);
|
||||
await setInternetCredentials(
|
||||
`${network}:accountIndices`,
|
||||
`${network}Counter`,
|
||||
updatedIndices,
|
||||
);
|
||||
};
|
||||
|
||||
const getCosmosAccounts = async (
|
||||
mnemonic: string,
|
||||
path: string,
|
||||
): Promise<{ cosmosWallet: Secp256k1HdWallet; data: AccountData }> => {
|
||||
const cosmosWallet = await Secp256k1HdWallet.fromMnemonic(mnemonic, {
|
||||
hdPaths: [stringToPath(`m/44'/118'/${path}`)],
|
||||
});
|
||||
|
||||
const accountsData = await cosmosWallet.getAccounts();
|
||||
const data = accountsData[0];
|
||||
|
||||
return { cosmosWallet, data };
|
||||
};
|
||||
|
||||
const getAddress = async (
|
||||
network: string,
|
||||
mnemonic: string,
|
||||
path: string,
|
||||
): Promise<string> => {
|
||||
switch (network) {
|
||||
case 'eth':
|
||||
return HDNode.fromMnemonic(mnemonic).derivePath(`m/44'/60'/${path}`)
|
||||
.address;
|
||||
case 'cosmos':
|
||||
return (await getCosmosAccounts(mnemonic, `${path}`)).data.address;
|
||||
default:
|
||||
throw new Error('Invalid wallet type');
|
||||
}
|
||||
};
|
||||
|
||||
export {
|
||||
createWallet,
|
||||
addAccount,
|
||||
@ -247,4 +345,8 @@ export {
|
||||
retrieveAccounts,
|
||||
retrieveSingleAccount,
|
||||
resetWallet,
|
||||
accountInfoFromHDPath,
|
||||
getNextAccountId,
|
||||
updateAccountIndices,
|
||||
getCosmosAccounts,
|
||||
};
|
@ -4,14 +4,13 @@ import 'react-native-get-random-values';
|
||||
|
||||
import '@ethersproject/shims';
|
||||
|
||||
import { HDNode } from 'ethers/lib/utils';
|
||||
import {
|
||||
getInternetCredentials,
|
||||
resetInternetCredentials,
|
||||
setInternetCredentials,
|
||||
} from 'react-native-keychain';
|
||||
|
||||
import { AccountData, Secp256k1HdWallet } from '@cosmjs/amino';
|
||||
import { AccountData } from '@cosmjs/amino';
|
||||
import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing';
|
||||
import { stringToPath } from '@cosmjs/crypto';
|
||||
|
||||
@ -29,36 +28,6 @@ const getHDPath = (network: string, path: string): string => {
|
||||
return network === 'eth' ? `m/44'/60'/${path}` : `m/44'/118'/${path}`;
|
||||
};
|
||||
|
||||
const getAddress = async (
|
||||
network: string,
|
||||
mnemonic: string,
|
||||
path: string,
|
||||
): Promise<string> => {
|
||||
switch (network) {
|
||||
case 'eth':
|
||||
return HDNode.fromMnemonic(mnemonic).derivePath(`m/44'/60'/${path}`)
|
||||
.address;
|
||||
case 'cosmos':
|
||||
return (await getCosmosAccounts(mnemonic, `${path}`)).data.address;
|
||||
default:
|
||||
throw new Error('Invalid wallet type');
|
||||
}
|
||||
};
|
||||
|
||||
const getCosmosAccounts = async (
|
||||
mnemonic: string,
|
||||
path: string,
|
||||
): Promise<{ cosmosWallet: Secp256k1HdWallet; data: AccountData }> => {
|
||||
const cosmosWallet = await Secp256k1HdWallet.fromMnemonic(mnemonic, {
|
||||
hdPaths: [stringToPath(`m/44'/118'/${path}`)],
|
||||
});
|
||||
|
||||
const accountsData = await cosmosWallet.getAccounts();
|
||||
const data = accountsData[0];
|
||||
|
||||
return { cosmosWallet, data };
|
||||
};
|
||||
|
||||
export const getDirectWallet = async (
|
||||
mnemonic: string,
|
||||
path: string,
|
||||
@ -72,46 +41,6 @@ export const getDirectWallet = async (
|
||||
return { directWallet, data };
|
||||
};
|
||||
|
||||
const accountInfoFromHDPath = async (
|
||||
hdPath: string,
|
||||
): Promise<
|
||||
| { privKey: string; pubKey: string; address: string; network: string }
|
||||
| undefined
|
||||
> => {
|
||||
const mnemonicStore = await getInternetCredentials('mnemonicServer');
|
||||
if (!mnemonicStore) {
|
||||
throw new Error('Mnemonic not found!');
|
||||
}
|
||||
|
||||
const mnemonic = mnemonicStore.password;
|
||||
const hdNode = HDNode.fromMnemonic(mnemonic);
|
||||
const node = hdNode.derivePath(hdPath);
|
||||
|
||||
const privKey = node.privateKey;
|
||||
const pubKey = node.publicKey;
|
||||
|
||||
const parts = hdPath.split('/');
|
||||
const path = parts.slice(-3).join('/');
|
||||
const coinType = parts[2];
|
||||
|
||||
let network: string;
|
||||
let address: string;
|
||||
|
||||
switch (coinType) {
|
||||
case "60'":
|
||||
network = 'eth';
|
||||
address = node.address;
|
||||
break;
|
||||
case "118'":
|
||||
network = 'cosmos';
|
||||
address = (await getCosmosAccounts(mnemonic, path)).data.address;
|
||||
break;
|
||||
default:
|
||||
throw new Error('Invalid wallet type');
|
||||
}
|
||||
return { privKey, pubKey, address, network };
|
||||
};
|
||||
|
||||
const getPathKey = async (
|
||||
network: string,
|
||||
accountId: number,
|
||||
@ -177,35 +106,6 @@ const updateGlobalCounter = async (
|
||||
return { accountCounter: updatedAccountCounter, counterId };
|
||||
};
|
||||
|
||||
const getNextAccountId = async (network: string): Promise<number> => {
|
||||
const idStore = await getInternetCredentials(`${network}:accountIndices`);
|
||||
if (!idStore) {
|
||||
throw new Error('Account id not found');
|
||||
}
|
||||
|
||||
const accountIds = idStore.password;
|
||||
const ids = accountIds.split(',').map(Number);
|
||||
return ids[ids.length - 1] + 1;
|
||||
};
|
||||
|
||||
const updateAccountIndices = async (
|
||||
network: string,
|
||||
id: number,
|
||||
): Promise<void> => {
|
||||
const idStore = await getInternetCredentials(`${network}:accountIndices`);
|
||||
if (!idStore) {
|
||||
throw new Error('Account id not found');
|
||||
}
|
||||
|
||||
const updatedIndices = `${idStore.password},${id.toString()}`;
|
||||
await resetInternetCredentials(`${network}:accountIndices`);
|
||||
await setInternetCredentials(
|
||||
`${network}:accountIndices`,
|
||||
`${network}Counter`,
|
||||
updatedIndices,
|
||||
);
|
||||
};
|
||||
|
||||
const resetKeyServers = async (prefix: string) => {
|
||||
const idStore = await getInternetCredentials(`${prefix}:accountIndices`);
|
||||
if (!idStore) {
|
||||
@ -222,14 +122,9 @@ const resetKeyServers = async (prefix: string) => {
|
||||
};
|
||||
|
||||
export {
|
||||
accountInfoFromHDPath,
|
||||
getCosmosAccounts,
|
||||
getMnemonic,
|
||||
getPathKey,
|
||||
getNextAccountId,
|
||||
updateGlobalCounter,
|
||||
updateAccountIndices,
|
||||
getHDPath,
|
||||
getAddress,
|
||||
resetKeyServers,
|
||||
};
|
@ -8,12 +8,8 @@ import { Wallet } from 'ethers';
|
||||
import { SignDoc } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
|
||||
|
||||
import { SignMessageParams } from '../types';
|
||||
import {
|
||||
getCosmosAccounts,
|
||||
getDirectWallet,
|
||||
getMnemonic,
|
||||
getPathKey,
|
||||
} from './utils';
|
||||
import { getDirectWallet, getMnemonic, getPathKey } from './misc';
|
||||
import { getCosmosAccounts } from './accounts';
|
||||
|
||||
const signMessage = async ({
|
||||
message,
|
@ -7,7 +7,8 @@ import { getSdkError } from '@walletconnect/utils';
|
||||
import { EIP155_SIGNING_METHODS } from './EIP155Lib';
|
||||
import { signDirectMessage, signEthMessage } from '../sign-message';
|
||||
import { Account } from '../../types';
|
||||
import { getCosmosAccounts, getMnemonic, getPathKey } from '../utils';
|
||||
import { getMnemonic, getPathKey } from '../misc';
|
||||
import { getCosmosAccounts } from '../accounts';
|
||||
|
||||
export async function approveWalletConnectRequest(
|
||||
requestEvent: SignClientTypes.EventArguments['session_request'],
|
||||
@ -70,7 +71,7 @@ export async function approveWalletConnectRequest(
|
||||
}
|
||||
}
|
||||
|
||||
export function rejectEIP155Request(
|
||||
export function rejectWalletConnectRequest(
|
||||
request: SignClientTypes.EventArguments['session_request'],
|
||||
) {
|
||||
const { id } = request;
|
@ -1,4 +1,3 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import Config from 'react-native-config';
|
||||
|
||||
import '@walletconnect/react-native-compat';
|
||||
@ -7,7 +6,7 @@ import { Core } from '@walletconnect/core';
|
||||
import { ICore } from '@walletconnect/types';
|
||||
import { Web3Wallet, IWeb3Wallet } from '@walletconnect/web3wallet';
|
||||
|
||||
export let web3wallet: IWeb3Wallet;
|
||||
export let web3wallet: IWeb3Wallet | undefined;
|
||||
export let core: ICore;
|
||||
|
||||
export async function createWeb3Wallet() {
|
||||
@ -26,27 +25,8 @@ export async function createWeb3Wallet() {
|
||||
});
|
||||
}
|
||||
|
||||
export default function useInitialization() {
|
||||
const [initialized, setInitialized] = useState(false);
|
||||
|
||||
const onInitialize = useCallback(async () => {
|
||||
try {
|
||||
await createWeb3Wallet();
|
||||
setInitialized(true);
|
||||
} catch (err: unknown) {
|
||||
console.log('Error for initializing', err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialized) {
|
||||
onInitialize();
|
||||
}
|
||||
}, [initialized, onInitialize]);
|
||||
|
||||
return initialized;
|
||||
}
|
||||
|
||||
export async function web3WalletPair(params: { uri: string }) {
|
||||
if (web3wallet) {
|
||||
return await web3wallet.core.pairing.pair({ uri: params.uri });
|
||||
}
|
||||
}
|
@ -1,3 +1,3 @@
|
||||
{
|
||||
"extends": "@react-native/typescript-config/tsconfig.json"
|
||||
"extends": "@react-native/typescript-config/tsconfig.json",
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user