Compare commits

..
11 changed files with 426 additions and 423 deletions
-1
View File
@@ -4,5 +4,4 @@ REACT_APP_DEFAULT_GAS_PRICE=0.025
# Reference: https://github.com/cosmos/cosmos-sdk/issues/16020
REACT_APP_GAS_ADJUSTMENT=2
REACT_APP_LACONICD_RPC_URL=https://laconicd-sapo.laconic.com
REACT_APP_DEPLOY_APP_URL=
+17
View File
@@ -41,6 +41,8 @@ import { AutoSignIn } from "./screens/AutoSignIn";
import { checkSufficientFunds, getPathKey, sendMessage } from "./utils/misc";
import useAccountsData from "./hooks/useAccountsData";
import { useWebViewHandler } from "./hooks/useWebViewHandler";
import SignMessageEmbed from "./screens/SignMessageEmbed";
import { AddAccountEmbed } from "./screens/AddAccountEmbed";
const Stack = createStackNavigator<StackParamsList>();
@@ -390,6 +392,21 @@ const App = (): React.JSX.Element => {
header: () => <></>,
}}
/>
<Stack.Screen
name="add-account-embed"
component={AddAccountEmbed}
options={{
header: () => <></>,
}}
/>
<Stack.Screen
name="sign-message-embed"
component={SignMessageEmbed}
options={{
// eslint-disable-next-line react/no-unstable-nested-components
header: () => <Header title="Wallet" />,
}}
/>
</Stack.Navigator>
<PairingModal
visible={modalVisible}
-12
View File
@@ -14,22 +14,10 @@ declare global {
// Called when accounts are ready for use
onAccountsReady?: () => void;
// Called when transfer is successfully completed
onTransferComplete?: (result: string) => void;
// Called when transfer fails
onTransferError?: (error: string) => void;
// Called when transfer is cancelled
onTransferCancelled?: () => void;
};
// Handles incoming signature requests from Android
receiveSignRequestFromAndroid?: (message: string) => void;
// Handles incoming transfer requests from Android
receiveTransferRequestFromAndroid?: (to: string, amount: string) => void;
}
}
+10 -7
View File
@@ -4,10 +4,12 @@ import { createWallet } from "../utils/accounts";
import { sendMessage } from "../utils/misc";
import useAccountsData from "./useAccountsData";
import { useNetworks } from "../context/NetworksContext";
import { useAccounts } from "../context/AccountsContext";
const useGetOrCreateAccounts = () => {
const { networksData } = useNetworks();
const { getAccountsData } = useAccountsData();
const { setAccounts } = useAccounts();
// Wrap the function in useCallback to prevent recreation on each render
const getOrCreateAccountsForChain = useCallback(async (chainId: string) => {
@@ -19,8 +21,11 @@ const useGetOrCreateAccounts = () => {
accountsData = await getAccountsData(chainId);
}
// Update the AccountsContext with the new accounts
setAccounts(accountsData);
return accountsData;
}, [networksData, getAccountsData]);
}, [networksData, getAccountsData, setAccounts]);
useEffect(() => {
const handleCreateAccounts = async (event: MessageEvent) => {
@@ -42,14 +47,13 @@ const useGetOrCreateAccounts = () => {
console.log('useGetOrCreateAccounts: No default chainId found');
return;
}
const accounts = await getOrCreateAccountsForChain(defaultChainId);
await getOrCreateAccountsForChain(defaultChainId);
// Notify Android that accounts are ready
if (window.Android?.onAccountsReady) {
// Only notify Android when we actually have accounts
if (accounts.length > 0 && window.Android?.onAccountsReady) {
window.Android.onAccountsReady();
} else {
console.log('useGetOrCreateAccounts: Android bridge not available');
console.log('No accounts created or Android bridge not available');
}
};
@@ -57,7 +61,6 @@ const useGetOrCreateAccounts = () => {
const isAndroidWebView = !!(window.Android);
// TODO: Call method to auto create accounts from android app
if (isAndroidWebView) {
autoCreateAccounts();
}
+3 -98
View File
@@ -6,17 +6,16 @@ import { useAccounts } from '../context/AccountsContext';
import { useNetworks } from '../context/NetworksContext';
import { StackParamsList } from '../types';
import useGetOrCreateAccounts from './useGetOrCreateAccounts';
import { retrieveAccountsForNetwork } from '../utils/accounts';
export const useWebViewHandler = () => {
// Navigation and context hooks
const navigation = useNavigation<NativeStackNavigationProp<StackParamsList>>();
const { selectedNetwork } = useNetworks();
const { accounts, currentIndex } = useAccounts();
// Initialize accounts
useGetOrCreateAccounts();
// Core navigation handler
const navigateToSignRequest = useCallback((message: string) => {
try {
@@ -71,106 +70,12 @@ export const useWebViewHandler = () => {
}
}, [selectedNetwork, accounts, currentIndex, navigation]);
// Handle incoming transfer requests
const navigateToTransfer = useCallback(async (to: string, amount: string) => {
if (!accounts || accounts.length === 0) {
console.error('No accounts available');
if (window.Android?.onTransferError) {
window.Android.onTransferError('No accounts available');
}
return;
}
const currentAccount = accounts[currentIndex];
if (!currentAccount) {
console.error('Current account not found');
if (window.Android?.onTransferError) {
window.Android.onTransferError('Current account not found');
}
return;
}
// Use Cosmos Hub Testnet network
const cosmosHubTestnet = {
namespace: 'cosmos',
chainId: 'provider',
addressPrefix: 'cosmos'
};
try {
// Get all accounts for Cosmos Hub Testnet
const cosmosAccounts = await retrieveAccountsForNetwork(
`${cosmosHubTestnet.namespace}:${cosmosHubTestnet.chainId}`,
'0' // Use the first account
);
if (!cosmosAccounts || cosmosAccounts.length === 0) {
console.error('No Cosmos Hub Testnet accounts found');
if (window.Android?.onTransferError) {
window.Android.onTransferError('No Cosmos Hub Testnet accounts found');
}
return;
}
const cosmosAccount = cosmosAccounts[0]; // Use the first account
const path = `/transfer/${cosmosHubTestnet.namespace}/${cosmosHubTestnet.chainId}/${cosmosAccount.address}/${to}/${amount}`;
const pathRegex = /^\/transfer\/(eip155|cosmos)\/(.+)\/(.+)\/(.+)\/(.+)$/;
if (!pathRegex.test(path)) {
console.error('Path does not match expected pattern:', path);
if (window.Android?.onTransferError) {
window.Android.onTransferError('Invalid path format');
}
return;
}
const match = path.match(pathRegex);
if (!match) {
console.error('Failed to parse path:', path);
if (window.Android?.onTransferError) {
window.Android.onTransferError('Failed to parse path');
}
return;
}
navigation.reset({
index: 0,
routes: [
{
name: 'ApproveTransfer',
path: `/transfer/${cosmosHubTestnet.namespace}/${cosmosHubTestnet.chainId}/${cosmosAccount.address}/${to}/${amount}`,
params: {
namespace: cosmosHubTestnet.namespace,
chainId: `${cosmosHubTestnet.namespace}:${cosmosHubTestnet.chainId}`,
transaction: {
from: cosmosAccount.address,
to: to,
value: amount,
data: ''
},
accountInfo: cosmosAccount,
},
},
],
});
} catch (error) {
console.error('Navigation error:', error);
if (window.Android?.onTransferError) {
window.Android.onTransferError(`Navigation error: ${error}`);
}
}
}, [accounts, currentIndex, navigation]);
useEffect(() => {
// Assign the function to the window object
window.receiveSignRequestFromAndroid = navigateToSignRequest;
window.receiveTransferRequestFromAndroid = navigateToTransfer;
return () => {
window.receiveSignRequestFromAndroid = undefined;
window.receiveTransferRequestFromAndroid = undefined;
};
}, [navigateToSignRequest, navigateToTransfer]); // Only the function reference as dependency
}, [navigateToSignRequest]); // Only the function reference as dependency
};
+58
View File
@@ -0,0 +1,58 @@
import React, { useEffect } from 'react';
import { useNetworks } from '../context/NetworksContext';
import { sendMessage } from '../utils/misc';
import useAccountsData from '../hooks/useAccountsData';
import useGetOrCreateAccounts from '../hooks/useGetOrCreateAccounts';
import { addAccount, retrieveSingleAccount } from '../utils/accounts';
import { useAccounts } from '../context/AccountsContext';
import { Account, NetworksDataState } from '../types';
export const AddAccountEmbed = () => {
const { networksData } = useNetworks();
const { accounts, setAccounts, setCurrentIndex } =
useAccounts();
const { getAccountsData } = useAccountsData();
const addAccountHandler = async (network: NetworksDataState) => {
const newAccount = await addAccount(network);
if (newAccount) {
setAccounts([...accounts, newAccount]);
setCurrentIndex(newAccount.index);
}
};
useEffect(() => {
const handleAddAccount = async (event: MessageEvent) => {
if (event.data.type !== 'ADD_ACCOUNT') return;
if (event.origin !== process.env.REACT_APP_DEPLOY_APP_URL) {
console.log('Unauthorized app.');
return;
}
const network = networksData.find(network => network.chainId === event.data.chainId);
await addAccountHandler(network!);
const accounts = await getAccountsData(event.data.chainId);
const accountsData: string[] = accounts.map((account: Account) => account.address);
sendMessage(event.source as Window, 'ADD_ACCOUNT_RESPONSE', accountsData, event.origin);
};
window.addEventListener('message', handleAddAccount);
return () => {
window.removeEventListener('message', handleAddAccount);
};
}, [networksData, getAccountsData]);
// Custom hook for adding listener to get accounts data
useGetOrCreateAccounts();
console.log('wallet')
return (
<>
</>
)
};
+141 -299
View File
@@ -46,29 +46,24 @@ export const MEMO = 'Sending signed tx from Laconic Wallet';
// Reference: https://ethereum.org/en/developers/docs/gas/#what-is-gas-limit
const ETH_MINIMUM_GAS = 21000;
type ApproveTransferProps = NativeStackScreenProps<StackParamsList, 'ApproveTransfer'> & {
route: {
params: {
transaction: any;
requestEvent?: {
params: {
chainId: string;
request: {
method: string;
};
};
};
requestSessionData?: any;
chainId?: string;
};
path?: string;
};
};
type SignRequestProps = NativeStackScreenProps<
StackParamsList,
'ApproveTransfer'
>;
const ApproveTransfer = ({ route }: ApproveTransferProps) => {
const ApproveTransfer = ({ route }: SignRequestProps) => {
const { networksData } = useNetworks();
const { web3wallet } = 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;
const transaction = route.params.transaction;
const requestEvent = route.params.requestEvent;
const chainId = requestEvent.params.chainId;
const requestMethod = requestEvent.params.request.method;
const [account, setAccount] = useState<Account>();
const [isLoading, setIsLoading] = useState(true);
const [balance, setBalance] = useState<string>('');
@@ -85,80 +80,6 @@ const ApproveTransfer = ({ route }: ApproveTransferProps) => {
const [ethMaxPriorityFee, setEthMaxPriorityFee] =
useState<BigNumber | null>();
const navigation =
useNavigation<NativeStackNavigationProp<StackParamsList>>();
// Extract data from route params or path
const requestSession = route.params?.requestSessionData;
const requestName = requestSession?.peer?.metadata?.name;
const requestIcon = requestSession?.peer?.metadata?.icons?.[0];
const requestURL = requestSession?.peer?.metadata?.url;
const transaction = route.params?.transaction;
const requestEvent = route.params?.requestEvent;
const chainId = requestEvent?.params?.chainId || route.params?.chainId;
const requestMethod = requestEvent?.params?.request?.method;
const sanitizePath = useCallback((path: string) => {
const regex = /^\/transfer\/(eip155|cosmos)\/(.+)\/(.+)\/(.+)\/(.+)$/;
const match = path.match(regex);
if (match) {
const [, pathNamespace, pathChainId, pathAddress, pathTo, pathAmount] = match;
return {
namespace: pathNamespace,
chainId: pathChainId,
address: pathAddress,
to: pathTo,
amount: pathAmount,
};
} else {
navigation.navigate('InvalidPath');
}
return null;
}, [navigation]);
const retrieveData = useCallback(async (requestNamespace: string, requestChainId: string, requestAddress: string) => {
const requestAccount = await retrieveSingleAccount(
requestNamespace,
requestChainId,
requestAddress,
);
if (!requestAccount) {
navigation.navigate('InvalidPath');
return;
}
setAccount(requestAccount);
}, [navigation]);
useEffect(() => {
if (route.path) {
const sanitizedRoute = sanitizePath(route.path);
if (sanitizedRoute) {
retrieveData(
sanitizedRoute.namespace,
sanitizedRoute.chainId,
sanitizedRoute.address,
);
return;
}
}
if (requestEvent) {
const requestedNetwork = networksData.find(
networkData => {
return `${networkData.namespace}:${networkData.chainId}` === chainId;
}
);
if (requestedNetwork && transaction?.from) {
retrieveData(
requestedNetwork.namespace,
requestedNetwork.chainId,
transaction.from,
);
}
}
}, [retrieveData, sanitizePath, route, networksData, requestEvent, chainId, transaction]);
const isSufficientFunds = useMemo(() => {
if (!transaction.value) {
return;
@@ -218,7 +139,7 @@ const ApproveTransfer = ({ route }: ApproveTransferProps) => {
).privKey;
const sender = await DirectSecp256k1Wallet.fromKey(
Uint8Array.from(Buffer.from(cosmosPrivKey.split('0x')[1], 'hex')),
Buffer.from(cosmosPrivKey.split('0x')[1], 'hex'),
requestedNetwork?.addressPrefix,
);
@@ -264,6 +185,26 @@ const ApproveTransfer = ({ route }: ApproveTransferProps) => {
}
}, [requestedNetwork, namespace]);
const navigation =
useNavigation<NativeStackNavigationProp<StackParamsList>>();
const retrieveData = useCallback(
async (requestAddress: string) => {
const requestAccount = await retrieveSingleAccount(
requestedNetwork!.namespace,
requestedNetwork!.chainId,
requestAddress,
);
if (!requestAccount) {
navigation.navigate('InvalidPath');
return;
}
setAccount(requestAccount);
},
[navigation, requestedNetwork],
);
useEffect(() => {
// Set loading to false when gas values for requested chain are fetched
// If requested chain is EVM compatible, the cosmos gas values will be undefined and vice-versa, hence the condition checks only one of them at the same time
@@ -305,6 +246,9 @@ const ApproveTransfer = ({ route }: ApproveTransferProps) => {
requestedNetwork,
ethMaxFee,
]);
useEffect(() => {
retrieveData(transaction.from!);
}, [retrieveData, transaction]);
const isEIP1559 = useMemo(() => {
if (cosmosGasLimit) {
@@ -316,101 +260,6 @@ const ApproveTransfer = ({ route }: ApproveTransferProps) => {
return false;
}, [cosmosGasLimit, ethMaxFee, ethMaxPriorityFee]);
const handleIntent = async () => {
if (!account) {
throw new Error('Account is not valid');
}
if (route.path) {
const sanitizedRoute = sanitizePath(route.path);
if (!sanitizedRoute) {
throw new Error('Invalid path');
}
const requestedNetwork = networksData.find(
networkData => networkData.chainId === sanitizedRoute.chainId,
);
if (!requestedNetwork) {
throw new Error('Network not found');
}
const cosmosPrivKey = (
await getPathKey(
`${requestedNetwork.namespace}:${requestedNetwork.chainId}`,
account.index,
)
).privKey;
const sender = await DirectSecp256k1Wallet.fromKey(
Uint8Array.from(Buffer.from(cosmosPrivKey.split('0x')[1], 'hex')),
requestedNetwork.addressPrefix,
);
const client = await SigningStargateClient.connectWithSigner(
requestedNetwork.rpcUrl!,
sender,
);
const sendMsg: MsgSendEncodeObject = {
typeUrl: '/cosmos.bank.v1beta1.MsgSend',
value: {
fromAddress: account.address,
toAddress: sanitizedRoute.to,
amount: [
{
amount: String(sanitizedRoute.amount),
denom: requestedNetwork.nativeDenom!,
},
],
},
};
const gasEstimation = await client.simulate(
account.address,
[sendMsg],
MEMO,
);
const gasLimit = String(
Math.round(gasEstimation * Number(process.env.REACT_APP_GAS_ADJUSTMENT)),
);
const gasPrice = GasPrice.fromString(
requestedNetwork.gasPrice! + requestedNetwork.nativeDenom,
);
const cosmosFees = calculateFee(Number(gasLimit), gasPrice);
const result = await client.signAndBroadcast(
account.address,
[sendMsg],
{
amount: [
{
amount: cosmosFees.amount[0].amount,
denom: requestedNetwork.nativeDenom!,
},
],
gas: gasLimit,
},
MEMO,
);
// Convert BigInt values to strings before sending to Android
const serializedResult = JSON.stringify(result, (key, value) =>
typeof value === 'bigint' ? value.toString() : value
);
// Send the result back to Android and close dialog
if (window.Android?.onTransferComplete) {
window.Android.onTransferComplete(serializedResult);
} else {
alert(`Transaction: ${serializedResult}`);
}
}
};
const acceptRequestHandler = async () => {
setIsTxLoading(true);
try {
@@ -418,80 +267,77 @@ const ApproveTransfer = ({ route }: ApproveTransferProps) => {
throw new Error('account not found');
}
if (requestEvent) {
// Handle WalletConnect request
if (ethGasLimit && ethGasLimit.lt(ETH_MINIMUM_GAS)) {
throw new Error(`Atleast ${ETH_MINIMUM_GAS} gas limit is required`);
}
if (ethMaxFee && ethMaxPriorityFee && ethMaxFee.lte(ethMaxPriorityFee)) {
throw new Error(
`Max fee per gas (${ethMaxFee.toNumber()}) cannot be lower than or equal to max priority fee per gas (${ethMaxPriorityFee.toNumber()})`,
);
}
let options: WalletConnectRequests;
switch (requestMethod) {
case EIP155_SIGNING_METHODS.ETH_SEND_TRANSACTION:
if (
ethMaxFee === undefined ||
ethMaxPriorityFee === undefined ||
ethGasPrice === undefined
) {
throw new Error('Gas values not found');
}
options = {
type: 'eth_sendTransaction',
provider: provider!,
ethGasLimit: BigNumber.from(ethGasLimit),
ethGasPrice: ethGasPrice ? ethGasPrice.toHexString() : null,
maxFeePerGas: ethMaxFee,
maxPriorityFeePerGas: ethMaxPriorityFee,
};
break;
case COSMOS_METHODS.COSMOS_SEND_TOKENS:
if (!cosmosStargateClient) {
throw new Error('Cosmos stargate client not found');
}
options = {
type: 'cosmos_sendTokens',
signingStargateClient: cosmosStargateClient,
cosmosFee: {
amount: [
{
amount: fees,
denom: requestedNetwork!.nativeDenom!,
},
],
gas: cosmosGasLimit,
},
sendMsg,
memo: MEMO,
};
break;
default:
throw new Error('Invalid method');
}
const response = await approveWalletConnectRequest(
requestEvent,
account!,
namespace,
requestedNetwork!.chainId,
options,
);
const { topic } = requestEvent;
await web3wallet!.respondSessionRequest({ topic, response });
navigation.navigate('Home');
} else {
// Handle direct intent
await handleIntent();
navigation.navigate('Home');
if (ethGasLimit && ethGasLimit.lt(ETH_MINIMUM_GAS)) {
throw new Error(`Atleast ${ETH_MINIMUM_GAS} gas limit is required`);
}
if (ethMaxFee && ethMaxPriorityFee && ethMaxFee.lte(ethMaxPriorityFee)) {
throw new Error(
`Max fee per gas (${ethMaxFee.toNumber()}) cannot be lower than or equal to max priority fee per gas (${ethMaxPriorityFee.toNumber()})`,
);
}
let options: WalletConnectRequests;
switch (requestMethod) {
case EIP155_SIGNING_METHODS.ETH_SEND_TRANSACTION:
if (
ethMaxFee === undefined ||
ethMaxPriorityFee === undefined ||
ethGasPrice === undefined
) {
throw new Error('Gas values not found');
}
options = {
type: 'eth_sendTransaction',
provider: provider!,
ethGasLimit: BigNumber.from(ethGasLimit),
ethGasPrice: ethGasPrice ? ethGasPrice.toHexString() : null,
maxFeePerGas: ethMaxFee,
maxPriorityFeePerGas: ethMaxPriorityFee,
};
break;
case COSMOS_METHODS.COSMOS_SEND_TOKENS:
if (!cosmosStargateClient) {
throw new Error('Cosmos stargate client not found');
}
options = {
type: 'cosmos_sendTokens',
signingStargateClient: cosmosStargateClient,
// StdFee object
cosmosFee: {
// This amount is total fees required for transaction
amount: [
{
amount: fees,
denom: requestedNetwork!.nativeDenom!,
},
],
gas: cosmosGasLimit,
},
sendMsg,
memo: MEMO,
};
break;
default:
throw new Error('Invalid method');
}
const response = await approveWalletConnectRequest(
requestEvent,
account,
namespace,
requestedNetwork!.chainId,
options,
);
const { topic } = requestEvent;
await web3wallet!.respondSessionRequest({ topic, response });
navigation.navigate('Home');
} catch (error) {
if (!(error instanceof Error)) {
throw error;
@@ -504,26 +350,20 @@ const ApproveTransfer = ({ route }: ApproveTransferProps) => {
};
const rejectRequestHandler = async () => {
if (requestEvent) {
const response = rejectWalletConnectRequest(requestEvent);
const { topic } = requestEvent;
await web3wallet!.respondSessionRequest({
topic,
response,
});
}
const response = rejectWalletConnectRequest(requestEvent);
const { topic } = requestEvent;
await web3wallet!.respondSessionRequest({
topic,
response,
});
if (window.Android?.onTransferCancelled) {
window.Android.onTransferCancelled();
} else {
navigation.navigate('Home');
}
navigation.navigate('Home');
};
useEffect(() => {
const getAccountBalance = async () => {
try {
if (!account || !requestedNetwork) {
if (!account) {
return;
}
if (namespace === EIP155) {
@@ -533,20 +373,20 @@ const ApproveTransfer = ({ route }: ApproveTransferProps) => {
const fetchedBalance = await provider.getBalance(account.address);
setBalance(fetchedBalance ? fetchedBalance.toString() : '0');
} else {
if (!cosmosStargateClient) {
return;
}
const cosmosBalance = await cosmosStargateClient.getBalance(
const cosmosBalance = await cosmosStargateClient?.getBalance(
account.address,
requestedNetwork.nativeDenom!.toLowerCase(),
requestedNetwork!.nativeDenom!.toLowerCase(),
);
setBalance(cosmosBalance?.amount || '0');
setBalance(cosmosBalance?.amount!);
}
} catch (error) {
console.error('Error fetching balance:', error);
setBalance('0');
// Don't show error dialog for balance fetch failures
// Just set balance to 0 and let the transaction proceed
if (!(error instanceof Error)) {
throw error;
}
setTxError(error.message);
setIsTxErrorDialogOpen(true);
}
};
@@ -668,18 +508,16 @@ const ApproveTransfer = ({ route }: ApproveTransferProps) => {
) : (
<>
<ScrollView contentContainerStyle={styles.appContainer}>
{requestSession && (
<View style={styles.dappDetails}>
{requestIcon && (
<Image
style={styles.dappLogo}
source={requestIcon ? { uri: requestIcon } : undefined}
/>
)}
<Text>{requestName}</Text>
<Text variant="bodyMedium">{requestURL}</Text>
</View>
)}
<View style={styles.dappDetails}>
{requestIcon && (
<Image
style={styles.dappLogo}
source={requestIcon ? { uri: requestIcon } : undefined}
/>
)}
<Text>{requestName}</Text>
<Text variant="bodyMedium">{requestURL}</Text>
</View>
<View style={styles.dataBoxContainer}>
<Text style={styles.dataBoxLabel}>From</Text>
<View style={styles.dataBox}>
@@ -690,7 +528,11 @@ const ApproveTransfer = ({ route }: ApproveTransferProps) => {
label={`Balance (${
namespace === EIP155 ? 'wei' : requestedNetwork!.nativeDenom
})`}
data={balance || '0'}
data={
balance === '' || balance === undefined
? 'Loading balance...'
: `${balance}`
}
/>
{transaction && (
<View style={styles.approveTransfer}>
+177
View File
@@ -0,0 +1,177 @@
import React, { useEffect, useState } from 'react';
import { ScrollView, View } from 'react-native';
import { ActivityIndicator, Button, Text, Appbar } from 'react-native-paper';
import { useNavigation } from '@react-navigation/native';
import {
NativeStackNavigationProp,
NativeStackScreenProps,
} from '@react-navigation/native-stack';
import { getHeaderTitle } from '@react-navigation/elements';
import { Account, StackParamsList } from '../types';
import AccountDetails from '../components/AccountDetails';
import styles from '../styles/stylesheet';
import { getCosmosAccounts, retrieveSingleAccount } from '../utils/accounts';
import { getMnemonic, getPathKey, sendMessage } from '../utils/misc';
import { COSMOS } from '../utils/constants';
type SignRequestProps = NativeStackScreenProps<StackParamsList, 'sign-message-embed'>;
const SignMessageEmbed = ({ route }: SignRequestProps) => {
const [displayAccount, setDisplayAccount] = useState<Account>();
const [message, setMessage] = useState<string>('');
const [chainId, setChainId] = useState<string>('');
const [signDoc, setSignDoc] = useState<any>(null);
const [signerAddress, setSignerAddress] = useState<string>('');
const [origin, setOrigin] = useState<string>('');
const [sourceWindow, setSourceWindow] = useState<Window | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isApproving, setIsApproving] = useState(false);
const navigation =
useNavigation<NativeStackNavigationProp<StackParamsList>>();
const signMessageHandler = async () => {
if (!signDoc || !signerAddress || !sourceWindow) return;
setIsApproving(true);
try {
const requestAccount = await retrieveSingleAccount(COSMOS, chainId, signerAddress);
const path = (await getPathKey(`${COSMOS}:${chainId}`, requestAccount!.index)).path;
const mnemonic = await getMnemonic();
const cosmosAccount = await getCosmosAccounts(mnemonic, path, 'zenith');
const cosmosAminoSignature = await cosmosAccount.cosmosWallet.signAmino(
signerAddress,
signDoc,
);
const signature = cosmosAminoSignature.signature.signature;
sendMessage(
sourceWindow,
'ZENITH_SIGNED_MESSAGE',
{ signature },
origin,
);
navigation.navigate('Home');
} catch (err) {
console.error('Signing failed:', err);
sendMessage(
sourceWindow!,
'ZENITH_SIGNED_MESSAGE',
{ error: err },
origin,
);
} finally {
setIsApproving(false);
}
};
const rejectRequestHandler = async () => {
if (sourceWindow && origin) {
sendMessage(
sourceWindow,
'ZENITH_SIGNED_MESSAGE',
{ error: 'User rejected the request' },
origin,
);
}
navigation.navigate('Home');
};
useEffect(() => {
const handleCosmosSignMessage = async (event: MessageEvent) => {
if (event.data.type !== 'SIGN_ZENITH_MESSAGE') return;
try {
const { signerAddress, signDoc } = event.data.params;
setSignerAddress(signerAddress);
setSignDoc(signDoc);
setMessage(signDoc.memo || '');
setOrigin(event.origin);
setSourceWindow(event.source as Window);
setChainId(event.data.chainId);
const requestAccount = await retrieveSingleAccount(
COSMOS,
event.data.chainId,
signerAddress,
);
setDisplayAccount(requestAccount);
setIsLoading(false);
} catch (err) {
console.error('Error preparing sign request:', err);
setIsLoading(false);
}
};
window.addEventListener('message', handleCosmosSignMessage);
return () => window.removeEventListener('message', handleCosmosSignMessage);
}, []);
useEffect(() => {
navigation.setOptions({
// eslint-disable-next-line react/no-unstable-nested-components
header: ({ options, back }) => {
const title = getHeaderTitle(options, 'Sign Message');
return (
<Appbar.Header>
{back && (
<Appbar.BackAction
onPress={async () => {
await rejectRequestHandler();
navigation.navigate('Home');
}}
/>
)}
<Appbar.Content title={title} />
</Appbar.Header>
);
},
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [navigation, route.name]);
return (
<>
{isLoading ? (
<View style={styles.spinnerContainer}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
) : (
<>
<ScrollView contentContainerStyle={styles.appContainer}>
<AccountDetails account={displayAccount} />
<View style={styles.requestMessage}>
<Text variant="bodyLarge">{message}</Text>
</View>
</ScrollView>
<View style={styles.buttonContainer}>
<Button
mode="contained"
onPress={signMessageHandler}
loading={isApproving}
disabled={isApproving}>
Yes
</Button>
<Button
mode="contained"
onPress={rejectRequestHandler}
buttonColor="#B82B0D">
No
</Button>
</View>
</>
)}
</>
);
};
export default SignMessageEmbed;
+2
View File
@@ -40,6 +40,8 @@ export type StackParamsList = {
};
"wallet-embed": undefined;
"auto-sign-in": undefined;
"sign-message-embed": undefined;
"add-account-embed": undefined;
};
export type Account = {
+15 -3
View File
@@ -18,6 +18,18 @@ export const DEFAULT_NETWORKS: NetworksFormData[] = [
gasPrice: '0.001',
isDefault: true,
},
{
chainId: 'zenith-testnet',
networkName: 'zenithd testnet',
namespace: COSMOS,
rpcUrl: 'http://127.0.0.1:26657',
blockExplorerUrl: '',
nativeDenom: 'znt',
addressPrefix: 'zenith',
coinType: '118',
gasPrice: '0.01',
isDefault: true,
},
{
chainId: 'laconic_9000-1',
networkName: 'laconicd',
@@ -41,10 +53,10 @@ export const DEFAULT_NETWORKS: NetworksFormData[] = [
isDefault: true,
},
{
chainId: 'provider',
networkName: COSMOS_TESTNET_CHAINS['cosmos:provider'].name,
chainId: 'theta-testnet-001',
networkName: COSMOS_TESTNET_CHAINS['cosmos:theta-testnet-001'].name,
namespace: COSMOS,
rpcUrl: COSMOS_TESTNET_CHAINS['cosmos:provider'].rpc,
rpcUrl: COSMOS_TESTNET_CHAINS['cosmos:theta-testnet-001'].rpc,
blockExplorerUrl: '',
nativeDenom: 'uatom',
addressPrefix: 'cosmos',
+3 -3
View File
@@ -19,10 +19,10 @@ export const COSMOS_TESTNET_CHAINS: Record<
namespace: string;
}
> = {
'cosmos:provider': {
chainId: 'provider',
'cosmos:theta-testnet-001': {
chainId: 'theta-testnet-001',
name: 'Cosmos Hub Testnet',
rpc: 'https://rpc-rs.cosmos.nodestake.top',
rpc: 'https://rpc-t.cosmos.nodestake.top',
namespace: 'cosmos',
},
};