Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
accd068901 | ||
|
|
eb165655a4 | ||
|
|
1aabebf2c0 | ||
|
|
feb86bd5f8 | ||
|
|
3eedadafc3 | ||
|
|
6ad37d0fa5 | ||
|
|
ad636e5847 | ||
|
|
b3b4cc12c4 | ||
|
|
20dee55dca | ||
|
|
2e84a41aaf | ||
|
|
23151f95e5 | ||
|
|
41acca6a42 | ||
|
|
d9011dbdb2 |
+1
-2
@@ -5,5 +5,4 @@ REACT_APP_DEFAULT_GAS_PRICE=0.025
|
|||||||
REACT_APP_GAS_ADJUSTMENT=2
|
REACT_APP_GAS_ADJUSTMENT=2
|
||||||
REACT_APP_LACONICD_RPC_URL=https://laconicd-sapo.laconic.com
|
REACT_APP_LACONICD_RPC_URL=https://laconicd-sapo.laconic.com
|
||||||
|
|
||||||
# Example: https://example-url-1.com,https://example-url-2.com
|
REACT_APP_DEPLOY_APP_URL=
|
||||||
REACT_APP_ALLOWED_URLS=
|
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "web-wallet",
|
"name": "web-wallet",
|
||||||
"version": "0.1.4",
|
"version": "0.1.3",
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@cerc-io/registry-sdk": "^0.2.5",
|
"@cerc-io/registry-sdk": "^0.2.5",
|
||||||
|
|||||||
-12
@@ -41,9 +41,6 @@ import { AutoSignIn } from "./screens/AutoSignIn";
|
|||||||
import { checkSufficientFunds, getPathKey, sendMessage } from "./utils/misc";
|
import { checkSufficientFunds, getPathKey, sendMessage } from "./utils/misc";
|
||||||
import useAccountsData from "./hooks/useAccountsData";
|
import useAccountsData from "./hooks/useAccountsData";
|
||||||
import { useWebViewHandler } from "./hooks/useWebViewHandler";
|
import { useWebViewHandler } from "./hooks/useWebViewHandler";
|
||||||
import SignRequestEmbed from "./screens/SignRequestEmbed";
|
|
||||||
import useAddAccountEmbed from "./hooks/useAddAccountEmbed";
|
|
||||||
import useExportPKEmbed from "./hooks/useExportPrivateKeyEmbed";
|
|
||||||
|
|
||||||
const Stack = createStackNavigator<StackParamsList>();
|
const Stack = createStackNavigator<StackParamsList>();
|
||||||
|
|
||||||
@@ -284,8 +281,6 @@ const App = (): React.JSX.Element => {
|
|||||||
const showWalletConnect = useMemo(() => accounts.length > 0, [accounts]);
|
const showWalletConnect = useMemo(() => accounts.length > 0, [accounts]);
|
||||||
|
|
||||||
useWebViewHandler();
|
useWebViewHandler();
|
||||||
useAddAccountEmbed();
|
|
||||||
useExportPKEmbed();
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Surface style={styles.appSurface}>
|
<Surface style={styles.appSurface}>
|
||||||
@@ -395,13 +390,6 @@ const App = (): React.JSX.Element => {
|
|||||||
header: () => <></>,
|
header: () => <></>,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Stack.Screen
|
|
||||||
name="sign-request-embed"
|
|
||||||
component={SignRequestEmbed}
|
|
||||||
options={{
|
|
||||||
header: () => <Header title="Wallet" />,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</Stack.Navigator>
|
</Stack.Navigator>
|
||||||
<PairingModal
|
<PairingModal
|
||||||
visible={modalVisible}
|
visible={modalVisible}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { Account } from '../types';
|
|||||||
|
|
||||||
const AccountsContext = createContext<{
|
const AccountsContext = createContext<{
|
||||||
accounts: Account[];
|
accounts: Account[];
|
||||||
setAccounts: React.Dispatch<React.SetStateAction<Account[]>>;
|
setAccounts: (account: Account[]) => void;
|
||||||
currentIndex: number;
|
currentIndex: number;
|
||||||
setCurrentIndex: (index: number) => void;
|
setCurrentIndex: (index: number) => void;
|
||||||
}>({
|
}>({
|
||||||
|
|||||||
Vendored
+12
@@ -14,10 +14,22 @@ declare global {
|
|||||||
|
|
||||||
// Called when accounts are ready for use
|
// Called when accounts are ready for use
|
||||||
onAccountsReady?: () => void;
|
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
|
// Handles incoming signature requests from Android
|
||||||
receiveSignRequestFromAndroid?: (message: string) => void;
|
receiveSignRequestFromAndroid?: (message: string) => void;
|
||||||
|
|
||||||
|
// Handles incoming transfer requests from Android
|
||||||
|
receiveTransferRequestFromAndroid?: (to: string, amount: string) => void;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,58 +0,0 @@
|
|||||||
import { useEffect, useCallback } from 'react';
|
|
||||||
|
|
||||||
import { useNetworks } from '../context/NetworksContext';
|
|
||||||
import { sendMessage } from '../utils/misc';
|
|
||||||
import useAccountsData from '../hooks/useAccountsData';
|
|
||||||
import { addAccount } from '../utils/accounts';
|
|
||||||
import { useAccounts } from '../context/AccountsContext';
|
|
||||||
import { Account, NetworksDataState } from '../types';
|
|
||||||
|
|
||||||
const REACT_APP_ALLOWED_URLS = process.env.REACT_APP_ALLOWED_URLS;
|
|
||||||
|
|
||||||
const useAddAccountEmbed = () => {
|
|
||||||
const { networksData } = useNetworks();
|
|
||||||
const { setAccounts, setCurrentIndex } = useAccounts();
|
|
||||||
const { getAccountsData } = useAccountsData();
|
|
||||||
|
|
||||||
const addAccountHandler = useCallback(async (network: NetworksDataState) => {
|
|
||||||
const newAccount = await addAccount(network);
|
|
||||||
if (newAccount) {
|
|
||||||
setAccounts(prev => [...prev, newAccount]);
|
|
||||||
setCurrentIndex(newAccount.index);
|
|
||||||
}
|
|
||||||
}, [setAccounts, setCurrentIndex]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const handleAddAccount = async (event: MessageEvent) => {
|
|
||||||
if (event.data.type !== 'ADD_ACCOUNT') return;
|
|
||||||
|
|
||||||
if (!REACT_APP_ALLOWED_URLS) {
|
|
||||||
console.log('Unauthorized app origin:', event.origin);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const allowedUrls = REACT_APP_ALLOWED_URLS.split(',').map(url => url.trim());
|
|
||||||
|
|
||||||
if (!allowedUrls.includes(event.origin)) {
|
|
||||||
console.log('Unauthorized app.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const network = networksData.find(network => network.chainId === event.data.chainId);
|
|
||||||
|
|
||||||
await addAccountHandler(network!);
|
|
||||||
const updatedAccounts = await getAccountsData(event.data.chainId);
|
|
||||||
const addresses = updatedAccounts.map((account: Account) => account.address);
|
|
||||||
|
|
||||||
sendMessage(event.source as Window, 'ADD_ACCOUNT_RESPONSE', addresses, event.origin);
|
|
||||||
};
|
|
||||||
|
|
||||||
window.addEventListener('message', handleAddAccount);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('message', handleAddAccount);
|
|
||||||
};
|
|
||||||
}, [networksData, getAccountsData, addAccountHandler]);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default useAddAccountEmbed;
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
import { useEffect } from 'react';
|
|
||||||
|
|
||||||
import { useAccounts } from '../context/AccountsContext';
|
|
||||||
import { getPathKey, sendMessage } from '../utils/misc';
|
|
||||||
|
|
||||||
const useExportPKEmbed = () => {
|
|
||||||
const { accounts } = useAccounts();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const handleMessage = async (event: MessageEvent) => {
|
|
||||||
const { type, chainId, address } = event.data;
|
|
||||||
|
|
||||||
if (type !== 'REQUEST_ACCOUNT_PK') return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const selectedAccount = accounts.find(account => account.address === address);
|
|
||||||
if (!selectedAccount) {
|
|
||||||
throw new Error("Account not found")
|
|
||||||
}
|
|
||||||
|
|
||||||
const pathKey = await getPathKey(chainId, selectedAccount.index);
|
|
||||||
const privateKey = pathKey.privKey;
|
|
||||||
|
|
||||||
sendMessage(
|
|
||||||
event.source as Window,
|
|
||||||
'ACCOUNT_PK_DATA',
|
|
||||||
{ privateKey },
|
|
||||||
event.origin,
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching private key:', error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
window.addEventListener('message', handleMessage);
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('message', handleMessage);
|
|
||||||
};
|
|
||||||
}, [accounts]);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default useExportPKEmbed;
|
|
||||||
@@ -4,14 +4,10 @@ import { createWallet } from "../utils/accounts";
|
|||||||
import { sendMessage } from "../utils/misc";
|
import { sendMessage } from "../utils/misc";
|
||||||
import useAccountsData from "./useAccountsData";
|
import useAccountsData from "./useAccountsData";
|
||||||
import { useNetworks } from "../context/NetworksContext";
|
import { useNetworks } from "../context/NetworksContext";
|
||||||
import { useAccounts } from "../context/AccountsContext";
|
|
||||||
|
|
||||||
const REACT_APP_ALLOWED_URLS = process.env.REACT_APP_ALLOWED_URLS;
|
|
||||||
|
|
||||||
const useGetOrCreateAccounts = () => {
|
const useGetOrCreateAccounts = () => {
|
||||||
const { networksData } = useNetworks();
|
const { networksData } = useNetworks();
|
||||||
const { getAccountsData } = useAccountsData();
|
const { getAccountsData } = useAccountsData();
|
||||||
const { setAccounts } = useAccounts();
|
|
||||||
|
|
||||||
// Wrap the function in useCallback to prevent recreation on each render
|
// Wrap the function in useCallback to prevent recreation on each render
|
||||||
const getOrCreateAccountsForChain = useCallback(async (chainId: string) => {
|
const getOrCreateAccountsForChain = useCallback(async (chainId: string) => {
|
||||||
@@ -23,28 +19,13 @@ const useGetOrCreateAccounts = () => {
|
|||||||
accountsData = await getAccountsData(chainId);
|
accountsData = await getAccountsData(chainId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update the AccountsContext with the new accounts
|
|
||||||
setAccounts(accountsData);
|
|
||||||
|
|
||||||
return accountsData;
|
return accountsData;
|
||||||
}, [networksData, getAccountsData, setAccounts]);
|
}, [networksData, getAccountsData]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleCreateAccounts = async (event: MessageEvent) => {
|
const handleCreateAccounts = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== 'REQUEST_CREATE_OR_GET_ACCOUNTS') return;
|
if (event.data.type !== 'REQUEST_CREATE_OR_GET_ACCOUNTS') return;
|
||||||
|
|
||||||
if (!REACT_APP_ALLOWED_URLS) {
|
|
||||||
console.log('Allowed URLs are not set');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const allowedUrls = REACT_APP_ALLOWED_URLS.split(',').map(url => url.trim());
|
|
||||||
|
|
||||||
if (!allowedUrls.includes(event.origin)) {
|
|
||||||
console.log('Unauthorized app.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const accountsData = await getOrCreateAccountsForChain(event.data.chainId);
|
const accountsData = await getOrCreateAccountsForChain(event.data.chainId);
|
||||||
|
|
||||||
sendMessage(
|
sendMessage(
|
||||||
@@ -56,25 +37,27 @@ const useGetOrCreateAccounts = () => {
|
|||||||
|
|
||||||
const autoCreateAccounts = async () => {
|
const autoCreateAccounts = async () => {
|
||||||
const defaultChainId = networksData[0]?.chainId;
|
const defaultChainId = networksData[0]?.chainId;
|
||||||
|
|
||||||
if (!defaultChainId) {
|
if (!defaultChainId) {
|
||||||
console.log('useGetOrCreateAccounts: No default chainId found');
|
console.log('useGetOrCreateAccounts: No default chainId found');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const accounts = await getOrCreateAccountsForChain(defaultChainId);
|
|
||||||
|
|
||||||
// Only notify Android when we actually have accounts
|
await getOrCreateAccountsForChain(defaultChainId);
|
||||||
if (accounts.length > 0 && window.Android?.onAccountsReady) {
|
|
||||||
|
// Notify Android that accounts are ready
|
||||||
|
if (window.Android?.onAccountsReady) {
|
||||||
window.Android.onAccountsReady();
|
window.Android.onAccountsReady();
|
||||||
} else {
|
} else {
|
||||||
console.log('No accounts created or Android bridge not available');
|
console.log('useGetOrCreateAccounts: Android bridge not available');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addEventListener('message', handleCreateAccounts);
|
window.addEventListener('message', handleCreateAccounts);
|
||||||
|
|
||||||
const isAndroidWebView = !!(window.Android);
|
const isAndroidWebView = !!(window.Android);
|
||||||
|
|
||||||
|
// TODO: Call method to auto create accounts from android app
|
||||||
if (isAndroidWebView) {
|
if (isAndroidWebView) {
|
||||||
autoCreateAccounts();
|
autoCreateAccounts();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,16 +6,17 @@ import { useAccounts } from '../context/AccountsContext';
|
|||||||
import { useNetworks } from '../context/NetworksContext';
|
import { useNetworks } from '../context/NetworksContext';
|
||||||
import { StackParamsList } from '../types';
|
import { StackParamsList } from '../types';
|
||||||
import useGetOrCreateAccounts from './useGetOrCreateAccounts';
|
import useGetOrCreateAccounts from './useGetOrCreateAccounts';
|
||||||
|
import { retrieveAccountsForNetwork } from '../utils/accounts';
|
||||||
|
|
||||||
export const useWebViewHandler = () => {
|
export const useWebViewHandler = () => {
|
||||||
// Navigation and context hooks
|
// Navigation and context hooks
|
||||||
const navigation = useNavigation<NativeStackNavigationProp<StackParamsList>>();
|
const navigation = useNavigation<NativeStackNavigationProp<StackParamsList>>();
|
||||||
const { selectedNetwork } = useNetworks();
|
const { selectedNetwork } = useNetworks();
|
||||||
const { accounts, currentIndex } = useAccounts();
|
const { accounts, currentIndex } = useAccounts();
|
||||||
|
|
||||||
// Initialize accounts
|
// Initialize accounts
|
||||||
useGetOrCreateAccounts();
|
useGetOrCreateAccounts();
|
||||||
|
|
||||||
// Core navigation handler
|
// Core navigation handler
|
||||||
const navigateToSignRequest = useCallback((message: string) => {
|
const navigateToSignRequest = useCallback((message: string) => {
|
||||||
try {
|
try {
|
||||||
@@ -40,7 +41,7 @@ export const useWebViewHandler = () => {
|
|||||||
const path = `/sign/${selectedNetwork.namespace}/${selectedNetwork.chainId}/${currentAccount.address}/${encodeURIComponent(message)}`;
|
const path = `/sign/${selectedNetwork.namespace}/${selectedNetwork.chainId}/${currentAccount.address}/${encodeURIComponent(message)}`;
|
||||||
const pathRegex = /^\/sign\/(eip155|cosmos)\/(.+)\/(.+)\/(.+)$/;
|
const pathRegex = /^\/sign\/(eip155|cosmos)\/(.+)\/(.+)\/(.+)$/;
|
||||||
const match = path.match(pathRegex);
|
const match = path.match(pathRegex);
|
||||||
|
|
||||||
if (!match) {
|
if (!match) {
|
||||||
window.Android?.onSignatureError?.('Invalid signing path');
|
window.Android?.onSignatureError?.('Invalid signing path');
|
||||||
return;
|
return;
|
||||||
@@ -70,12 +71,106 @@ export const useWebViewHandler = () => {
|
|||||||
}
|
}
|
||||||
}, [selectedNetwork, accounts, currentIndex, navigation]);
|
}, [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(() => {
|
useEffect(() => {
|
||||||
// Assign the function to the window object
|
// Assign the function to the window object
|
||||||
window.receiveSignRequestFromAndroid = navigateToSignRequest;
|
window.receiveSignRequestFromAndroid = navigateToSignRequest;
|
||||||
|
|
||||||
|
window.receiveTransferRequestFromAndroid = navigateToTransfer;
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
window.receiveSignRequestFromAndroid = undefined;
|
window.receiveSignRequestFromAndroid = undefined;
|
||||||
|
window.receiveTransferRequestFromAndroid = undefined;
|
||||||
};
|
};
|
||||||
}, [navigateToSignRequest]); // Only the function reference as dependency
|
}, [navigateToSignRequest, navigateToTransfer]); // Only the function reference as dependency
|
||||||
};
|
};
|
||||||
|
|||||||
+297
-139
@@ -46,24 +46,29 @@ export const MEMO = 'Sending signed tx from Laconic Wallet';
|
|||||||
// Reference: https://ethereum.org/en/developers/docs/gas/#what-is-gas-limit
|
// Reference: https://ethereum.org/en/developers/docs/gas/#what-is-gas-limit
|
||||||
const ETH_MINIMUM_GAS = 21000;
|
const ETH_MINIMUM_GAS = 21000;
|
||||||
|
|
||||||
type SignRequestProps = NativeStackScreenProps<
|
type ApproveTransferProps = NativeStackScreenProps<StackParamsList, 'ApproveTransfer'> & {
|
||||||
StackParamsList,
|
route: {
|
||||||
'ApproveTransfer'
|
params: {
|
||||||
>;
|
transaction: any;
|
||||||
|
requestEvent?: {
|
||||||
|
params: {
|
||||||
|
chainId: string;
|
||||||
|
request: {
|
||||||
|
method: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
requestSessionData?: any;
|
||||||
|
chainId?: string;
|
||||||
|
};
|
||||||
|
path?: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
const ApproveTransfer = ({ route }: SignRequestProps) => {
|
const ApproveTransfer = ({ route }: ApproveTransferProps) => {
|
||||||
const { networksData } = useNetworks();
|
const { networksData } = useNetworks();
|
||||||
const { web3wallet } = useWalletConnect();
|
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 [account, setAccount] = useState<Account>();
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [balance, setBalance] = useState<string>('');
|
const [balance, setBalance] = useState<string>('');
|
||||||
@@ -80,6 +85,80 @@ const ApproveTransfer = ({ route }: SignRequestProps) => {
|
|||||||
const [ethMaxPriorityFee, setEthMaxPriorityFee] =
|
const [ethMaxPriorityFee, setEthMaxPriorityFee] =
|
||||||
useState<BigNumber | null>();
|
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(() => {
|
const isSufficientFunds = useMemo(() => {
|
||||||
if (!transaction.value) {
|
if (!transaction.value) {
|
||||||
return;
|
return;
|
||||||
@@ -139,7 +218,7 @@ const ApproveTransfer = ({ route }: SignRequestProps) => {
|
|||||||
).privKey;
|
).privKey;
|
||||||
|
|
||||||
const sender = await DirectSecp256k1Wallet.fromKey(
|
const sender = await DirectSecp256k1Wallet.fromKey(
|
||||||
Buffer.from(cosmosPrivKey.split('0x')[1], 'hex'),
|
Uint8Array.from(Buffer.from(cosmosPrivKey.split('0x')[1], 'hex')),
|
||||||
requestedNetwork?.addressPrefix,
|
requestedNetwork?.addressPrefix,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -185,26 +264,6 @@ const ApproveTransfer = ({ route }: SignRequestProps) => {
|
|||||||
}
|
}
|
||||||
}, [requestedNetwork, namespace]);
|
}, [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(() => {
|
useEffect(() => {
|
||||||
// Set loading to false when gas values for requested chain are fetched
|
// 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
|
// 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
|
||||||
@@ -246,9 +305,6 @@ const ApproveTransfer = ({ route }: SignRequestProps) => {
|
|||||||
requestedNetwork,
|
requestedNetwork,
|
||||||
ethMaxFee,
|
ethMaxFee,
|
||||||
]);
|
]);
|
||||||
useEffect(() => {
|
|
||||||
retrieveData(transaction.from!);
|
|
||||||
}, [retrieveData, transaction]);
|
|
||||||
|
|
||||||
const isEIP1559 = useMemo(() => {
|
const isEIP1559 = useMemo(() => {
|
||||||
if (cosmosGasLimit) {
|
if (cosmosGasLimit) {
|
||||||
@@ -260,6 +316,101 @@ const ApproveTransfer = ({ route }: SignRequestProps) => {
|
|||||||
return false;
|
return false;
|
||||||
}, [cosmosGasLimit, ethMaxFee, ethMaxPriorityFee]);
|
}, [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 () => {
|
const acceptRequestHandler = async () => {
|
||||||
setIsTxLoading(true);
|
setIsTxLoading(true);
|
||||||
try {
|
try {
|
||||||
@@ -267,77 +418,80 @@ const ApproveTransfer = ({ route }: SignRequestProps) => {
|
|||||||
throw new Error('account not found');
|
throw new Error('account not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ethGasLimit && ethGasLimit.lt(ETH_MINIMUM_GAS)) {
|
if (requestEvent) {
|
||||||
throw new Error(`Atleast ${ETH_MINIMUM_GAS} gas limit is required`);
|
// 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)) {
|
if (ethMaxFee && ethMaxPriorityFee && ethMaxFee.lte(ethMaxPriorityFee)) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Max fee per gas (${ethMaxFee.toNumber()}) cannot be lower than or equal to max priority fee per gas (${ethMaxPriorityFee.toNumber()})`,
|
`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');
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
} catch (error) {
|
||||||
if (!(error instanceof Error)) {
|
if (!(error instanceof Error)) {
|
||||||
throw error;
|
throw error;
|
||||||
@@ -350,20 +504,26 @@ const ApproveTransfer = ({ route }: SignRequestProps) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const rejectRequestHandler = async () => {
|
const rejectRequestHandler = async () => {
|
||||||
const response = rejectWalletConnectRequest(requestEvent);
|
if (requestEvent) {
|
||||||
const { topic } = requestEvent;
|
const response = rejectWalletConnectRequest(requestEvent);
|
||||||
await web3wallet!.respondSessionRequest({
|
const { topic } = requestEvent;
|
||||||
topic,
|
await web3wallet!.respondSessionRequest({
|
||||||
response,
|
topic,
|
||||||
});
|
response,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
navigation.navigate('Home');
|
if (window.Android?.onTransferCancelled) {
|
||||||
|
window.Android.onTransferCancelled();
|
||||||
|
} else {
|
||||||
|
navigation.navigate('Home');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const getAccountBalance = async () => {
|
const getAccountBalance = async () => {
|
||||||
try {
|
try {
|
||||||
if (!account) {
|
if (!account || !requestedNetwork) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (namespace === EIP155) {
|
if (namespace === EIP155) {
|
||||||
@@ -373,20 +533,20 @@ const ApproveTransfer = ({ route }: SignRequestProps) => {
|
|||||||
const fetchedBalance = await provider.getBalance(account.address);
|
const fetchedBalance = await provider.getBalance(account.address);
|
||||||
setBalance(fetchedBalance ? fetchedBalance.toString() : '0');
|
setBalance(fetchedBalance ? fetchedBalance.toString() : '0');
|
||||||
} else {
|
} else {
|
||||||
const cosmosBalance = await cosmosStargateClient?.getBalance(
|
if (!cosmosStargateClient) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const cosmosBalance = await cosmosStargateClient.getBalance(
|
||||||
account.address,
|
account.address,
|
||||||
requestedNetwork!.nativeDenom!.toLowerCase(),
|
requestedNetwork.nativeDenom!.toLowerCase(),
|
||||||
);
|
);
|
||||||
|
setBalance(cosmosBalance?.amount || '0');
|
||||||
setBalance(cosmosBalance?.amount!);
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!(error instanceof Error)) {
|
console.error('Error fetching balance:', error);
|
||||||
throw error;
|
setBalance('0');
|
||||||
}
|
// Don't show error dialog for balance fetch failures
|
||||||
|
// Just set balance to 0 and let the transaction proceed
|
||||||
setTxError(error.message);
|
|
||||||
setIsTxErrorDialogOpen(true);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -508,16 +668,18 @@ const ApproveTransfer = ({ route }: SignRequestProps) => {
|
|||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<ScrollView contentContainerStyle={styles.appContainer}>
|
<ScrollView contentContainerStyle={styles.appContainer}>
|
||||||
<View style={styles.dappDetails}>
|
{requestSession && (
|
||||||
{requestIcon && (
|
<View style={styles.dappDetails}>
|
||||||
<Image
|
{requestIcon && (
|
||||||
style={styles.dappLogo}
|
<Image
|
||||||
source={requestIcon ? { uri: requestIcon } : undefined}
|
style={styles.dappLogo}
|
||||||
/>
|
source={requestIcon ? { uri: requestIcon } : undefined}
|
||||||
)}
|
/>
|
||||||
<Text>{requestName}</Text>
|
)}
|
||||||
<Text variant="bodyMedium">{requestURL}</Text>
|
<Text>{requestName}</Text>
|
||||||
</View>
|
<Text variant="bodyMedium">{requestURL}</Text>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
<View style={styles.dataBoxContainer}>
|
<View style={styles.dataBoxContainer}>
|
||||||
<Text style={styles.dataBoxLabel}>From</Text>
|
<Text style={styles.dataBoxLabel}>From</Text>
|
||||||
<View style={styles.dataBox}>
|
<View style={styles.dataBox}>
|
||||||
@@ -528,11 +690,7 @@ const ApproveTransfer = ({ route }: SignRequestProps) => {
|
|||||||
label={`Balance (${
|
label={`Balance (${
|
||||||
namespace === EIP155 ? 'wei' : requestedNetwork!.nativeDenom
|
namespace === EIP155 ? 'wei' : requestedNetwork!.nativeDenom
|
||||||
})`}
|
})`}
|
||||||
data={
|
data={balance || '0'}
|
||||||
balance === '' || balance === undefined
|
|
||||||
? 'Loading balance...'
|
|
||||||
: `${balance}`
|
|
||||||
}
|
|
||||||
/>
|
/>
|
||||||
{transaction && (
|
{transaction && (
|
||||||
<View style={styles.approveTransfer}>
|
<View style={styles.approveTransfer}>
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ import { sendMessage } from '../utils/misc';
|
|||||||
import useAccountsData from '../hooks/useAccountsData';
|
import useAccountsData from '../hooks/useAccountsData';
|
||||||
import useGetOrCreateAccounts from '../hooks/useGetOrCreateAccounts';
|
import useGetOrCreateAccounts from '../hooks/useGetOrCreateAccounts';
|
||||||
|
|
||||||
const REACT_APP_ALLOWED_URLS = process.env.REACT_APP_ALLOWED_URLS;
|
|
||||||
|
|
||||||
export const AutoSignIn = () => {
|
export const AutoSignIn = () => {
|
||||||
const { networksData } = useNetworks();
|
const { networksData } = useNetworks();
|
||||||
|
|
||||||
@@ -18,14 +16,7 @@ export const AutoSignIn = () => {
|
|||||||
const handleSignIn = async (event: MessageEvent) => {
|
const handleSignIn = async (event: MessageEvent) => {
|
||||||
if (event.data.type !== 'AUTO_SIGN_IN') return;
|
if (event.data.type !== 'AUTO_SIGN_IN') return;
|
||||||
|
|
||||||
if (!REACT_APP_ALLOWED_URLS) {
|
if (event.origin !== process.env.REACT_APP_DEPLOY_APP_URL) {
|
||||||
console.log('Allowed URLs are not set');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const allowedUrls = REACT_APP_ALLOWED_URLS.split(',').map(url => url.trim());
|
|
||||||
|
|
||||||
if (!allowedUrls.includes(event.origin)) {
|
|
||||||
console.log('Unauthorized app.');
|
console.log('Unauthorized app.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,189 +0,0 @@
|
|||||||
import React, { useCallback, 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';
|
|
||||||
|
|
||||||
const REACT_APP_ALLOWED_URLS = process.env.REACT_APP_ALLOWED_URLS;
|
|
||||||
|
|
||||||
type SignRequestProps = NativeStackScreenProps<StackParamsList, 'sign-request-embed'>;
|
|
||||||
|
|
||||||
const SignRequestEmbed = ({ 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 = useCallback(async () => {
|
|
||||||
if (sourceWindow && origin) {
|
|
||||||
sendMessage(
|
|
||||||
sourceWindow,
|
|
||||||
'ZENITH_SIGNED_MESSAGE',
|
|
||||||
{ error: 'User rejected the request' },
|
|
||||||
origin,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}, [sourceWindow, origin]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const handleCosmosSignMessage = async (event: MessageEvent) => {
|
|
||||||
if (event.data.type !== 'SIGN_ZENITH_MESSAGE') return;
|
|
||||||
|
|
||||||
|
|
||||||
if (!REACT_APP_ALLOWED_URLS) {
|
|
||||||
console.log('Allowed URLs are not set');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const allowedUrls = REACT_APP_ALLOWED_URLS.split(',').map(url => url.trim());
|
|
||||||
|
|
||||||
if (!allowedUrls.includes(event.origin)) {
|
|
||||||
console.log('Unauthorized app.');
|
|
||||||
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>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}, [navigation, rejectRequestHandler]);
|
|
||||||
|
|
||||||
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 SignRequestEmbed;
|
|
||||||
@@ -40,7 +40,6 @@ export type StackParamsList = {
|
|||||||
};
|
};
|
||||||
"wallet-embed": undefined;
|
"wallet-embed": undefined;
|
||||||
"auto-sign-in": undefined;
|
"auto-sign-in": undefined;
|
||||||
"sign-request-embed": undefined;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Account = {
|
export type Account = {
|
||||||
|
|||||||
+3
-15
@@ -18,18 +18,6 @@ export const DEFAULT_NETWORKS: NetworksFormData[] = [
|
|||||||
gasPrice: '0.001',
|
gasPrice: '0.001',
|
||||||
isDefault: true,
|
isDefault: true,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
chainId: 'zenith-testnet',
|
|
||||||
networkName: 'zenithd testnet',
|
|
||||||
namespace: COSMOS,
|
|
||||||
rpcUrl: 'https://zenith-node-rpc.com',
|
|
||||||
blockExplorerUrl: '',
|
|
||||||
nativeDenom: 'znt',
|
|
||||||
addressPrefix: 'zenith',
|
|
||||||
coinType: '118',
|
|
||||||
gasPrice: '0.01',
|
|
||||||
isDefault: true,
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
chainId: 'laconic_9000-1',
|
chainId: 'laconic_9000-1',
|
||||||
networkName: 'laconicd',
|
networkName: 'laconicd',
|
||||||
@@ -53,10 +41,10 @@ export const DEFAULT_NETWORKS: NetworksFormData[] = [
|
|||||||
isDefault: true,
|
isDefault: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
chainId: 'theta-testnet-001',
|
chainId: 'provider',
|
||||||
networkName: COSMOS_TESTNET_CHAINS['cosmos:theta-testnet-001'].name,
|
networkName: COSMOS_TESTNET_CHAINS['cosmos:provider'].name,
|
||||||
namespace: COSMOS,
|
namespace: COSMOS,
|
||||||
rpcUrl: COSMOS_TESTNET_CHAINS['cosmos:theta-testnet-001'].rpc,
|
rpcUrl: COSMOS_TESTNET_CHAINS['cosmos:provider'].rpc,
|
||||||
blockExplorerUrl: '',
|
blockExplorerUrl: '',
|
||||||
nativeDenom: 'uatom',
|
nativeDenom: 'uatom',
|
||||||
addressPrefix: 'cosmos',
|
addressPrefix: 'cosmos',
|
||||||
|
|||||||
@@ -19,10 +19,10 @@ export const COSMOS_TESTNET_CHAINS: Record<
|
|||||||
namespace: string;
|
namespace: string;
|
||||||
}
|
}
|
||||||
> = {
|
> = {
|
||||||
'cosmos:theta-testnet-001': {
|
'cosmos:provider': {
|
||||||
chainId: 'theta-testnet-001',
|
chainId: 'provider',
|
||||||
name: 'Cosmos Hub Testnet',
|
name: 'Cosmos Hub Testnet',
|
||||||
rpc: 'https://rpc-t.cosmos.nodestake.top',
|
rpc: 'https://rpc-rs.cosmos.nodestake.top',
|
||||||
namespace: 'cosmos',
|
namespace: 'cosmos',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ services:
|
|||||||
CERC_DEFAULT_GAS_PRICE: ${CERC_DEFAULT_GAS_PRICE:-0.025}
|
CERC_DEFAULT_GAS_PRICE: ${CERC_DEFAULT_GAS_PRICE:-0.025}
|
||||||
CERC_GAS_ADJUSTMENT: ${CERC_GAS_ADJUSTMENT:-2}
|
CERC_GAS_ADJUSTMENT: ${CERC_GAS_ADJUSTMENT:-2}
|
||||||
CERC_LACONICD_RPC_URL: ${CERC_LACONICD_RPC_URL:-https://laconicd.laconic.com}
|
CERC_LACONICD_RPC_URL: ${CERC_LACONICD_RPC_URL:-https://laconicd.laconic.com}
|
||||||
CERC_ALLOWED_URLS: ${CERC_ALLOWED_URLS}
|
CERC_DEPLOY_APP_URL: ${CERC_DEPLOY_APP_URL}
|
||||||
command: ["bash", "/scripts/run.sh"]
|
command: ["bash", "/scripts/run.sh"]
|
||||||
volumes:
|
volumes:
|
||||||
- ../config/app/run.sh:/scripts/run.sh
|
- ../config/app/run.sh:/scripts/run.sh
|
||||||
|
|||||||
@@ -10,14 +10,14 @@ echo "WALLET_CONNECT_ID: ${WALLET_CONNECT_ID}"
|
|||||||
echo "CERC_DEFAULT_GAS_PRICE: ${CERC_DEFAULT_GAS_PRICE}"
|
echo "CERC_DEFAULT_GAS_PRICE: ${CERC_DEFAULT_GAS_PRICE}"
|
||||||
echo "CERC_GAS_ADJUSTMENT: ${CERC_GAS_ADJUSTMENT}"
|
echo "CERC_GAS_ADJUSTMENT: ${CERC_GAS_ADJUSTMENT}"
|
||||||
echo "CERC_LACONICD_RPC_URL: ${CERC_LACONICD_RPC_URL}"
|
echo "CERC_LACONICD_RPC_URL: ${CERC_LACONICD_RPC_URL}"
|
||||||
echo "CERC_ALLOWED_URLS: ${CERC_ALLOWED_URLS}"
|
echo "CERC_DEPLOY_APP_URL: ${CERC_DEPLOY_APP_URL}"
|
||||||
|
|
||||||
# Build with required env
|
# Build with required env
|
||||||
REACT_APP_WALLET_CONNECT_PROJECT_ID=$WALLET_CONNECT_ID \
|
REACT_APP_WALLET_CONNECT_PROJECT_ID=$WALLET_CONNECT_ID \
|
||||||
REACT_APP_DEFAULT_GAS_PRICE=$CERC_DEFAULT_GAS_PRICE \
|
REACT_APP_DEFAULT_GAS_PRICE=$CERC_DEFAULT_GAS_PRICE \
|
||||||
REACT_APP_GAS_ADJUSTMENT=$CERC_GAS_ADJUSTMENT \
|
REACT_APP_GAS_ADJUSTMENT=$CERC_GAS_ADJUSTMENT \
|
||||||
REACT_APP_LACONICD_RPC_URL=$CERC_LACONICD_RPC_URL \
|
REACT_APP_LACONICD_RPC_URL=$CERC_LACONICD_RPC_URL \
|
||||||
REACT_APP_ALLOWED_URLS=$CERC_ALLOWED_URLS \
|
REACT_APP_DEPLOY_APP_URL=$CERC_DEPLOY_APP_URL \
|
||||||
yarn build
|
yarn build
|
||||||
|
|
||||||
# Define the directory and file path
|
# Define the directory and file path
|
||||||
|
|||||||
@@ -49,9 +49,6 @@ Instructions for running the `laconic-wallet-web` using [laconic-so](https://git
|
|||||||
# WalletConnect project ID, same should be used in the laconic-wallet
|
# WalletConnect project ID, same should be used in the laconic-wallet
|
||||||
WALLET_CONNECT_ID=
|
WALLET_CONNECT_ID=
|
||||||
|
|
||||||
# Allowed urls is a comma separated list of allowed urls
|
|
||||||
CERC_ALLOWED_URLS=
|
|
||||||
|
|
||||||
# Optional
|
# Optional
|
||||||
|
|
||||||
# WalletConnect code for hostname verification
|
# WalletConnect code for hostname verification
|
||||||
@@ -66,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)
|
# RPC endpoint of laconicd node (default: https://laconicd.laconic.com)
|
||||||
CERC_LACONICD_RPC_URL=
|
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
|
## Start the deployment
|
||||||
|
|||||||
Reference in New Issue
Block a user