Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b200563139 | ||
|
|
616ead7ae5 | ||
|
|
817aa95530 |
+1
-3
@@ -1,8 +1,6 @@
|
||||
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_DEPLOY_APP_URL=
|
||||
REACT_APP_AUTH_SECRET=
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
build
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "web-wallet",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.2",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@cerc-io/registry-sdk": "^0.2.5",
|
||||
|
||||
+6
-18
@@ -39,8 +39,7 @@ import { Header } from "./components/Header";
|
||||
import { WalletEmbed } from "./screens/WalletEmbed";
|
||||
import { AutoSignIn } from "./screens/AutoSignIn";
|
||||
import { checkSufficientFunds, getPathKey, sendMessage } from "./utils/misc";
|
||||
import useAccountsData from "./hooks/useAccountsData";
|
||||
import { useWebViewHandler } from "./hooks/useWebViewHandler";
|
||||
import { retrieveSingleAccount } from "./utils/accounts";
|
||||
|
||||
const Stack = createStackNavigator<StackParamsList>();
|
||||
|
||||
@@ -50,8 +49,6 @@ 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<
|
||||
@@ -230,7 +227,7 @@ const App = (): React.JSX.Element => {
|
||||
const handleCheckBalance = async (event: MessageEvent) => {
|
||||
if (event.data.type !== 'CHECK_BALANCE') return;
|
||||
|
||||
const { chainId, amount } = event.data;
|
||||
const { chainId, address, amount } = event.data;
|
||||
const network = networksData.find(net => net.chainId === chainId);
|
||||
|
||||
if (!network) {
|
||||
@@ -238,18 +235,11 @@ const App = (): React.JSX.Element => {
|
||||
throw new Error('Requested network not supported.');
|
||||
}
|
||||
|
||||
if (network.namespace !== COSMOS) {
|
||||
throw new Error('Unsupported network');
|
||||
}
|
||||
|
||||
const accounts = await getAccountsData(chainId);
|
||||
const account = accounts[0];
|
||||
|
||||
const account = await retrieveSingleAccount(network.namespace, network.chainId, address);
|
||||
if (!account) {
|
||||
throw new Error(`No accounts in network ${chainId}`);
|
||||
throw new Error('Account not found for the requested address.');
|
||||
}
|
||||
|
||||
|
||||
const cosmosPrivKey = (
|
||||
await getPathKey(`${network.namespace}:${chainId}`, account.index)
|
||||
).privKey;
|
||||
@@ -266,7 +256,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);
|
||||
};
|
||||
@@ -276,12 +266,10 @@ const App = (): React.JSX.Element => {
|
||||
return () => {
|
||||
window.removeEventListener('message', handleCheckBalance);
|
||||
};
|
||||
}, [networksData, getAccountsData]);
|
||||
}, [networksData]);
|
||||
|
||||
const showWalletConnect = useMemo(() => accounts.length > 0, [accounts]);
|
||||
|
||||
useWebViewHandler();
|
||||
|
||||
return (
|
||||
<Surface style={styles.appSurface}>
|
||||
<Stack.Navigator
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from 'react';
|
||||
|
||||
import { NetworksDataState } from '../types';
|
||||
import { retrieveNetworksData } from '../utils/accounts';
|
||||
import { retrieveNetworksData, storeNetworkData } from '../utils/accounts';
|
||||
import { DEFAULT_NETWORKS, EIP155 } from '../utils/constants';
|
||||
import { setInternetCredentials } from '../utils/key-store';
|
||||
|
||||
const NetworksContext = createContext<{
|
||||
networksData: NetworksDataState[];
|
||||
@@ -28,38 +27,28 @@ 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[]>(DEFAULT_NETWORKS_DATA);
|
||||
const [networksData, setNetworksData] = useState<NetworksDataState[]>([]);
|
||||
const [networkType, setNetworkType] = useState<string>(EIP155);
|
||||
const [selectedNetwork, setSelectedNetwork] = useState<NetworksDataState>();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
let retrievedNetworks = await retrieveNetworksData();
|
||||
|
||||
const retrievedNetworks = await retrieveNetworksData();
|
||||
if (retrievedNetworks.length === 0) {
|
||||
setInternetCredentials(
|
||||
'networks',
|
||||
'_',
|
||||
JSON.stringify(DEFAULT_NETWORKS_DATA),
|
||||
);
|
||||
|
||||
retrievedNetworks = DEFAULT_NETWORKS_DATA;
|
||||
for (const defaultNetwork of DEFAULT_NETWORKS) {
|
||||
await storeNetworkData(defaultNetwork);
|
||||
}
|
||||
}
|
||||
|
||||
setNetworksData(retrievedNetworks);
|
||||
setSelectedNetwork(retrievedNetworks[0]);
|
||||
const retrievedNewNetworks = await retrieveNetworksData();
|
||||
setNetworksData(retrievedNewNetworks);
|
||||
setSelectedNetwork(retrievedNewNetworks[0]);
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
if (networksData.length === 0) {
|
||||
fetchData();
|
||||
}
|
||||
}, [networksData]);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedNetwork(prevSelectedNetwork => {
|
||||
|
||||
Vendored
-36
@@ -1,36 +0,0 @@
|
||||
// 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;
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -1,23 +0,0 @@
|
||||
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;
|
||||
@@ -1,71 +0,0 @@
|
||||
import { useEffect, useCallback } from "react";
|
||||
|
||||
import { createWallet } from "../utils/accounts";
|
||||
import { sendMessage } from "../utils/misc";
|
||||
import useAccountsData from "./useAccountsData";
|
||||
import { useNetworks } from "../context/NetworksContext";
|
||||
|
||||
const useGetOrCreateAccounts = () => {
|
||||
const { networksData } = useNetworks();
|
||||
const { getAccountsData } = useAccountsData();
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
return accountsData;
|
||||
}, [networksData, getAccountsData]);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
await getOrCreateAccountsForChain(defaultChainId);
|
||||
|
||||
// Notify Android that accounts are ready
|
||||
if (window.Android?.onAccountsReady) {
|
||||
window.Android.onAccountsReady();
|
||||
} else {
|
||||
console.log('useGetOrCreateAccounts: Android bridge not available');
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleCreateAccounts);
|
||||
|
||||
const isAndroidWebView = !!(window.Android);
|
||||
|
||||
// TODO: Call method to auto create accounts from android app
|
||||
if (isAndroidWebView) {
|
||||
autoCreateAccounts();
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('message', handleCreateAccounts);
|
||||
};
|
||||
}, [networksData, getAccountsData, getOrCreateAccountsForChain]);
|
||||
};
|
||||
|
||||
export default useGetOrCreateAccounts;
|
||||
@@ -1,176 +0,0 @@
|
||||
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';
|
||||
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 {
|
||||
// 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]);
|
||||
|
||||
// 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
|
||||
};
|
||||
+141
-299
@@ -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}>
|
||||
|
||||
+60
-12
@@ -1,26 +1,43 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import React, { useEffect, useCallback } 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 } = useAccountsData();
|
||||
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);
|
||||
};
|
||||
|
||||
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) {
|
||||
@@ -39,8 +56,39 @@ export const AutoSignIn = () => {
|
||||
};
|
||||
}, [networksData, getAccountsData]);
|
||||
|
||||
// Custom hook for adding listener to get accounts data
|
||||
useGetOrCreateAccounts();
|
||||
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]);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -202,13 +202,7 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
||||
chainId,
|
||||
accountId: account.index,
|
||||
});
|
||||
|
||||
// Send the result back to Android and close dialog
|
||||
if (window.Android?.onSignatureComplete) {
|
||||
window.Android.onSignatureComplete(signedMessage || "");
|
||||
} else {
|
||||
alert(`Signature: ${signedMessage}`);
|
||||
}
|
||||
alert(`Signature ${signedMessage}`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -236,11 +230,7 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
||||
}
|
||||
|
||||
setIsRejecting(false);
|
||||
if (window.Android?.onSignatureCancelled) {
|
||||
window.Android.onSignatureCancelled();
|
||||
} else {
|
||||
navigation.navigate('Home');
|
||||
}
|
||||
navigation.navigate('Home');
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
+43
-13
@@ -15,7 +15,7 @@ import {
|
||||
SigningStargateClient,
|
||||
} from '@cosmjs/stargate';
|
||||
|
||||
import { retrieveSingleAccount } from '../utils/accounts';
|
||||
import { createWallet, retrieveAccounts, retrieveSingleAccount } from '../utils/accounts';
|
||||
import AccountDetails from '../components/AccountDetails';
|
||||
import styles from '../styles/stylesheet';
|
||||
import DataBox from '../components/DataBox';
|
||||
@@ -24,8 +24,6 @@ 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;
|
||||
@@ -47,7 +45,22 @@ export const WalletEmbed = () => {
|
||||
const txEventRef = useRef<MessageEvent | null>(null);
|
||||
|
||||
const { networksData } = useNetworks();
|
||||
const { getAccountsData } = useAccountsData();
|
||||
|
||||
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]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleGetAccounts = async (event: MessageEvent) => {
|
||||
@@ -60,12 +73,7 @@ export const WalletEmbed = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
sendMessage(
|
||||
event.source as Window,
|
||||
'WALLET_ACCOUNTS_DATA',
|
||||
accountsData.map(account => account.address),
|
||||
event.origin
|
||||
);
|
||||
sendMessage(event.source as Window, 'WALLET_ACCOUNTS_DATA', accountsData, event.origin);
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleGetAccounts);
|
||||
@@ -75,8 +83,29 @@ export const WalletEmbed = () => {
|
||||
};
|
||||
}, [getAccountsData]);
|
||||
|
||||
// Custom hook for adding listener to get accounts data
|
||||
useGetOrCreateAccounts();
|
||||
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]);
|
||||
|
||||
const handleTxRequested = useCallback(
|
||||
async (event: MessageEvent) => {
|
||||
@@ -139,7 +168,8 @@ export const WalletEmbed = () => {
|
||||
});
|
||||
|
||||
if (!checkSufficientFunds(amount, balance.amount)) {
|
||||
console.log("Insufficient funds detected. Throwing error.");
|
||||
console.log("Insufficient funds detected");
|
||||
sendMessage(event.source as Window, 'INSUFFICIENT_FUNDS', null, event.origin);
|
||||
throw new Error('Insufficient funds');
|
||||
}
|
||||
|
||||
|
||||
@@ -13,10 +13,8 @@ export type StackParamsList = {
|
||||
};
|
||||
SignRequest: {
|
||||
namespace: string;
|
||||
chainId?: string;
|
||||
address: string;
|
||||
message: string;
|
||||
accountInfo?: Account;
|
||||
requestEvent?: Web3WalletTypes.SessionRequest;
|
||||
requestSessionData?: SessionTypes.Struct;
|
||||
};
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
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: NetworksFormData[] = [
|
||||
export const DEFAULT_NETWORKS = [
|
||||
{
|
||||
chainId: 'laconic-testnet-2',
|
||||
networkName: 'laconicd testnet-2',
|
||||
@@ -41,10 +39,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',
|
||||
|
||||
+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.gte(amountBigNum);
|
||||
return balanceBigNum.gt(amountBigNum);
|
||||
};
|
||||
|
||||
export {
|
||||
|
||||
@@ -3,7 +3,6 @@ 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';
|
||||
@@ -25,7 +24,7 @@ const signMessage = async ({
|
||||
case EIP155:
|
||||
return await signEthMessage(message, accountId, chainId);
|
||||
case COSMOS:
|
||||
return await signCosmosMessage(message, path.path, path.address);
|
||||
return await signCosmosMessage(message, path.path);
|
||||
default:
|
||||
throw new Error('Invalid wallet type');
|
||||
}
|
||||
@@ -52,13 +51,10 @@ const signEthMessage = async (
|
||||
const signCosmosMessage = async (
|
||||
message: string,
|
||||
path: string,
|
||||
cosmosAddress: string,
|
||||
): Promise<string | undefined> => {
|
||||
try {
|
||||
const mnemonic = await getMnemonic();
|
||||
const addressPrefix = fromBech32(cosmosAddress).prefix
|
||||
|
||||
const cosmosAccount = await getCosmosAccounts(mnemonic, path, addressPrefix);
|
||||
const cosmosAccount = await getCosmosAccounts(mnemonic, path);
|
||||
const address = cosmosAccount.data.address;
|
||||
const cosmosSignature = await cosmosAccount.cosmosWallet.signAmino(
|
||||
address,
|
||||
|
||||
@@ -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',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -9,7 +9,6 @@ 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';
|
||||
@@ -20,7 +19,6 @@ 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';
|
||||
@@ -82,13 +80,7 @@ export async function approveWalletConnectRequest(
|
||||
const path = (await getPathKey(`${namespace}:${chainId}`, account.index))
|
||||
.path;
|
||||
const mnemonic = await getMnemonic();
|
||||
|
||||
let addressPrefix: string | undefined
|
||||
if (namespace === COSMOS) {
|
||||
addressPrefix = fromBech32(account.address).prefix
|
||||
}
|
||||
|
||||
const cosmosAccount = await getCosmosAccounts(mnemonic, path, addressPrefix);
|
||||
const cosmosAccount = await getCosmosAccounts(mnemonic, path);
|
||||
const address = account.address;
|
||||
|
||||
switch (request.method) {
|
||||
|
||||
@@ -10,7 +10,6 @@ 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,14 +10,12 @@ 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,10 +63,6 @@ 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