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-native';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import App from '../App';
|
import App from '../src/App';
|
||||||
|
|
||||||
// Note: import explicitly to use the types shipped with jest.
|
// Note: import explicitly to use the types shipped with jest.
|
||||||
import {it} from '@jest/globals';
|
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 { NavigationContainer } from '@react-navigation/native';
|
||||||
|
|
||||||
import App from './App';
|
import App from './src/App';
|
||||||
import { AccountsProvider } from './context/AccountsContext';
|
import { AccountsProvider } from './src/context/AccountsContext';
|
||||||
import { WalletConnectProvider } from './context/WalletConnectContext';
|
import { WalletConnectProvider } from './src/context/WalletConnectContext';
|
||||||
import { name as appName } from './app.json';
|
import { name as appName } from './app.json';
|
||||||
|
|
||||||
export default function Main() {
|
export default function Main() {
|
||||||
|
@ -9,20 +9,22 @@ import {
|
|||||||
NativeStackNavigationProp,
|
NativeStackNavigationProp,
|
||||||
createNativeStackNavigator,
|
createNativeStackNavigator,
|
||||||
} from '@react-navigation/native-stack';
|
} from '@react-navigation/native-stack';
|
||||||
|
import { getSdkError } from '@walletconnect/utils';
|
||||||
import { Web3WalletTypes } from '@walletconnect/web3wallet';
|
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 PairingModal from './components/PairingModal';
|
||||||
import AddSession from './components/AddSession';
|
import { useWalletConnect } from './context/WalletConnectContext';
|
||||||
import WalletConnect from './components/WalletConnect';
|
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 { StackParamsList } from './types';
|
||||||
import { web3wallet } from './utils/wallet-connect/WalletConnectUtils';
|
import { web3wallet } from './utils/wallet-connect/WalletConnectUtils';
|
||||||
import { EIP155_SIGNING_METHODS } from './utils/wallet-connect/EIP155Lib';
|
import { EIP155_SIGNING_METHODS } from './utils/wallet-connect/EIP155Lib';
|
||||||
import { getSignParamsMessage } from './utils/wallet-connect/Helpers';
|
import { getSignParamsMessage } from './utils/wallet-connect/Helpers';
|
||||||
import { useWalletConnect } from './context/WalletConnectContext';
|
|
||||||
|
|
||||||
const Stack = createNativeStackNavigator<StackParamsList>();
|
const Stack = createNativeStackNavigator<StackParamsList>();
|
||||||
|
|
||||||
@ -30,9 +32,8 @@ const App = (): React.JSX.Element => {
|
|||||||
const navigation =
|
const navigation =
|
||||||
useNavigation<NativeStackNavigationProp<StackParamsList>>();
|
useNavigation<NativeStackNavigationProp<StackParamsList>>();
|
||||||
|
|
||||||
const { requestSession, setRequestSession, setActiveSessions } =
|
const { setActiveSessions } = useWalletConnect();
|
||||||
useWalletConnect();
|
const { accounts } = useAccounts();
|
||||||
|
|
||||||
const [modalVisible, setModalVisible] = useState(false);
|
const [modalVisible, setModalVisible] = useState(false);
|
||||||
const [toastVisible, setToastVisible] = useState(false);
|
const [toastVisible, setToastVisible] = useState(false);
|
||||||
const [currentProposal, setCurrentProposal] = useState<
|
const [currentProposal, setCurrentProposal] = useState<
|
||||||
@ -40,11 +41,19 @@ const App = (): React.JSX.Element => {
|
|||||||
>();
|
>();
|
||||||
|
|
||||||
const onSessionProposal = useCallback(
|
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);
|
setModalVisible(true);
|
||||||
setCurrentProposal(proposal);
|
setCurrentProposal(proposal);
|
||||||
},
|
},
|
||||||
[],
|
[accounts.ethAccounts, accounts.cosmosAccounts],
|
||||||
);
|
);
|
||||||
|
|
||||||
const onSessionRequest = useCallback(
|
const onSessionRequest = useCallback(
|
||||||
@ -53,10 +62,7 @@ const App = (): React.JSX.Element => {
|
|||||||
const { request } = params;
|
const { request } = params;
|
||||||
|
|
||||||
const requestSessionData =
|
const requestSessionData =
|
||||||
web3wallet.engine.signClient.session.get(topic);
|
web3wallet!.engine.signClient.session.get(topic);
|
||||||
|
|
||||||
setRequestSession(requestSessionData);
|
|
||||||
|
|
||||||
switch (request.method) {
|
switch (request.method) {
|
||||||
case EIP155_SIGNING_METHODS.PERSONAL_SIGN:
|
case EIP155_SIGNING_METHODS.PERSONAL_SIGN:
|
||||||
navigation.navigate('SignRequest', {
|
navigation.navigate('SignRequest', {
|
||||||
@ -64,7 +70,7 @@ const App = (): React.JSX.Element => {
|
|||||||
address: request.params[1],
|
address: request.params[1],
|
||||||
message: getSignParamsMessage(request.params),
|
message: getSignParamsMessage(request.params),
|
||||||
requestEvent,
|
requestEvent,
|
||||||
requestSession,
|
requestSessionData,
|
||||||
});
|
});
|
||||||
|
|
||||||
break;
|
break;
|
||||||
@ -90,7 +96,7 @@ const App = (): React.JSX.Element => {
|
|||||||
address: request.params.signerAddress,
|
address: request.params.signerAddress,
|
||||||
message: JSON.stringify(message, undefined, 2),
|
message: JSON.stringify(message, undefined, 2),
|
||||||
requestEvent,
|
requestEvent,
|
||||||
requestSession,
|
requestSessionData,
|
||||||
});
|
});
|
||||||
|
|
||||||
break;
|
break;
|
||||||
@ -100,7 +106,7 @@ const App = (): React.JSX.Element => {
|
|||||||
address: request.params.signerAddress,
|
address: request.params.signerAddress,
|
||||||
message: request.params.signDoc.memo,
|
message: request.params.signDoc.memo,
|
||||||
requestEvent,
|
requestEvent,
|
||||||
requestSession,
|
requestSessionData,
|
||||||
});
|
});
|
||||||
|
|
||||||
break;
|
break;
|
||||||
@ -108,13 +114,13 @@ const App = (): React.JSX.Element => {
|
|||||||
throw new Error('Invalid method');
|
throw new Error('Invalid method');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[requestSession, setRequestSession, navigation],
|
[navigation],
|
||||||
);
|
);
|
||||||
|
|
||||||
const onSessionDelete = useCallback(() => {
|
const onSessionDelete = useCallback(() => {
|
||||||
let sessions = web3wallet?.getActiveSessions();
|
const sessions = web3wallet!.getActiveSessions();
|
||||||
setActiveSessions(sessions);
|
setActiveSessions(sessions);
|
||||||
}, []);
|
}, [setActiveSessions]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
web3wallet?.on('session_proposal', onSessionProposal);
|
web3wallet?.on('session_proposal', onSessionProposal);
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
@ -54,38 +54,48 @@ const Accounts = ({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const updateSessions = async () => {
|
const updateSessions = async () => {
|
||||||
const sessions = web3wallet?.getActiveSessions() || {};
|
const sessions = (web3wallet && web3wallet.getActiveSessions()) || {};
|
||||||
|
// Iterate through each session
|
||||||
|
|
||||||
for (const topic in sessions) {
|
for (const topic in sessions) {
|
||||||
const session = sessions[topic];
|
const session = sessions[topic];
|
||||||
const requiredNamespaces = session.requiredNamespaces;
|
const requiredNamespaces = session.requiredNamespaces;
|
||||||
const namespaces = session.namespaces;
|
const namespaces = session.namespaces;
|
||||||
|
|
||||||
|
// Check if EIP155 namespace exists and Ethereum accounts have changed
|
||||||
if (
|
if (
|
||||||
namespaces.hasOwnProperty('eip155') &&
|
namespaces.hasOwnProperty('eip155') &&
|
||||||
prevEthAccountsRef !== accounts.ethAccounts
|
prevEthAccountsRef !== accounts.ethAccounts
|
||||||
) {
|
) {
|
||||||
|
// Iterate through each chain ID in required EIP155 namespaces
|
||||||
requiredNamespaces.eip155.chains?.forEach(chainId => {
|
requiredNamespaces.eip155.chains?.forEach(chainId => {
|
||||||
|
// Update Ethereum accounts in namespaces with chain prefix
|
||||||
namespaces.eip155.accounts = accounts.ethAccounts.map(
|
namespaces.eip155.accounts = accounts.ethAccounts.map(
|
||||||
ethAccount => `${chainId}:${ethAccount.address}`,
|
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 (
|
if (
|
||||||
namespaces.hasOwnProperty('cosmos') &&
|
namespaces.hasOwnProperty('cosmos') &&
|
||||||
prevCosmosAccountsRef !== accounts.cosmosAccounts
|
prevCosmosAccountsRef !== accounts.cosmosAccounts
|
||||||
) {
|
) {
|
||||||
|
// Iterate through each chain ID in required Cosmos namespaces
|
||||||
requiredNamespaces?.cosmos.chains?.forEach(chainId => {
|
requiredNamespaces?.cosmos.chains?.forEach(chainId => {
|
||||||
|
// Iterate through each chain ID in required Cosmos namespaces
|
||||||
namespaces.cosmos.accounts = accounts.cosmosAccounts.map(
|
namespaces.cosmos.accounts = accounts.cosmosAccounts.map(
|
||||||
cosmosAccount => `${chainId}:${cosmosAccount.address}`,
|
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();
|
updateSessions();
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [accounts]);
|
}, [accounts]);
|
@ -137,13 +137,13 @@ const PairingModal = ({
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
await web3wallet.approveSession({
|
await web3wallet!.approveSession({
|
||||||
id,
|
id,
|
||||||
relayProtocol: relays[0].protocol,
|
relayProtocol: relays[0].protocol,
|
||||||
namespaces,
|
namespaces,
|
||||||
});
|
});
|
||||||
|
|
||||||
const sessions = web3wallet.getActiveSessions();
|
const sessions = web3wallet!.getActiveSessions();
|
||||||
setActiveSessions(sessions);
|
setActiveSessions(sessions);
|
||||||
setModalVisible(false);
|
setModalVisible(false);
|
||||||
setToastVisible(true);
|
setToastVisible(true);
|
||||||
@ -159,7 +159,7 @@ const PairingModal = ({
|
|||||||
const handleReject = async () => {
|
const handleReject = async () => {
|
||||||
if (currentProposal) {
|
if (currentProposal) {
|
||||||
const { id } = currentProposal;
|
const { id } = currentProposal;
|
||||||
await web3wallet.rejectSession({
|
await web3wallet!.rejectSession({
|
||||||
id,
|
id,
|
||||||
reason: getSdkError('USER_REJECTED_METHODS'),
|
reason: getSdkError('USER_REJECTED_METHODS'),
|
||||||
});
|
});
|
@ -3,13 +3,10 @@ import React, { createContext, useContext, useEffect, useState } from 'react';
|
|||||||
import { SessionTypes } from '@walletconnect/types';
|
import { SessionTypes } from '@walletconnect/types';
|
||||||
|
|
||||||
import { WalletConnectContextProps } from '../types';
|
import { WalletConnectContextProps } from '../types';
|
||||||
import useInitialization, {
|
import { web3wallet } from '../utils/wallet-connect/WalletConnectUtils';
|
||||||
web3wallet,
|
import useInitialization from '../hooks/useInitialization';
|
||||||
} from '../utils/wallet-connect/WalletConnectUtils';
|
|
||||||
|
|
||||||
const WalletConnectContext = createContext<WalletConnectContextProps>({
|
const WalletConnectContext = createContext<WalletConnectContextProps>({
|
||||||
requestSession: {},
|
|
||||||
setRequestSession: () => {},
|
|
||||||
activeSessions: {},
|
activeSessions: {},
|
||||||
setActiveSessions: () => {},
|
setActiveSessions: () => {},
|
||||||
});
|
});
|
||||||
@ -23,11 +20,10 @@ const WalletConnectProvider = ({ children }: { children: React.ReactNode }) => {
|
|||||||
useInitialization();
|
useInitialization();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const sessions = web3wallet?.getActiveSessions() ?? {};
|
const sessions = (web3wallet && web3wallet.getActiveSessions()) || {};
|
||||||
setActiveSessions(sessions);
|
setActiveSessions(sessions);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const [requestSession, setRequestSession] = useState<any>({});
|
|
||||||
const [activeSessions, setActiveSessions] = useState<
|
const [activeSessions, setActiveSessions] = useState<
|
||||||
Record<string, SessionTypes.Struct>
|
Record<string, SessionTypes.Struct>
|
||||||
>({});
|
>({});
|
||||||
@ -35,8 +31,6 @@ const WalletConnectProvider = ({ children }: { children: React.ReactNode }) => {
|
|||||||
return (
|
return (
|
||||||
<WalletConnectContext.Provider
|
<WalletConnectContext.Provider
|
||||||
value={{
|
value={{
|
||||||
requestSession,
|
|
||||||
setRequestSession,
|
|
||||||
activeSessions,
|
activeSessions,
|
||||||
setActiveSessions,
|
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 {
|
export function usePrevious<T>(value: T): T | undefined {
|
||||||
const ref = useRef(value);
|
const ref = useRef(value);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
ref.current = value;
|
ref.current = value;
|
||||||
}, [value]);
|
}, [value]);
|
@ -7,11 +7,11 @@ import { useNavigation } from '@react-navigation/native';
|
|||||||
import { getSdkError } from '@walletconnect/utils';
|
import { getSdkError } from '@walletconnect/utils';
|
||||||
|
|
||||||
import { createWallet, resetWallet, retrieveAccounts } from '../utils/accounts';
|
import { createWallet, resetWallet, retrieveAccounts } from '../utils/accounts';
|
||||||
import { DialogComponent } from './Dialog';
|
import { DialogComponent } from '../components/Dialog';
|
||||||
import { NetworkDropdown } from './NetworkDropdown';
|
import { NetworkDropdown } from '../components/NetworkDropdown';
|
||||||
import Accounts from './Accounts';
|
import Accounts from '../components/Accounts';
|
||||||
import CreateWallet from './CreateWallet';
|
import CreateWallet from '../components/CreateWallet';
|
||||||
import ResetWalletDialog from './ResetWalletDialog';
|
import ResetWalletDialog from '../components/ResetWalletDialog';
|
||||||
import styles from '../styles/stylesheet';
|
import styles from '../styles/stylesheet';
|
||||||
import { useAccounts } from '../context/AccountsContext';
|
import { useAccounts } from '../context/AccountsContext';
|
||||||
import { useWalletConnect } from '../context/WalletConnectContext';
|
import { useWalletConnect } from '../context/WalletConnectContext';
|
@ -7,7 +7,7 @@ import { NativeStackScreenProps } from '@react-navigation/native-stack';
|
|||||||
import { StackParamsList } from '../types';
|
import { StackParamsList } from '../types';
|
||||||
import styles from '../styles/stylesheet';
|
import styles from '../styles/stylesheet';
|
||||||
import { signMessage } from '../utils/sign-message';
|
import { signMessage } from '../utils/sign-message';
|
||||||
import AccountDetails from './AccountDetails';
|
import AccountDetails from '../components/AccountDetails';
|
||||||
|
|
||||||
type SignProps = NativeStackScreenProps<StackParamsList, 'SignMessage'>;
|
type SignProps = NativeStackScreenProps<StackParamsList, 'SignMessage'>;
|
||||||
|
|
@ -10,22 +10,20 @@ import {
|
|||||||
import { getHeaderTitle } from '@react-navigation/elements';
|
import { getHeaderTitle } from '@react-navigation/elements';
|
||||||
|
|
||||||
import { Account, StackParamsList } from '../types';
|
import { Account, StackParamsList } from '../types';
|
||||||
import AccountDetails from './AccountDetails';
|
import AccountDetails from '../components/AccountDetails';
|
||||||
import styles from '../styles/stylesheet';
|
import styles from '../styles/stylesheet';
|
||||||
import { signMessage } from '../utils/sign-message';
|
import { signMessage } from '../utils/sign-message';
|
||||||
import { retrieveSingleAccount } from '../utils/accounts';
|
import { retrieveSingleAccount } from '../utils/accounts';
|
||||||
import {
|
import {
|
||||||
approveWalletConnectRequest,
|
approveWalletConnectRequest,
|
||||||
rejectEIP155Request,
|
rejectWalletConnectRequest,
|
||||||
} from '../utils/wallet-connect/WalletConnectRequests';
|
} from '../utils/wallet-connect/WalletConnectRequests';
|
||||||
import { web3wallet } from '../utils/wallet-connect/WalletConnectUtils';
|
import { web3wallet } from '../utils/wallet-connect/WalletConnectUtils';
|
||||||
import { useWalletConnect } from '../context/WalletConnectContext';
|
|
||||||
|
|
||||||
type SignRequestProps = NativeStackScreenProps<StackParamsList, 'SignRequest'>;
|
type SignRequestProps = NativeStackScreenProps<StackParamsList, 'SignRequest'>;
|
||||||
|
|
||||||
const SignRequest = ({ route }: SignRequestProps) => {
|
const SignRequest = ({ route }: SignRequestProps) => {
|
||||||
const { requestSession } = useWalletConnect();
|
const requestSession = route.params?.requestSessionData;
|
||||||
|
|
||||||
const requestName = requestSession?.peer?.metadata?.name;
|
const requestName = requestSession?.peer?.metadata?.name;
|
||||||
const requestIcon = requestSession?.peer?.metadata?.icons[0];
|
const requestIcon = requestSession?.peer?.metadata?.icons[0];
|
||||||
const requestURL = requestSession?.peer?.metadata?.url;
|
const requestURL = requestSession?.peer?.metadata?.url;
|
||||||
@ -159,7 +157,7 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
|||||||
|
|
||||||
const rejectRequestHandler = async () => {
|
const rejectRequestHandler = async () => {
|
||||||
if (route.params?.requestEvent) {
|
if (route.params?.requestEvent) {
|
||||||
const response = rejectEIP155Request(route.params?.requestEvent);
|
const response = rejectWalletConnectRequest(route.params?.requestEvent);
|
||||||
const { topic } = route.params?.requestEvent;
|
const { topic } = route.params?.requestEvent;
|
||||||
await web3wallet.respondSessionRequest({
|
await web3wallet.respondSessionRequest({
|
||||||
topic,
|
topic,
|
||||||
@ -169,6 +167,7 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
|||||||
navigation.navigate('Laconic');
|
navigation.navigate('Laconic');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
navigation.setOptions({
|
navigation.setOptions({
|
||||||
// eslint-disable-next-line react/no-unstable-nested-components
|
// eslint-disable-next-line react/no-unstable-nested-components
|
||||||
header: ({ options, back }) => {
|
header: ({ options, back }) => {
|
||||||
@ -189,6 +188,8 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [navigation, route.name]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
@ -10,7 +10,7 @@ export type StackParamsList = {
|
|||||||
address: string;
|
address: string;
|
||||||
message: string;
|
message: string;
|
||||||
requestEvent?: Web3WalletTypes.SessionRequest;
|
requestEvent?: Web3WalletTypes.SessionRequest;
|
||||||
requestSession?: any;
|
requestSessionData?: SessionTypes.Struct;
|
||||||
}
|
}
|
||||||
| undefined;
|
| undefined;
|
||||||
InvalidPath: undefined;
|
InvalidPath: undefined;
|
||||||
@ -101,17 +101,7 @@ export interface PairingModalProps {
|
|||||||
setToastVisible: (arg1: boolean) => void;
|
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 {
|
export interface WalletConnectContextProps {
|
||||||
requestSession: any;
|
|
||||||
setRequestSession: (requestSession: any) => void;
|
|
||||||
activeSessions: Record<string, SessionTypes.Struct>;
|
activeSessions: Record<string, SessionTypes.Struct>;
|
||||||
setActiveSessions: (
|
setActiveSessions: (
|
||||||
activeSessions: Record<string, SessionTypes.Struct>,
|
activeSessions: Record<string, SessionTypes.Struct>,
|
@ -12,19 +12,18 @@ import {
|
|||||||
getInternetCredentials,
|
getInternetCredentials,
|
||||||
} from 'react-native-keychain';
|
} 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 { Account, WalletDetails } from '../types';
|
||||||
import {
|
import {
|
||||||
accountInfoFromHDPath,
|
|
||||||
getAddress,
|
|
||||||
getCosmosAccounts,
|
|
||||||
getHDPath,
|
getHDPath,
|
||||||
getMnemonic,
|
getMnemonic,
|
||||||
getNextAccountId,
|
|
||||||
getPathKey,
|
getPathKey,
|
||||||
resetKeyServers,
|
resetKeyServers,
|
||||||
updateAccountIndices,
|
|
||||||
updateGlobalCounter,
|
updateGlobalCounter,
|
||||||
} from './utils';
|
} from './misc';
|
||||||
|
|
||||||
const createWallet = async (): Promise<WalletDetails> => {
|
const createWallet = async (): Promise<WalletDetails> => {
|
||||||
try {
|
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 {
|
export {
|
||||||
createWallet,
|
createWallet,
|
||||||
addAccount,
|
addAccount,
|
||||||
@ -247,4 +345,8 @@ export {
|
|||||||
retrieveAccounts,
|
retrieveAccounts,
|
||||||
retrieveSingleAccount,
|
retrieveSingleAccount,
|
||||||
resetWallet,
|
resetWallet,
|
||||||
|
accountInfoFromHDPath,
|
||||||
|
getNextAccountId,
|
||||||
|
updateAccountIndices,
|
||||||
|
getCosmosAccounts,
|
||||||
};
|
};
|
@ -4,14 +4,13 @@ import 'react-native-get-random-values';
|
|||||||
|
|
||||||
import '@ethersproject/shims';
|
import '@ethersproject/shims';
|
||||||
|
|
||||||
import { HDNode } from 'ethers/lib/utils';
|
|
||||||
import {
|
import {
|
||||||
getInternetCredentials,
|
getInternetCredentials,
|
||||||
resetInternetCredentials,
|
resetInternetCredentials,
|
||||||
setInternetCredentials,
|
setInternetCredentials,
|
||||||
} from 'react-native-keychain';
|
} from 'react-native-keychain';
|
||||||
|
|
||||||
import { AccountData, Secp256k1HdWallet } from '@cosmjs/amino';
|
import { AccountData } from '@cosmjs/amino';
|
||||||
import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing';
|
import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing';
|
||||||
import { stringToPath } from '@cosmjs/crypto';
|
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}`;
|
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 (
|
export const getDirectWallet = async (
|
||||||
mnemonic: string,
|
mnemonic: string,
|
||||||
path: string,
|
path: string,
|
||||||
@ -72,46 +41,6 @@ export const getDirectWallet = async (
|
|||||||
return { directWallet, data };
|
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 (
|
const getPathKey = async (
|
||||||
network: string,
|
network: string,
|
||||||
accountId: number,
|
accountId: number,
|
||||||
@ -177,35 +106,6 @@ const updateGlobalCounter = async (
|
|||||||
return { accountCounter: updatedAccountCounter, counterId };
|
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 resetKeyServers = async (prefix: string) => {
|
||||||
const idStore = await getInternetCredentials(`${prefix}:accountIndices`);
|
const idStore = await getInternetCredentials(`${prefix}:accountIndices`);
|
||||||
if (!idStore) {
|
if (!idStore) {
|
||||||
@ -222,14 +122,9 @@ const resetKeyServers = async (prefix: string) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export {
|
export {
|
||||||
accountInfoFromHDPath,
|
|
||||||
getCosmosAccounts,
|
|
||||||
getMnemonic,
|
getMnemonic,
|
||||||
getPathKey,
|
getPathKey,
|
||||||
getNextAccountId,
|
|
||||||
updateGlobalCounter,
|
updateGlobalCounter,
|
||||||
updateAccountIndices,
|
|
||||||
getHDPath,
|
getHDPath,
|
||||||
getAddress,
|
|
||||||
resetKeyServers,
|
resetKeyServers,
|
||||||
};
|
};
|
@ -8,12 +8,8 @@ import { Wallet } from 'ethers';
|
|||||||
import { SignDoc } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
|
import { SignDoc } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
|
||||||
|
|
||||||
import { SignMessageParams } from '../types';
|
import { SignMessageParams } from '../types';
|
||||||
import {
|
import { getDirectWallet, getMnemonic, getPathKey } from './misc';
|
||||||
getCosmosAccounts,
|
import { getCosmosAccounts } from './accounts';
|
||||||
getDirectWallet,
|
|
||||||
getMnemonic,
|
|
||||||
getPathKey,
|
|
||||||
} from './utils';
|
|
||||||
|
|
||||||
const signMessage = async ({
|
const signMessage = async ({
|
||||||
message,
|
message,
|
@ -7,7 +7,8 @@ import { getSdkError } from '@walletconnect/utils';
|
|||||||
import { EIP155_SIGNING_METHODS } from './EIP155Lib';
|
import { EIP155_SIGNING_METHODS } from './EIP155Lib';
|
||||||
import { signDirectMessage, signEthMessage } from '../sign-message';
|
import { signDirectMessage, signEthMessage } from '../sign-message';
|
||||||
import { Account } from '../../types';
|
import { Account } from '../../types';
|
||||||
import { getCosmosAccounts, getMnemonic, getPathKey } from '../utils';
|
import { getMnemonic, getPathKey } from '../misc';
|
||||||
|
import { getCosmosAccounts } from '../accounts';
|
||||||
|
|
||||||
export async function approveWalletConnectRequest(
|
export async function approveWalletConnectRequest(
|
||||||
requestEvent: SignClientTypes.EventArguments['session_request'],
|
requestEvent: SignClientTypes.EventArguments['session_request'],
|
||||||
@ -70,7 +71,7 @@ export async function approveWalletConnectRequest(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function rejectEIP155Request(
|
export function rejectWalletConnectRequest(
|
||||||
request: SignClientTypes.EventArguments['session_request'],
|
request: SignClientTypes.EventArguments['session_request'],
|
||||||
) {
|
) {
|
||||||
const { id } = request;
|
const { id } = request;
|
@ -1,4 +1,3 @@
|
|||||||
import { useState, useCallback, useEffect } from 'react';
|
|
||||||
import Config from 'react-native-config';
|
import Config from 'react-native-config';
|
||||||
|
|
||||||
import '@walletconnect/react-native-compat';
|
import '@walletconnect/react-native-compat';
|
||||||
@ -7,7 +6,7 @@ import { Core } from '@walletconnect/core';
|
|||||||
import { ICore } from '@walletconnect/types';
|
import { ICore } from '@walletconnect/types';
|
||||||
import { Web3Wallet, IWeb3Wallet } from '@walletconnect/web3wallet';
|
import { Web3Wallet, IWeb3Wallet } from '@walletconnect/web3wallet';
|
||||||
|
|
||||||
export let web3wallet: IWeb3Wallet;
|
export let web3wallet: IWeb3Wallet | undefined;
|
||||||
export let core: ICore;
|
export let core: ICore;
|
||||||
|
|
||||||
export async function createWeb3Wallet() {
|
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 }) {
|
export async function web3WalletPair(params: { uri: string }) {
|
||||||
|
if (web3wallet) {
|
||||||
return await web3wallet.core.pairing.pair({ uri: params.uri });
|
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