Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3fdf6e39a4 | ||
|
|
563bb8d31a | ||
|
|
6b0a730a2d | ||
|
|
6d5fcf798d | ||
|
|
3a0a321c6f | ||
|
|
59176ad7cb | ||
|
|
0b4ceae6b2 | ||
|
|
cbb28a6eb3 |
+2
-1
@@ -1,6 +1,7 @@
|
||||
REACT_APP_WALLET_CONNECT_PROJECT_ID=
|
||||
|
||||
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_AUTH_SECRET=
|
||||
REACT_APP_DEPLOY_APP_URL=
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
build
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "web-wallet",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@cerc-io/registry-sdk": "^0.2.5",
|
||||
|
||||
+36
-7
@@ -39,7 +39,10 @@ import { Header } from "./components/Header";
|
||||
import { WalletEmbed } from "./screens/WalletEmbed";
|
||||
import { AutoSignIn } from "./screens/AutoSignIn";
|
||||
import { checkSufficientFunds, getPathKey, sendMessage } from "./utils/misc";
|
||||
import { retrieveSingleAccount } from "./utils/accounts";
|
||||
import useAccountsData from "./hooks/useAccountsData";
|
||||
import { useWebViewHandler } from "./hooks/useWebViewHandler";
|
||||
import SignMessageEmbed from "./screens/SignMessageEmbed";
|
||||
import { AddAccountEmbed } from "./screens/AddAccountEmbed";
|
||||
|
||||
const Stack = createStackNavigator<StackParamsList>();
|
||||
|
||||
@@ -49,6 +52,8 @@ const App = (): React.JSX.Element => {
|
||||
const { web3wallet, setActiveSessions } = useWalletConnect();
|
||||
const { accounts, setCurrentIndex } = useAccounts();
|
||||
const { networksData, selectedNetwork, setSelectedNetwork } = useNetworks();
|
||||
const { getAccountsData } = useAccountsData();
|
||||
|
||||
const [modalVisible, setModalVisible] = useState(false);
|
||||
const [toastVisible, setToastVisible] = useState(false);
|
||||
const [currentProposal, setCurrentProposal] = useState<
|
||||
@@ -227,7 +232,7 @@ const App = (): React.JSX.Element => {
|
||||
const handleCheckBalance = async (event: MessageEvent) => {
|
||||
if (event.data.type !== 'CHECK_BALANCE') return;
|
||||
|
||||
const { chainId, address, amount } = event.data;
|
||||
const { chainId, amount } = event.data;
|
||||
const network = networksData.find(net => net.chainId === chainId);
|
||||
|
||||
if (!network) {
|
||||
@@ -235,11 +240,18 @@ const App = (): React.JSX.Element => {
|
||||
throw new Error('Requested network not supported.');
|
||||
}
|
||||
|
||||
const account = await retrieveSingleAccount(network.namespace, network.chainId, address);
|
||||
if (!account) {
|
||||
throw new Error('Account not found for the requested address.');
|
||||
if (network.namespace !== COSMOS) {
|
||||
throw new Error('Unsupported network');
|
||||
}
|
||||
|
||||
const accounts = await getAccountsData(chainId);
|
||||
const account = accounts[0];
|
||||
|
||||
if (!account) {
|
||||
throw new Error(`No accounts in network ${chainId}`);
|
||||
}
|
||||
|
||||
|
||||
const cosmosPrivKey = (
|
||||
await getPathKey(`${network.namespace}:${chainId}`, account.index)
|
||||
).privKey;
|
||||
@@ -256,7 +268,7 @@ const App = (): React.JSX.Element => {
|
||||
network.nativeDenom!.toLowerCase()
|
||||
);
|
||||
|
||||
const areFundsSufficient = !checkSufficientFunds(amount, balance.amount);
|
||||
const areFundsSufficient = checkSufficientFunds(amount, balance.amount);
|
||||
|
||||
sendMessage(event.source as Window, 'IS_SUFFICIENT', areFundsSufficient, event.origin);
|
||||
};
|
||||
@@ -266,10 +278,12 @@ const App = (): React.JSX.Element => {
|
||||
return () => {
|
||||
window.removeEventListener('message', handleCheckBalance);
|
||||
};
|
||||
}, [networksData]);
|
||||
}, [networksData, getAccountsData]);
|
||||
|
||||
const showWalletConnect = useMemo(() => accounts.length > 0, [accounts]);
|
||||
|
||||
useWebViewHandler();
|
||||
|
||||
return (
|
||||
<Surface style={styles.appSurface}>
|
||||
<Stack.Navigator
|
||||
@@ -378,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}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from 'react';
|
||||
|
||||
import { NetworksDataState } from '../types';
|
||||
import { retrieveNetworksData, storeNetworkData } from '../utils/accounts';
|
||||
import { retrieveNetworksData } from '../utils/accounts';
|
||||
import { DEFAULT_NETWORKS, EIP155 } from '../utils/constants';
|
||||
import { setInternetCredentials } from '../utils/key-store';
|
||||
|
||||
const NetworksContext = createContext<{
|
||||
networksData: NetworksDataState[];
|
||||
@@ -27,28 +28,38 @@ const useNetworks = () => {
|
||||
return networksContext;
|
||||
};
|
||||
|
||||
const DEFAULT_NETWORKS_DATA = DEFAULT_NETWORKS.map((defaultNetwork, index) => (
|
||||
{
|
||||
...defaultNetwork,
|
||||
networkId: index.toString()
|
||||
})
|
||||
);
|
||||
|
||||
const NetworksProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
const [networksData, setNetworksData] = useState<NetworksDataState[]>([]);
|
||||
const [networksData, setNetworksData] = useState<NetworksDataState[]>(DEFAULT_NETWORKS_DATA);
|
||||
const [networkType, setNetworkType] = useState<string>(EIP155);
|
||||
const [selectedNetwork, setSelectedNetwork] = useState<NetworksDataState>();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
const retrievedNetworks = await retrieveNetworksData();
|
||||
let retrievedNetworks = await retrieveNetworksData();
|
||||
|
||||
if (retrievedNetworks.length === 0) {
|
||||
for (const defaultNetwork of DEFAULT_NETWORKS) {
|
||||
await storeNetworkData(defaultNetwork);
|
||||
}
|
||||
setInternetCredentials(
|
||||
'networks',
|
||||
'_',
|
||||
JSON.stringify(DEFAULT_NETWORKS_DATA),
|
||||
);
|
||||
|
||||
retrievedNetworks = DEFAULT_NETWORKS_DATA;
|
||||
}
|
||||
const retrievedNewNetworks = await retrieveNetworksData();
|
||||
setNetworksData(retrievedNewNetworks);
|
||||
setSelectedNetwork(retrievedNewNetworks[0]);
|
||||
|
||||
setNetworksData(retrievedNetworks);
|
||||
setSelectedNetwork(retrievedNetworks[0]);
|
||||
};
|
||||
|
||||
if (networksData.length === 0) {
|
||||
fetchData();
|
||||
}
|
||||
}, [networksData]);
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedNetwork(prevSelectedNetwork => {
|
||||
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
// Extends the Window interface for Android WebView communication
|
||||
declare global {
|
||||
interface Window {
|
||||
// Android bridge callbacks for signature and accounts related events
|
||||
Android?: {
|
||||
// Called when signature is successfully generated
|
||||
onSignatureComplete?: (signature: string) => void;
|
||||
|
||||
// Called when signature generation fails
|
||||
onSignatureError?: (error: string) => void;
|
||||
|
||||
// Called when signature process is cancelled
|
||||
onSignatureCancelled?: () => void;
|
||||
|
||||
// Called when accounts are ready for use
|
||||
onAccountsReady?: () => void;
|
||||
};
|
||||
|
||||
// Handles incoming signature requests from Android
|
||||
receiveSignRequestFromAndroid?: (message: string) => void;
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { retrieveAccounts } from "../utils/accounts";
|
||||
import { useNetworks } from "../context/NetworksContext";
|
||||
|
||||
const useAccountsData = () => {
|
||||
const { networksData } = useNetworks();
|
||||
|
||||
const getAccountsData = useCallback(async (chainId: string) => {
|
||||
const targetNetwork = networksData.find(network => network.chainId === chainId);
|
||||
|
||||
if (!targetNetwork) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const accounts = await retrieveAccounts(targetNetwork);
|
||||
return accounts || [];
|
||||
}, [networksData]);
|
||||
|
||||
return { getAccountsData };
|
||||
};
|
||||
|
||||
export default useAccountsData;
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useEffect, useCallback } from "react";
|
||||
|
||||
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) => {
|
||||
let accountsData = await getAccountsData(chainId);
|
||||
|
||||
if (accountsData.length === 0) {
|
||||
console.log("Accounts not found, creating wallet...");
|
||||
await createWallet(networksData);
|
||||
accountsData = await getAccountsData(chainId);
|
||||
}
|
||||
|
||||
// Update the AccountsContext with the new accounts
|
||||
setAccounts(accountsData);
|
||||
|
||||
return accountsData;
|
||||
}, [networksData, getAccountsData, setAccounts]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleCreateAccounts = async (event: MessageEvent) => {
|
||||
if (event.data.type !== 'REQUEST_CREATE_OR_GET_ACCOUNTS') return;
|
||||
|
||||
const accountsData = await getOrCreateAccountsForChain(event.data.chainId);
|
||||
|
||||
sendMessage(
|
||||
event.source as Window, 'WALLET_ACCOUNTS_DATA',
|
||||
accountsData.map(account => account.address),
|
||||
event.origin
|
||||
);
|
||||
};
|
||||
|
||||
const autoCreateAccounts = async () => {
|
||||
const defaultChainId = networksData[0]?.chainId;
|
||||
|
||||
if (!defaultChainId) {
|
||||
console.log('useGetOrCreateAccounts: No default chainId found');
|
||||
return;
|
||||
}
|
||||
const accounts = await getOrCreateAccountsForChain(defaultChainId);
|
||||
|
||||
// Only notify Android when we actually have accounts
|
||||
if (accounts.length > 0 && window.Android?.onAccountsReady) {
|
||||
window.Android.onAccountsReady();
|
||||
} else {
|
||||
console.log('No accounts created or Android bridge not available');
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleCreateAccounts);
|
||||
|
||||
const isAndroidWebView = !!(window.Android);
|
||||
|
||||
if (isAndroidWebView) {
|
||||
autoCreateAccounts();
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('message', handleCreateAccounts);
|
||||
};
|
||||
}, [networksData, getAccountsData, getOrCreateAccountsForChain]);
|
||||
};
|
||||
|
||||
export default useGetOrCreateAccounts;
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useEffect, useCallback } from 'react';
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
|
||||
|
||||
import { useAccounts } from '../context/AccountsContext';
|
||||
import { useNetworks } from '../context/NetworksContext';
|
||||
import { StackParamsList } from '../types';
|
||||
import useGetOrCreateAccounts from './useGetOrCreateAccounts';
|
||||
|
||||
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 {
|
||||
// Validation checks
|
||||
if (!selectedNetwork?.namespace || !selectedNetwork?.chainId) {
|
||||
window.Android?.onSignatureError?.('Invalid network configuration');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!accounts?.length) {
|
||||
window.Android?.onSignatureError?.('No accounts available');
|
||||
return;
|
||||
}
|
||||
|
||||
const currentAccount = accounts[currentIndex];
|
||||
if (!currentAccount) {
|
||||
window.Android?.onSignatureError?.('Current account not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the path and validate with regex
|
||||
const path = `/sign/${selectedNetwork.namespace}/${selectedNetwork.chainId}/${currentAccount.address}/${encodeURIComponent(message)}`;
|
||||
const pathRegex = /^\/sign\/(eip155|cosmos)\/(.+)\/(.+)\/(.+)$/;
|
||||
const match = path.match(pathRegex);
|
||||
|
||||
if (!match) {
|
||||
window.Android?.onSignatureError?.('Invalid signing path');
|
||||
return;
|
||||
}
|
||||
|
||||
const [, pathNamespace, pathChainId, pathAddress, pathMessage] = match;
|
||||
|
||||
// Reset navigation stack and navigate to sign request
|
||||
navigation.reset({
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: 'SignRequest',
|
||||
path,
|
||||
params: {
|
||||
namespace: pathNamespace,
|
||||
chainId: pathChainId,
|
||||
address: pathAddress,
|
||||
message: decodeURIComponent(pathMessage),
|
||||
accountInfo: currentAccount,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
} catch (error) {
|
||||
window.Android?.onSignatureError?.(`Navigation error: ${error}`);
|
||||
}
|
||||
}, [selectedNetwork, accounts, currentIndex, navigation]);
|
||||
|
||||
useEffect(() => {
|
||||
// Assign the function to the window object
|
||||
window.receiveSignRequestFromAndroid = navigateToSignRequest;
|
||||
|
||||
return () => {
|
||||
window.receiveSignRequestFromAndroid = undefined;
|
||||
};
|
||||
}, [navigateToSignRequest]); // Only the function reference as dependency
|
||||
};
|
||||
@@ -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 (
|
||||
<>
|
||||
</>
|
||||
)
|
||||
};
|
||||
+12
-60
@@ -1,43 +1,26 @@
|
||||
import React, { useEffect, useCallback } from 'react';
|
||||
import React, { useEffect } from 'react';
|
||||
|
||||
import { createWallet, retrieveAccounts } from '../utils/accounts';
|
||||
import { useNetworks } from '../context/NetworksContext';
|
||||
import { Account } from '../types';
|
||||
import { signMessage } from '../utils/sign-message';
|
||||
import { EIP155 } from '../utils/constants';
|
||||
import { sendMessage } from '../utils/misc';
|
||||
import useAccountsData from '../hooks/useAccountsData';
|
||||
import useGetOrCreateAccounts from '../hooks/useGetOrCreateAccounts';
|
||||
|
||||
export const AutoSignIn = () => {
|
||||
const { networksData } = useNetworks();
|
||||
|
||||
const getAccountsData = useCallback(async (chainId: string): Promise<Account[]> => {
|
||||
const targetNetwork = networksData.find(network => network.chainId === chainId);
|
||||
|
||||
if (!targetNetwork) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const accounts = await retrieveAccounts(targetNetwork);
|
||||
|
||||
if (!accounts || accounts.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return accounts
|
||||
}, [networksData]);
|
||||
|
||||
const sendMessage = (
|
||||
source: Window | null,
|
||||
type: string,
|
||||
data: any,
|
||||
origin: string
|
||||
): void => {
|
||||
source?.postMessage({ type, data }, origin);
|
||||
};
|
||||
const { getAccountsData } = useAccountsData();
|
||||
|
||||
useEffect(() => {
|
||||
const handleSignIn = async (event: MessageEvent) => {
|
||||
if (event.data.type !== 'AUTO_SIGN_IN') return;
|
||||
|
||||
if (event.origin !== process.env.REACT_APP_DEPLOY_APP_URL) {
|
||||
console.log('Unauthorized app.');
|
||||
return;
|
||||
}
|
||||
|
||||
const accountsData = await getAccountsData(event.data.chainId);
|
||||
|
||||
if (!accountsData.length) {
|
||||
@@ -56,39 +39,8 @@ export const AutoSignIn = () => {
|
||||
};
|
||||
}, [networksData, getAccountsData]);
|
||||
|
||||
useEffect(() => {
|
||||
const getAccountAddress = async (event: MessageEvent) => {
|
||||
if (event.data.type !== 'GET_ACCOUNT_ADDRESS') return;
|
||||
|
||||
|
||||
if (event.data.secret !== process.env.REACT_APP_AUTH_SECRET) {
|
||||
console.log('Unauthorized app.');
|
||||
return;
|
||||
}
|
||||
|
||||
let accountsData = await getAccountsData(event.data.chainId);
|
||||
|
||||
if (accountsData.length === 0) {
|
||||
console.log("Accounts not found, creating wallet...");
|
||||
await createWallet(networksData);
|
||||
|
||||
// Re-fetch newly created accounts
|
||||
accountsData = await getAccountsData(event.data.chainId);
|
||||
}
|
||||
|
||||
if (!accountsData.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
sendMessage(event.source as Window, 'ACCOUNT_ADDRESS_RESPONSE', accountsData[0].address, event.origin);
|
||||
};
|
||||
|
||||
window.addEventListener('message', getAccountAddress);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('message', getAccountAddress);
|
||||
};
|
||||
}, [networksData, getAccountsData]);
|
||||
// Custom hook for adding listener to get accounts data
|
||||
useGetOrCreateAccounts();
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -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;
|
||||
@@ -202,7 +202,13 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
||||
chainId,
|
||||
accountId: account.index,
|
||||
});
|
||||
alert(`Signature ${signedMessage}`);
|
||||
|
||||
// Send the result back to Android and close dialog
|
||||
if (window.Android?.onSignatureComplete) {
|
||||
window.Android.onSignatureComplete(signedMessage || "");
|
||||
} else {
|
||||
alert(`Signature: ${signedMessage}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -230,7 +236,11 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
||||
}
|
||||
|
||||
setIsRejecting(false);
|
||||
navigation.navigate('Home');
|
||||
if (window.Android?.onSignatureCancelled) {
|
||||
window.Android.onSignatureCancelled();
|
||||
} else {
|
||||
navigation.navigate('Home');
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
+13
-43
@@ -15,7 +15,7 @@ import {
|
||||
SigningStargateClient,
|
||||
} from '@cosmjs/stargate';
|
||||
|
||||
import { createWallet, retrieveAccounts, retrieveSingleAccount } from '../utils/accounts';
|
||||
import { retrieveSingleAccount } from '../utils/accounts';
|
||||
import AccountDetails from '../components/AccountDetails';
|
||||
import styles from '../styles/stylesheet';
|
||||
import DataBox from '../components/DataBox';
|
||||
@@ -24,6 +24,8 @@ import { useNetworks } from '../context/NetworksContext';
|
||||
import TxErrorDialog from '../components/TxErrorDialog';
|
||||
import { MEMO } from '../screens/ApproveTransfer';
|
||||
import { Account, NetworksDataState } from '../types';
|
||||
import useGetOrCreateAccounts from '../hooks/useGetOrCreateAccounts';
|
||||
import useAccountsData from '../hooks/useAccountsData';
|
||||
|
||||
type TransactionDetails = {
|
||||
chainId: string;
|
||||
@@ -45,22 +47,7 @@ export const WalletEmbed = () => {
|
||||
const txEventRef = useRef<MessageEvent | null>(null);
|
||||
|
||||
const { networksData } = useNetworks();
|
||||
|
||||
const getAccountsData = useCallback(async (chainId: string): Promise<string[]> => {
|
||||
const targetNetwork = networksData.find(network => network.chainId === chainId);
|
||||
|
||||
if (!targetNetwork) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const accounts = await retrieveAccounts(targetNetwork);
|
||||
|
||||
if (!accounts || accounts.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return accounts.map(account => account.address);
|
||||
}, [networksData]);
|
||||
const { getAccountsData } = useAccountsData();
|
||||
|
||||
useEffect(() => {
|
||||
const handleGetAccounts = async (event: MessageEvent) => {
|
||||
@@ -73,7 +60,12 @@ export const WalletEmbed = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
sendMessage(event.source as Window, 'WALLET_ACCOUNTS_DATA', accountsData, event.origin);
|
||||
sendMessage(
|
||||
event.source as Window,
|
||||
'WALLET_ACCOUNTS_DATA',
|
||||
accountsData.map(account => account.address),
|
||||
event.origin
|
||||
);
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleGetAccounts);
|
||||
@@ -83,29 +75,8 @@ export const WalletEmbed = () => {
|
||||
};
|
||||
}, [getAccountsData]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleCreateAccounts = async (event: MessageEvent) => {
|
||||
if (event.data.type !== 'REQUEST_CREATE_OR_GET_ACCOUNTS') return;
|
||||
|
||||
let accountsData = await getAccountsData(event.data.chainId);
|
||||
|
||||
if (accountsData.length === 0) {
|
||||
console.log("Accounts not found, creating wallet...");
|
||||
await createWallet(networksData);
|
||||
|
||||
// Re-fetch newly created accounts
|
||||
accountsData = await getAccountsData(event.data.chainId);
|
||||
}
|
||||
|
||||
sendMessage(event.source as Window, 'WALLET_ACCOUNTS_DATA', accountsData, event.origin);
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleCreateAccounts);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('message', handleCreateAccounts);
|
||||
};
|
||||
}, [networksData, getAccountsData]);
|
||||
// Custom hook for adding listener to get accounts data
|
||||
useGetOrCreateAccounts();
|
||||
|
||||
const handleTxRequested = useCallback(
|
||||
async (event: MessageEvent) => {
|
||||
@@ -168,8 +139,7 @@ export const WalletEmbed = () => {
|
||||
});
|
||||
|
||||
if (!checkSufficientFunds(amount, balance.amount)) {
|
||||
console.log("Insufficient funds detected");
|
||||
sendMessage(event.source as Window, 'INSUFFICIENT_FUNDS', null, event.origin);
|
||||
console.log("Insufficient funds detected. Throwing error.");
|
||||
throw new Error('Insufficient funds');
|
||||
}
|
||||
|
||||
|
||||
@@ -13,8 +13,10 @@ export type StackParamsList = {
|
||||
};
|
||||
SignRequest: {
|
||||
namespace: string;
|
||||
chainId?: string;
|
||||
address: string;
|
||||
message: string;
|
||||
accountInfo?: Account;
|
||||
requestEvent?: Web3WalletTypes.SessionRequest;
|
||||
requestSessionData?: SessionTypes.Struct;
|
||||
};
|
||||
@@ -38,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
-1
@@ -1,9 +1,11 @@
|
||||
import { COSMOS_TESTNET_CHAINS } from './wallet-connect/COSMOSData';
|
||||
import { EIP155_CHAINS } from './wallet-connect/EIP155Data';
|
||||
import { NetworksFormData } from '../types';
|
||||
|
||||
export const EIP155 = 'eip155';
|
||||
export const COSMOS = 'cosmos';
|
||||
export const DEFAULT_NETWORKS = [
|
||||
|
||||
export const DEFAULT_NETWORKS: NetworksFormData[] = [
|
||||
{
|
||||
chainId: 'laconic-testnet-2',
|
||||
networkName: 'laconicd testnet-2',
|
||||
@@ -16,6 +18,18 @@ export const DEFAULT_NETWORKS = [
|
||||
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',
|
||||
|
||||
+1
-1
@@ -162,7 +162,7 @@ const checkSufficientFunds = (amount: string, balance: string) => {
|
||||
const amountBigNum = BigNumber.from(String(amount));
|
||||
const balanceBigNum = BigNumber.from(balance);
|
||||
|
||||
return balanceBigNum.gt(amountBigNum);
|
||||
return balanceBigNum.gte(amountBigNum);
|
||||
};
|
||||
|
||||
export {
|
||||
|
||||
@@ -3,6 +3,7 @@ For more information, "visit https://docs.ethers.org/v5/cookbook/react-native/#c
|
||||
import 'react-native-get-random-values';
|
||||
|
||||
import '@ethersproject/shims';
|
||||
import { fromBech32 } from '@cosmjs/encoding';
|
||||
|
||||
import { Wallet } from 'ethers';
|
||||
import { SignDoc } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
|
||||
@@ -24,7 +25,7 @@ const signMessage = async ({
|
||||
case EIP155:
|
||||
return await signEthMessage(message, accountId, chainId);
|
||||
case COSMOS:
|
||||
return await signCosmosMessage(message, path.path);
|
||||
return await signCosmosMessage(message, path.path, path.address);
|
||||
default:
|
||||
throw new Error('Invalid wallet type');
|
||||
}
|
||||
@@ -51,10 +52,13 @@ const signEthMessage = async (
|
||||
const signCosmosMessage = async (
|
||||
message: string,
|
||||
path: string,
|
||||
cosmosAddress: string,
|
||||
): Promise<string | undefined> => {
|
||||
try {
|
||||
const mnemonic = await getMnemonic();
|
||||
const cosmosAccount = await getCosmosAccounts(mnemonic, path);
|
||||
const addressPrefix = fromBech32(cosmosAddress).prefix
|
||||
|
||||
const cosmosAccount = await getCosmosAccounts(mnemonic, path, addressPrefix);
|
||||
const address = cosmosAccount.data.address;
|
||||
const cosmosSignature = await cosmosAccount.cosmosWallet.signAmino(
|
||||
address,
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
StdFee,
|
||||
MsgSendEncodeObject
|
||||
} from '@cosmjs/stargate';
|
||||
import { fromBech32 } from '@cosmjs/encoding';
|
||||
import { EncodeObject } from '@cosmjs/proto-signing';
|
||||
import { LaconicClient } from '@cerc-io/registry-sdk';
|
||||
import { Buffer } from 'buffer';
|
||||
@@ -19,6 +20,7 @@ import { Account } from '../../types';
|
||||
import { getMnemonic, getPathKey } from '../misc';
|
||||
import { getCosmosAccounts } from '../accounts';
|
||||
import { COSMOS_METHODS } from './COSMOSData';
|
||||
import { COSMOS } from '../constants';
|
||||
|
||||
interface EthSendTransaction {
|
||||
type: 'eth_sendTransaction';
|
||||
@@ -80,7 +82,13 @@ export async function approveWalletConnectRequest(
|
||||
const path = (await getPathKey(`${namespace}:${chainId}`, account.index))
|
||||
.path;
|
||||
const mnemonic = await getMnemonic();
|
||||
const cosmosAccount = await getCosmosAccounts(mnemonic, path);
|
||||
|
||||
let addressPrefix: string | undefined
|
||||
if (namespace === COSMOS) {
|
||||
addressPrefix = fromBech32(account.address).prefix
|
||||
}
|
||||
|
||||
const cosmosAccount = await getCosmosAccounts(mnemonic, path, addressPrefix);
|
||||
const address = account.address;
|
||||
|
||||
switch (request.method) {
|
||||
|
||||
@@ -10,6 +10,7 @@ services:
|
||||
CERC_DEFAULT_GAS_PRICE: ${CERC_DEFAULT_GAS_PRICE:-0.025}
|
||||
CERC_GAS_ADJUSTMENT: ${CERC_GAS_ADJUSTMENT:-2}
|
||||
CERC_LACONICD_RPC_URL: ${CERC_LACONICD_RPC_URL:-https://laconicd.laconic.com}
|
||||
CERC_DEPLOY_APP_URL: ${CERC_DEPLOY_APP_URL}
|
||||
command: ["bash", "/scripts/run.sh"]
|
||||
volumes:
|
||||
- ../config/app/run.sh:/scripts/run.sh
|
||||
|
||||
@@ -10,12 +10,14 @@ echo "WALLET_CONNECT_ID: ${WALLET_CONNECT_ID}"
|
||||
echo "CERC_DEFAULT_GAS_PRICE: ${CERC_DEFAULT_GAS_PRICE}"
|
||||
echo "CERC_GAS_ADJUSTMENT: ${CERC_GAS_ADJUSTMENT}"
|
||||
echo "CERC_LACONICD_RPC_URL: ${CERC_LACONICD_RPC_URL}"
|
||||
echo "CERC_DEPLOY_APP_URL: ${CERC_DEPLOY_APP_URL}"
|
||||
|
||||
# Build with required env
|
||||
REACT_APP_WALLET_CONNECT_PROJECT_ID=$WALLET_CONNECT_ID \
|
||||
REACT_APP_DEFAULT_GAS_PRICE=$CERC_DEFAULT_GAS_PRICE \
|
||||
REACT_APP_GAS_ADJUSTMENT=$CERC_GAS_ADJUSTMENT \
|
||||
REACT_APP_LACONICD_RPC_URL=$CERC_LACONICD_RPC_URL \
|
||||
REACT_APP_DEPLOY_APP_URL=$CERC_DEPLOY_APP_URL \
|
||||
yarn build
|
||||
|
||||
# Define the directory and file path
|
||||
|
||||
@@ -63,6 +63,10 @@ Instructions for running the `laconic-wallet-web` using [laconic-so](https://git
|
||||
|
||||
# RPC endpoint of laconicd node (default: https://laconicd.laconic.com)
|
||||
CERC_LACONICD_RPC_URL=
|
||||
|
||||
# Deploy app URL used for checking origin of the messages for auto-sign-in route
|
||||
# Deploy app repo: https://git.vdb.to/cerc-io/snowballtools-base
|
||||
CERC_DEPLOY_APP_URL=
|
||||
```
|
||||
|
||||
## Start the deployment
|
||||
|
||||
Reference in New Issue
Block a user