Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
accd068901 | ||
|
|
eb165655a4 | ||
|
|
1aabebf2c0 | ||
|
|
feb86bd5f8 | ||
|
|
3eedadafc3 | ||
|
|
6ad37d0fa5 | ||
|
|
ad636e5847 | ||
|
|
b3b4cc12c4 | ||
|
|
20dee55dca | ||
|
|
2e84a41aaf | ||
|
|
23151f95e5 | ||
|
|
41acca6a42 | ||
|
|
d9011dbdb2 | ||
|
|
3a0a321c6f | ||
|
|
59176ad7cb | ||
|
|
0b4ceae6b2 | ||
|
|
cbb28a6eb3 | ||
|
|
9d2e710632 | ||
|
|
b527a9486d | ||
|
|
b94fd22c76 | ||
|
|
657c39e5ed |
+4
-1
@@ -1,5 +1,8 @@
|
|||||||
REACT_APP_WALLET_CONNECT_PROJECT_ID=
|
REACT_APP_WALLET_CONNECT_PROJECT_ID=
|
||||||
|
|
||||||
REACT_APP_DEFAULT_GAS_PRICE=0.025
|
REACT_APP_DEFAULT_GAS_PRICE=0.025
|
||||||
# Reference: https://github.com/cosmos/cosmos-sdk/issues/16020
|
# Reference: https://github.com/cosmos/cosmos-sdk/issues/16020
|
||||||
REACT_APP_GAS_ADJUSTMENT=2
|
REACT_APP_GAS_ADJUSTMENT=2
|
||||||
REACT_APP_LACONICD_RPC_URL=https://laconicd.laconic.com
|
REACT_APP_LACONICD_RPC_URL=https://laconicd-sapo.laconic.com
|
||||||
|
|
||||||
|
REACT_APP_DEPLOY_APP_URL=
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
build
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "web-wallet",
|
"name": "web-wallet",
|
||||||
"version": "0.1.2",
|
"version": "0.1.3",
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@cerc-io/registry-sdk": "^0.2.5",
|
"@cerc-io/registry-sdk": "^0.2.5",
|
||||||
|
|||||||
+77
@@ -4,6 +4,8 @@ import { TxBody, AuthInfo } from "cosmjs-types/cosmos/tx/v1beta1/tx";
|
|||||||
|
|
||||||
import { SignClientTypes } from "@walletconnect/types";
|
import { SignClientTypes } from "@walletconnect/types";
|
||||||
import { useNavigation } from "@react-navigation/native";
|
import { useNavigation } from "@react-navigation/native";
|
||||||
|
import { DirectSecp256k1Wallet } from "@cosmjs/proto-signing";
|
||||||
|
import { SigningStargateClient } from "@cosmjs/stargate";
|
||||||
import {
|
import {
|
||||||
createStackNavigator,
|
createStackNavigator,
|
||||||
StackNavigationProp,
|
StackNavigationProp,
|
||||||
@@ -34,6 +36,11 @@ import { NETWORK_METHODS } from "./utils/wallet-connect/common-data";
|
|||||||
import { COSMOS_METHODS } from "./utils/wallet-connect/COSMOSData";
|
import { COSMOS_METHODS } from "./utils/wallet-connect/COSMOSData";
|
||||||
import styles from "./styles/stylesheet";
|
import styles from "./styles/stylesheet";
|
||||||
import { Header } from "./components/Header";
|
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";
|
||||||
|
|
||||||
const Stack = createStackNavigator<StackParamsList>();
|
const Stack = createStackNavigator<StackParamsList>();
|
||||||
|
|
||||||
@@ -43,6 +50,8 @@ const App = (): React.JSX.Element => {
|
|||||||
const { web3wallet, setActiveSessions } = useWalletConnect();
|
const { web3wallet, setActiveSessions } = useWalletConnect();
|
||||||
const { accounts, setCurrentIndex } = useAccounts();
|
const { accounts, setCurrentIndex } = useAccounts();
|
||||||
const { networksData, selectedNetwork, setSelectedNetwork } = useNetworks();
|
const { networksData, selectedNetwork, setSelectedNetwork } = useNetworks();
|
||||||
|
const { getAccountsData } = useAccountsData();
|
||||||
|
|
||||||
const [modalVisible, setModalVisible] = useState(false);
|
const [modalVisible, setModalVisible] = useState(false);
|
||||||
const [toastVisible, setToastVisible] = useState(false);
|
const [toastVisible, setToastVisible] = useState(false);
|
||||||
const [currentProposal, setCurrentProposal] = useState<
|
const [currentProposal, setCurrentProposal] = useState<
|
||||||
@@ -217,8 +226,62 @@ const App = (): React.JSX.Element => {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleCheckBalance = async (event: MessageEvent) => {
|
||||||
|
if (event.data.type !== 'CHECK_BALANCE') return;
|
||||||
|
|
||||||
|
const { chainId, amount } = event.data;
|
||||||
|
const network = networksData.find(net => net.chainId === chainId);
|
||||||
|
|
||||||
|
if (!network) {
|
||||||
|
console.error('Network not found');
|
||||||
|
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];
|
||||||
|
|
||||||
|
if (!account) {
|
||||||
|
throw new Error(`No accounts in network ${chainId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const cosmosPrivKey = (
|
||||||
|
await getPathKey(`${network.namespace}:${chainId}`, account.index)
|
||||||
|
).privKey;
|
||||||
|
|
||||||
|
const sender = await DirectSecp256k1Wallet.fromKey(
|
||||||
|
Buffer.from(cosmosPrivKey.split('0x')[1], 'hex'),
|
||||||
|
network.addressPrefix
|
||||||
|
);
|
||||||
|
|
||||||
|
const client = await SigningStargateClient.connectWithSigner(network.rpcUrl!, sender);
|
||||||
|
|
||||||
|
const balance = await client.getBalance(
|
||||||
|
account.address,
|
||||||
|
network.nativeDenom!.toLowerCase()
|
||||||
|
);
|
||||||
|
|
||||||
|
const areFundsSufficient = checkSufficientFunds(amount, balance.amount);
|
||||||
|
|
||||||
|
sendMessage(event.source as Window, 'IS_SUFFICIENT', areFundsSufficient, event.origin);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('message', handleCheckBalance);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('message', handleCheckBalance);
|
||||||
|
};
|
||||||
|
}, [networksData, getAccountsData]);
|
||||||
|
|
||||||
const showWalletConnect = useMemo(() => accounts.length > 0, [accounts]);
|
const showWalletConnect = useMemo(() => accounts.length > 0, [accounts]);
|
||||||
|
|
||||||
|
useWebViewHandler();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Surface style={styles.appSurface}>
|
<Surface style={styles.appSurface}>
|
||||||
<Stack.Navigator
|
<Stack.Navigator
|
||||||
@@ -313,6 +376,20 @@ const App = (): React.JSX.Element => {
|
|||||||
header: () => <Header title="Wallet" />,
|
header: () => <Header title="Wallet" />,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
<Stack.Screen
|
||||||
|
name="wallet-embed"
|
||||||
|
component={WalletEmbed}
|
||||||
|
options={{
|
||||||
|
header: () => <></>,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Stack.Screen
|
||||||
|
name="auto-sign-in"
|
||||||
|
component={AutoSignIn}
|
||||||
|
options={{
|
||||||
|
header: () => <></>,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</Stack.Navigator>
|
</Stack.Navigator>
|
||||||
<PairingModal
|
<PairingModal
|
||||||
visible={modalVisible}
|
visible={modalVisible}
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import React, { createContext, useContext, useEffect, useState } from 'react';
|
import React, { createContext, useContext, useEffect, useState } from 'react';
|
||||||
|
|
||||||
import { NetworksDataState } from '../types';
|
import { NetworksDataState } from '../types';
|
||||||
import { retrieveNetworksData, storeNetworkData } from '../utils/accounts';
|
import { retrieveNetworksData } from '../utils/accounts';
|
||||||
import { DEFAULT_NETWORKS, EIP155 } from '../utils/constants';
|
import { DEFAULT_NETWORKS, EIP155 } from '../utils/constants';
|
||||||
|
import { setInternetCredentials } from '../utils/key-store';
|
||||||
|
|
||||||
const NetworksContext = createContext<{
|
const NetworksContext = createContext<{
|
||||||
networksData: NetworksDataState[];
|
networksData: NetworksDataState[];
|
||||||
@@ -27,28 +28,38 @@ const useNetworks = () => {
|
|||||||
return networksContext;
|
return networksContext;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const DEFAULT_NETWORKS_DATA = DEFAULT_NETWORKS.map((defaultNetwork, index) => (
|
||||||
|
{
|
||||||
|
...defaultNetwork,
|
||||||
|
networkId: index.toString()
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
const NetworksProvider = ({ children }: { children: React.ReactNode }) => {
|
const NetworksProvider = ({ children }: { children: React.ReactNode }) => {
|
||||||
const [networksData, setNetworksData] = useState<NetworksDataState[]>([]);
|
const [networksData, setNetworksData] = useState<NetworksDataState[]>(DEFAULT_NETWORKS_DATA);
|
||||||
const [networkType, setNetworkType] = useState<string>(EIP155);
|
const [networkType, setNetworkType] = useState<string>(EIP155);
|
||||||
const [selectedNetwork, setSelectedNetwork] = useState<NetworksDataState>();
|
const [selectedNetwork, setSelectedNetwork] = useState<NetworksDataState>();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
const retrievedNetworks = await retrieveNetworksData();
|
let retrievedNetworks = await retrieveNetworksData();
|
||||||
|
|
||||||
if (retrievedNetworks.length === 0) {
|
if (retrievedNetworks.length === 0) {
|
||||||
for (const defaultNetwork of DEFAULT_NETWORKS) {
|
setInternetCredentials(
|
||||||
await storeNetworkData(defaultNetwork);
|
'networks',
|
||||||
}
|
'_',
|
||||||
|
JSON.stringify(DEFAULT_NETWORKS_DATA),
|
||||||
|
);
|
||||||
|
|
||||||
|
retrievedNetworks = DEFAULT_NETWORKS_DATA;
|
||||||
}
|
}
|
||||||
const retrievedNewNetworks = await retrieveNetworksData();
|
|
||||||
setNetworksData(retrievedNewNetworks);
|
setNetworksData(retrievedNetworks);
|
||||||
setSelectedNetwork(retrievedNewNetworks[0]);
|
setSelectedNetwork(retrievedNetworks[0]);
|
||||||
};
|
};
|
||||||
|
|
||||||
if (networksData.length === 0) {
|
fetchData();
|
||||||
fetchData();
|
}, []);
|
||||||
}
|
|
||||||
}, [networksData]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setSelectedNetwork(prevSelectedNetwork => {
|
setSelectedNetwork(prevSelectedNetwork => {
|
||||||
|
|||||||
Vendored
+36
@@ -0,0 +1,36 @@
|
|||||||
|
// 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 {};
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { useCallback } from "react";
|
||||||
|
|
||||||
|
import { retrieveAccounts } from "../utils/accounts";
|
||||||
|
import { useNetworks } from "../context/NetworksContext";
|
||||||
|
|
||||||
|
const useAccountsData = () => {
|
||||||
|
const { networksData } = useNetworks();
|
||||||
|
|
||||||
|
const getAccountsData = useCallback(async (chainId: string) => {
|
||||||
|
const targetNetwork = networksData.find(network => network.chainId === chainId);
|
||||||
|
|
||||||
|
if (!targetNetwork) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const accounts = await retrieveAccounts(targetNetwork);
|
||||||
|
return accounts || [];
|
||||||
|
}, [networksData]);
|
||||||
|
|
||||||
|
return { getAccountsData };
|
||||||
|
};
|
||||||
|
|
||||||
|
export default useAccountsData;
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
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;
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
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
|
||||||
|
};
|
||||||
@@ -22,7 +22,6 @@ import {
|
|||||||
EMPTY_FIELD_ERROR,
|
EMPTY_FIELD_ERROR,
|
||||||
INVALID_URL_ERROR,
|
INVALID_URL_ERROR,
|
||||||
IS_NUMBER_REGEX,
|
IS_NUMBER_REGEX,
|
||||||
LACONIC,
|
|
||||||
} from "../utils/constants";
|
} from "../utils/constants";
|
||||||
import { getCosmosAccounts } from "../utils/accounts";
|
import { getCosmosAccounts } from "../utils/accounts";
|
||||||
import ETH_CHAINS from "../assets/ethereum-chains.json";
|
import ETH_CHAINS from "../assets/ethereum-chains.json";
|
||||||
@@ -163,7 +162,6 @@ const AddNetwork = () => {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case COSMOS:
|
case COSMOS:
|
||||||
case LACONIC:
|
|
||||||
address = (
|
address = (
|
||||||
await getCosmosAccounts(
|
await getCosmosAccounts(
|
||||||
mnemonic,
|
mnemonic,
|
||||||
|
|||||||
+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}>
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import React, { useEffect } from 'react';
|
||||||
|
|
||||||
|
import { useNetworks } from '../context/NetworksContext';
|
||||||
|
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();
|
||||||
|
|
||||||
|
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) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const signature = await signMessage({ message: event.data.message, accountId: accountsData[0].index, chainId: event.data.chainId, namespace: EIP155 })
|
||||||
|
|
||||||
|
sendMessage(event.source as Window, 'SIGN_IN_RESPONSE', { message: event.data.message, signature }, event.origin);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('message', handleSignIn);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('message', handleSignIn);
|
||||||
|
};
|
||||||
|
}, [networksData, getAccountsData]);
|
||||||
|
|
||||||
|
// Custom hook for adding listener to get accounts data
|
||||||
|
useGetOrCreateAccounts();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
};
|
||||||
@@ -202,7 +202,13 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
|||||||
chainId,
|
chainId,
|
||||||
accountId: account.index,
|
accountId: account.index,
|
||||||
});
|
});
|
||||||
alert(`Signature ${signedMessage}`);
|
|
||||||
|
// Send the result back to Android and close dialog
|
||||||
|
if (window.Android?.onSignatureComplete) {
|
||||||
|
window.Android.onSignatureComplete(signedMessage || "");
|
||||||
|
} else {
|
||||||
|
alert(`Signature: ${signedMessage}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -230,7 +236,11 @@ const SignRequest = ({ route }: SignRequestProps) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setIsRejecting(false);
|
setIsRejecting(false);
|
||||||
navigation.navigate('Home');
|
if (window.Android?.onSignatureCancelled) {
|
||||||
|
window.Android.onSignatureCancelled();
|
||||||
|
} else {
|
||||||
|
navigation.navigate('Home');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -0,0 +1,317 @@
|
|||||||
|
import React, { useEffect, useState, useCallback, useRef } from 'react';
|
||||||
|
import { ScrollView, View } from 'react-native';
|
||||||
|
import {
|
||||||
|
ActivityIndicator,
|
||||||
|
Button,
|
||||||
|
Text,
|
||||||
|
TextInput,
|
||||||
|
} from 'react-native-paper';
|
||||||
|
import { BigNumber } from 'ethers';
|
||||||
|
|
||||||
|
import { DirectSecp256k1Wallet } from '@cosmjs/proto-signing';
|
||||||
|
import {
|
||||||
|
calculateFee,
|
||||||
|
GasPrice,
|
||||||
|
SigningStargateClient,
|
||||||
|
} from '@cosmjs/stargate';
|
||||||
|
|
||||||
|
import { retrieveSingleAccount } from '../utils/accounts';
|
||||||
|
import AccountDetails from '../components/AccountDetails';
|
||||||
|
import styles from '../styles/stylesheet';
|
||||||
|
import DataBox from '../components/DataBox';
|
||||||
|
import { checkSufficientFunds, getPathKey, sendMessage } from '../utils/misc';
|
||||||
|
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;
|
||||||
|
fromAddress: string;
|
||||||
|
toAddress: string;
|
||||||
|
amount: string;
|
||||||
|
account: Account
|
||||||
|
balance: string;
|
||||||
|
requestedNetwork: NetworksDataState
|
||||||
|
};
|
||||||
|
|
||||||
|
export const WalletEmbed = () => {
|
||||||
|
const [isTxRequested, setIsTxRequested] = useState<boolean>(false);
|
||||||
|
const [transactionDetails, setTransactionDetails] = useState<TransactionDetails | null>(null);
|
||||||
|
const [fees, setFees] = useState<string>('');
|
||||||
|
const [gasLimit, setGasLimit] = useState<string>('');
|
||||||
|
const [isTxLoading, setIsTxLoading] = useState(false);
|
||||||
|
const [txError, setTxError] = useState<string | null>(null);
|
||||||
|
const txEventRef = useRef<MessageEvent | null>(null);
|
||||||
|
|
||||||
|
const { networksData } = useNetworks();
|
||||||
|
const { getAccountsData } = useAccountsData();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleGetAccounts = async (event: MessageEvent) => {
|
||||||
|
if (event.data.type !== 'REQUEST_WALLET_ACCOUNTS') return;
|
||||||
|
|
||||||
|
const accountsData = await getAccountsData(event.data.chainId);
|
||||||
|
|
||||||
|
if (accountsData.length === 0) {
|
||||||
|
sendMessage(event.source as Window, 'ERROR', 'Wallet accounts not found', event.origin);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendMessage(
|
||||||
|
event.source as Window,
|
||||||
|
'WALLET_ACCOUNTS_DATA',
|
||||||
|
accountsData.map(account => account.address),
|
||||||
|
event.origin
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('message', handleGetAccounts);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('message', handleGetAccounts);
|
||||||
|
};
|
||||||
|
}, [getAccountsData]);
|
||||||
|
|
||||||
|
// Custom hook for adding listener to get accounts data
|
||||||
|
useGetOrCreateAccounts();
|
||||||
|
|
||||||
|
const handleTxRequested = useCallback(
|
||||||
|
async (event: MessageEvent) => {
|
||||||
|
try {
|
||||||
|
if (event.data.type !== 'REQUEST_TX') return;
|
||||||
|
|
||||||
|
txEventRef.current = event;
|
||||||
|
|
||||||
|
const { chainId, fromAddress, toAddress, amount } = event.data;
|
||||||
|
const network = networksData.find(net => net.chainId === chainId);
|
||||||
|
|
||||||
|
if (!network) {
|
||||||
|
console.error('Network not found');
|
||||||
|
throw new Error('Requested network not supported.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const account = await retrieveSingleAccount(network.namespace, network.chainId, fromAddress);
|
||||||
|
if (!account) {
|
||||||
|
throw new Error('Account not found for the requested address.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const cosmosPrivKey = (
|
||||||
|
await getPathKey(`${network.namespace}:${chainId}`, account.index)
|
||||||
|
).privKey;
|
||||||
|
|
||||||
|
const sender = await DirectSecp256k1Wallet.fromKey(
|
||||||
|
Buffer.from(cosmosPrivKey.split('0x')[1], 'hex'),
|
||||||
|
network.addressPrefix
|
||||||
|
);
|
||||||
|
|
||||||
|
const client = await SigningStargateClient.connectWithSigner(network.rpcUrl!, sender);
|
||||||
|
|
||||||
|
const balance = await client.getBalance(
|
||||||
|
account.address,
|
||||||
|
network.nativeDenom!.toLowerCase()
|
||||||
|
);
|
||||||
|
|
||||||
|
const sendMsg = {
|
||||||
|
typeUrl: '/cosmos.bank.v1beta1.MsgSend',
|
||||||
|
value: {
|
||||||
|
fromAddress: fromAddress,
|
||||||
|
toAddress: toAddress,
|
||||||
|
amount: [
|
||||||
|
{
|
||||||
|
amount: String(amount),
|
||||||
|
denom: network.nativeDenom!,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
setTransactionDetails({
|
||||||
|
chainId,
|
||||||
|
fromAddress,
|
||||||
|
toAddress,
|
||||||
|
amount,
|
||||||
|
account,
|
||||||
|
balance: balance.amount,
|
||||||
|
requestedNetwork: network,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!checkSufficientFunds(amount, balance.amount)) {
|
||||||
|
console.log("Insufficient funds detected. Throwing error.");
|
||||||
|
throw new Error('Insufficient funds');
|
||||||
|
}
|
||||||
|
|
||||||
|
const gasEstimation = await client.simulate(fromAddress, [sendMsg], MEMO);
|
||||||
|
const gasLimit = String(
|
||||||
|
Math.round(gasEstimation * Number(process.env.REACT_APP_GAS_ADJUSTMENT))
|
||||||
|
);
|
||||||
|
setGasLimit(gasLimit);
|
||||||
|
|
||||||
|
const gasPrice = GasPrice.fromString(`${network.gasPrice}${network.nativeDenom}`);
|
||||||
|
const cosmosFees = calculateFee(Number(gasLimit), gasPrice);
|
||||||
|
setFees(cosmosFees.amount[0].amount);
|
||||||
|
|
||||||
|
setIsTxRequested(true);
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof Error)) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
setTxError(error.message);
|
||||||
|
}
|
||||||
|
}, [networksData]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
window.addEventListener('message', handleTxRequested);
|
||||||
|
return () => window.removeEventListener('message', handleTxRequested);
|
||||||
|
}, [handleTxRequested]);
|
||||||
|
|
||||||
|
const acceptRequestHandler = async () => {
|
||||||
|
try {
|
||||||
|
setIsTxLoading(true);
|
||||||
|
if (!transactionDetails) {
|
||||||
|
throw new Error('Tx details not set');
|
||||||
|
}
|
||||||
|
const balanceBigNum = BigNumber.from(transactionDetails.balance);
|
||||||
|
const amountBigNum = BigNumber.from(String(transactionDetails.amount));
|
||||||
|
if (amountBigNum.gte(balanceBigNum)) {
|
||||||
|
throw new Error('Insufficient funds');
|
||||||
|
}
|
||||||
|
|
||||||
|
const cosmosPrivKey = (
|
||||||
|
await getPathKey(`${transactionDetails.requestedNetwork.namespace}:${transactionDetails.chainId}`, transactionDetails.account.index)
|
||||||
|
).privKey;
|
||||||
|
|
||||||
|
const sender = await DirectSecp256k1Wallet.fromKey(
|
||||||
|
Buffer.from(cosmosPrivKey.split('0x')[1], 'hex'),
|
||||||
|
transactionDetails.requestedNetwork.addressPrefix
|
||||||
|
);
|
||||||
|
|
||||||
|
const client = await SigningStargateClient.connectWithSigner(
|
||||||
|
transactionDetails.requestedNetwork.rpcUrl!,
|
||||||
|
sender
|
||||||
|
);
|
||||||
|
|
||||||
|
const fee = calculateFee(
|
||||||
|
Number(gasLimit),
|
||||||
|
GasPrice.fromString(`${transactionDetails.requestedNetwork.gasPrice}${transactionDetails.requestedNetwork.nativeDenom}`)
|
||||||
|
);
|
||||||
|
|
||||||
|
const txResult = await client.sendTokens(
|
||||||
|
transactionDetails.fromAddress,
|
||||||
|
transactionDetails.toAddress,
|
||||||
|
[{ amount: String(transactionDetails.amount), denom: transactionDetails.requestedNetwork.nativeDenom! }],
|
||||||
|
fee
|
||||||
|
);
|
||||||
|
|
||||||
|
const event = txEventRef.current;
|
||||||
|
if (event?.source) {
|
||||||
|
sendMessage(event.source as Window, 'TRANSACTION_RESPONSE', txResult.transactionHash, event.origin);
|
||||||
|
} else {
|
||||||
|
console.error('No event source available to send message');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof Error)) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
setTxError(error.message);
|
||||||
|
} finally {
|
||||||
|
setIsTxLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const rejectRequestHandler = () => {
|
||||||
|
const event = txEventRef.current;
|
||||||
|
|
||||||
|
setIsTxRequested(false);
|
||||||
|
setTransactionDetails(null);
|
||||||
|
if (event?.source) {
|
||||||
|
sendMessage(event.source as Window, 'TRANSACTION_RESPONSE', null, event.origin);
|
||||||
|
} else {
|
||||||
|
console.error('No event source available to send message');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{isTxRequested && transactionDetails ? (
|
||||||
|
<>
|
||||||
|
<ScrollView contentContainerStyle={styles.appContainer}>
|
||||||
|
<View style={styles.dataBoxContainer}>
|
||||||
|
<Text style={styles.dataBoxLabel}>From</Text>
|
||||||
|
<View style={styles.dataBox}>
|
||||||
|
<AccountDetails account={transactionDetails.account} />
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
<DataBox
|
||||||
|
label={`Balance (${transactionDetails.requestedNetwork.nativeDenom})`}
|
||||||
|
data={
|
||||||
|
transactionDetails.balance === '' ||
|
||||||
|
transactionDetails.balance === undefined
|
||||||
|
? 'Loading balance...'
|
||||||
|
: `${transactionDetails.balance}`
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<View style={styles.approveTransfer}>
|
||||||
|
<DataBox label="To" data={transactionDetails.toAddress} />
|
||||||
|
<DataBox
|
||||||
|
label={`Amount (${transactionDetails.requestedNetwork.nativeDenom})`}
|
||||||
|
data={transactionDetails.amount}
|
||||||
|
/>
|
||||||
|
<TextInput
|
||||||
|
mode="outlined"
|
||||||
|
label="Fee"
|
||||||
|
value={fees}
|
||||||
|
onChangeText={setFees}
|
||||||
|
style={styles.transactionFeesInput}
|
||||||
|
/>
|
||||||
|
<TextInput
|
||||||
|
mode="outlined"
|
||||||
|
label="Gas Limit"
|
||||||
|
value={gasLimit}
|
||||||
|
onChangeText={value =>
|
||||||
|
/^\d+$/.test(value) ? setGasLimit(value) : null
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
|
</ScrollView>
|
||||||
|
<View style={styles.buttonContainer}>
|
||||||
|
<Button
|
||||||
|
mode="contained"
|
||||||
|
onPress={acceptRequestHandler}
|
||||||
|
loading={isTxLoading}
|
||||||
|
disabled={!transactionDetails.balance || !fees || isTxLoading}
|
||||||
|
>
|
||||||
|
{isTxLoading ? 'Processing' : 'Yes'}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
mode="contained"
|
||||||
|
onPress={rejectRequestHandler}
|
||||||
|
buttonColor="#B82B0D"
|
||||||
|
disabled={isTxLoading}
|
||||||
|
>
|
||||||
|
No
|
||||||
|
</Button>
|
||||||
|
</View>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<View style={styles.spinnerContainer}>
|
||||||
|
<View style={{ marginTop: 50 }}></View>
|
||||||
|
<ActivityIndicator size="large" color="#0000ff" />
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
<TxErrorDialog
|
||||||
|
error={txError!}
|
||||||
|
visible={!!txError}
|
||||||
|
hideDialog={() => {
|
||||||
|
setTxError(null)
|
||||||
|
if (window.parent) {
|
||||||
|
sendMessage(window.parent, 'TRANSACTION_RESPONSE', null, '*');
|
||||||
|
sendMessage(window.parent, 'closeIframe', null, '*');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -288,7 +288,7 @@ const styles = StyleSheet.create({
|
|||||||
fontSize: 18,
|
fontSize: 18,
|
||||||
fontWeight: "bold",
|
fontWeight: "bold",
|
||||||
marginBottom: 3,
|
marginBottom: 3,
|
||||||
color: "black",
|
color: "white",
|
||||||
},
|
},
|
||||||
dataBox: {
|
dataBox: {
|
||||||
borderWidth: 1,
|
borderWidth: 1,
|
||||||
|
|||||||
@@ -13,8 +13,10 @@ export type StackParamsList = {
|
|||||||
};
|
};
|
||||||
SignRequest: {
|
SignRequest: {
|
||||||
namespace: string;
|
namespace: string;
|
||||||
|
chainId?: string;
|
||||||
address: string;
|
address: string;
|
||||||
message: string;
|
message: string;
|
||||||
|
accountInfo?: Account;
|
||||||
requestEvent?: Web3WalletTypes.SessionRequest;
|
requestEvent?: Web3WalletTypes.SessionRequest;
|
||||||
requestSessionData?: SessionTypes.Struct;
|
requestSessionData?: SessionTypes.Struct;
|
||||||
};
|
};
|
||||||
@@ -36,6 +38,8 @@ export type StackParamsList = {
|
|||||||
requestEvent: Web3WalletTypes.SessionRequest;
|
requestEvent: Web3WalletTypes.SessionRequest;
|
||||||
requestSessionData: SessionTypes.Struct;
|
requestSessionData: SessionTypes.Struct;
|
||||||
};
|
};
|
||||||
|
"wallet-embed": undefined;
|
||||||
|
"auto-sign-in": undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Account = {
|
export type Account = {
|
||||||
|
|||||||
+22
-9
@@ -1,22 +1,35 @@
|
|||||||
import { COSMOS_TESTNET_CHAINS } from './wallet-connect/COSMOSData';
|
import { COSMOS_TESTNET_CHAINS } from './wallet-connect/COSMOSData';
|
||||||
import { EIP155_CHAINS } from './wallet-connect/EIP155Data';
|
import { EIP155_CHAINS } from './wallet-connect/EIP155Data';
|
||||||
|
import { NetworksFormData } from '../types';
|
||||||
|
|
||||||
export const EIP155 = 'eip155';
|
export const EIP155 = 'eip155';
|
||||||
export const COSMOS = 'cosmos';
|
export const COSMOS = 'cosmos';
|
||||||
export const LACONIC = 'laconic';
|
|
||||||
export const DEFAULT_NETWORKS = [
|
export const DEFAULT_NETWORKS: NetworksFormData[] = [
|
||||||
{
|
{
|
||||||
chainId: 'laconic_9000-1',
|
chainId: 'laconic-testnet-2',
|
||||||
networkName: 'laconicd',
|
networkName: 'laconicd testnet-2',
|
||||||
namespace: LACONIC,
|
namespace: COSMOS,
|
||||||
rpcUrl: process.env.REACT_APP_LACONICD_RPC_URL!,
|
rpcUrl: process.env.REACT_APP_LACONICD_RPC_URL!,
|
||||||
blockExplorerUrl: '',
|
blockExplorerUrl: '',
|
||||||
nativeDenom: 'alnt',
|
nativeDenom: 'alnt',
|
||||||
addressPrefix: 'laconic',
|
addressPrefix: 'laconic',
|
||||||
coinType: '118',
|
coinType: '118',
|
||||||
gasPrice: '1',
|
gasPrice: '0.001',
|
||||||
isDefault: true,
|
isDefault: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
chainId: 'laconic_9000-1',
|
||||||
|
networkName: 'laconicd',
|
||||||
|
namespace: COSMOS,
|
||||||
|
rpcUrl: "https://laconicd.laconic.com",
|
||||||
|
blockExplorerUrl: '',
|
||||||
|
nativeDenom: 'alnt',
|
||||||
|
addressPrefix: 'laconic',
|
||||||
|
coinType: '118',
|
||||||
|
gasPrice: '1',
|
||||||
|
isDefault: false,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
chainId: '1',
|
chainId: '1',
|
||||||
networkName: EIP155_CHAINS['eip155:1'].name,
|
networkName: EIP155_CHAINS['eip155:1'].name,
|
||||||
@@ -28,10 +41,10 @@ export const DEFAULT_NETWORKS = [
|
|||||||
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',
|
||||||
|
|||||||
+22
-4
@@ -1,7 +1,11 @@
|
|||||||
/* Importing this library provides react native with a secure random source.
|
/* Importing this library provides react native with a secure random source.
|
||||||
For more information, "visit https://docs.ethers.org/v5/cookbook/react-native/#cookbook-reactnative-security" */
|
For more information, "visit https://docs.ethers.org/v5/cookbook/react-native/#cookbook-reactnative-security" */
|
||||||
import 'react-native-get-random-values';
|
import 'react-native-get-random-values';
|
||||||
|
import { BigNumber } from 'ethers';
|
||||||
|
|
||||||
|
import { AccountData } from '@cosmjs/amino';
|
||||||
|
import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing';
|
||||||
|
import { stringToPath } from '@cosmjs/crypto';
|
||||||
import '@ethersproject/shims';
|
import '@ethersproject/shims';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -9,10 +13,6 @@ import {
|
|||||||
resetInternetCredentials,
|
resetInternetCredentials,
|
||||||
setInternetCredentials,
|
setInternetCredentials,
|
||||||
} from './key-store';
|
} from './key-store';
|
||||||
|
|
||||||
import { AccountData } from '@cosmjs/amino';
|
|
||||||
import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing';
|
|
||||||
import { stringToPath } from '@cosmjs/crypto';
|
|
||||||
import { EIP155 } from './constants';
|
import { EIP155 } from './constants';
|
||||||
import { NetworksDataState } from '../types';
|
import { NetworksDataState } from '../types';
|
||||||
|
|
||||||
@@ -149,10 +149,28 @@ const resetKeyServers = async (namespace: string) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const sendMessage = (
|
||||||
|
source: Window | null,
|
||||||
|
type: string,
|
||||||
|
data: any,
|
||||||
|
origin: string
|
||||||
|
): void => {
|
||||||
|
source?.postMessage({ type, data }, origin);
|
||||||
|
};
|
||||||
|
|
||||||
|
const checkSufficientFunds = (amount: string, balance: string) => {
|
||||||
|
const amountBigNum = BigNumber.from(String(amount));
|
||||||
|
const balanceBigNum = BigNumber.from(balance);
|
||||||
|
|
||||||
|
return balanceBigNum.gte(amountBigNum);
|
||||||
|
};
|
||||||
|
|
||||||
export {
|
export {
|
||||||
getMnemonic,
|
getMnemonic,
|
||||||
getPathKey,
|
getPathKey,
|
||||||
updateAccountIndices,
|
updateAccountIndices,
|
||||||
getHDPath,
|
getHDPath,
|
||||||
resetKeyServers,
|
resetKeyServers,
|
||||||
|
sendMessage,
|
||||||
|
checkSufficientFunds,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ For more information, "visit https://docs.ethers.org/v5/cookbook/react-native/#c
|
|||||||
import 'react-native-get-random-values';
|
import 'react-native-get-random-values';
|
||||||
|
|
||||||
import '@ethersproject/shims';
|
import '@ethersproject/shims';
|
||||||
|
import { fromBech32 } from '@cosmjs/encoding';
|
||||||
|
|
||||||
import { Wallet } from 'ethers';
|
import { Wallet } from 'ethers';
|
||||||
import { SignDoc } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
|
import { SignDoc } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
|
||||||
@@ -24,7 +25,7 @@ const signMessage = async ({
|
|||||||
case EIP155:
|
case EIP155:
|
||||||
return await signEthMessage(message, accountId, chainId);
|
return await signEthMessage(message, accountId, chainId);
|
||||||
case COSMOS:
|
case COSMOS:
|
||||||
return await signCosmosMessage(message, path.path);
|
return await signCosmosMessage(message, path.path, path.address);
|
||||||
default:
|
default:
|
||||||
throw new Error('Invalid wallet type');
|
throw new Error('Invalid wallet type');
|
||||||
}
|
}
|
||||||
@@ -51,10 +52,13 @@ const signEthMessage = async (
|
|||||||
const signCosmosMessage = async (
|
const signCosmosMessage = async (
|
||||||
message: string,
|
message: string,
|
||||||
path: string,
|
path: string,
|
||||||
|
cosmosAddress: string,
|
||||||
): Promise<string | undefined> => {
|
): Promise<string | undefined> => {
|
||||||
try {
|
try {
|
||||||
const mnemonic = await getMnemonic();
|
const mnemonic = await getMnemonic();
|
||||||
const cosmosAccount = await getCosmosAccounts(mnemonic, path);
|
const addressPrefix = fromBech32(cosmosAddress).prefix
|
||||||
|
|
||||||
|
const cosmosAccount = await getCosmosAccounts(mnemonic, path, addressPrefix);
|
||||||
const address = cosmosAccount.data.address;
|
const address = cosmosAccount.data.address;
|
||||||
const cosmosSignature = await cosmosAccount.cosmosWallet.signAmino(
|
const cosmosSignature = await cosmosAccount.cosmosWallet.signAmino(
|
||||||
address,
|
address,
|
||||||
|
|||||||
@@ -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',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { Account, NetworksDataState } from '../../types';
|
|||||||
import { EIP155_SIGNING_METHODS } from './EIP155Data';
|
import { EIP155_SIGNING_METHODS } from './EIP155Data';
|
||||||
import { mergeWith } from 'lodash';
|
import { mergeWith } from 'lodash';
|
||||||
import { retrieveAccounts } from '../accounts';
|
import { retrieveAccounts } from '../accounts';
|
||||||
import { COSMOS, EIP155, LACONIC } from '../constants';
|
import { COSMOS, EIP155 } from '../constants';
|
||||||
import { NETWORK_METHODS } from './common-data';
|
import { NETWORK_METHODS } from './common-data';
|
||||||
import { COSMOS_METHODS } from './COSMOSData';
|
import { COSMOS_METHODS } from './COSMOSData';
|
||||||
|
|
||||||
@@ -131,20 +131,6 @@ export const getNamespaces = async (
|
|||||||
],
|
],
|
||||||
accounts: requiredAddresses.filter(account => account.includes(COSMOS)),
|
accounts: requiredAddresses.filter(account => account.includes(COSMOS)),
|
||||||
},
|
},
|
||||||
laconic: {
|
|
||||||
chains: walletConnectChains.filter(chain => chain.includes(LACONIC)),
|
|
||||||
methods: [
|
|
||||||
...Object.values(COSMOS_METHODS),
|
|
||||||
...Object.values(NETWORK_METHODS),
|
|
||||||
...(optionalNamespaces.laconic?.methods ?? []),
|
|
||||||
...(requiredNamespaces.laconic?.methods ?? []),
|
|
||||||
],
|
|
||||||
events: [
|
|
||||||
...(optionalNamespaces.laconic?.events ?? []),
|
|
||||||
...(requiredNamespaces.laconic?.events ?? []),
|
|
||||||
],
|
|
||||||
accounts: requiredAddresses.filter(account => account.includes(LACONIC)),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return newNamespaces;
|
return newNamespaces;
|
||||||
@@ -175,12 +161,6 @@ export const getNamespaces = async (
|
|||||||
events: [],
|
events: [],
|
||||||
accounts: [],
|
accounts: [],
|
||||||
},
|
},
|
||||||
laconic: {
|
|
||||||
chains: [],
|
|
||||||
methods: [],
|
|
||||||
events: [],
|
|
||||||
accounts: [],
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
case COSMOS:
|
case COSMOS:
|
||||||
return {
|
return {
|
||||||
@@ -206,43 +186,6 @@ export const getNamespaces = async (
|
|||||||
events: [],
|
events: [],
|
||||||
accounts: [],
|
accounts: [],
|
||||||
},
|
},
|
||||||
laconic: {
|
|
||||||
chains: [],
|
|
||||||
methods: [],
|
|
||||||
events: [],
|
|
||||||
accounts: [],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
case LACONIC:
|
|
||||||
return {
|
|
||||||
laconic: {
|
|
||||||
chains: [namespaceChainId],
|
|
||||||
methods: [
|
|
||||||
...Object.values(COSMOS_METHODS),
|
|
||||||
...Object.values(NETWORK_METHODS),
|
|
||||||
...(optionalNamespaces.laconic?.methods ?? []),
|
|
||||||
...(requiredNamespaces.laconic?.methods ?? []),
|
|
||||||
],
|
|
||||||
events: [
|
|
||||||
...(optionalNamespaces.laconic?.events ?? []),
|
|
||||||
...(requiredNamespaces.laconic?.events ?? []),
|
|
||||||
],
|
|
||||||
accounts: accounts.map(laconicAccount => {
|
|
||||||
return `${namespaceChainId}:${laconicAccount.address}`;
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
eip155: {
|
|
||||||
chains: [],
|
|
||||||
methods: [],
|
|
||||||
events: [],
|
|
||||||
accounts: [],
|
|
||||||
},
|
|
||||||
cosmos: {
|
|
||||||
chains: [],
|
|
||||||
methods: [],
|
|
||||||
events: [],
|
|
||||||
accounts: [],
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
StdFee,
|
StdFee,
|
||||||
MsgSendEncodeObject
|
MsgSendEncodeObject
|
||||||
} from '@cosmjs/stargate';
|
} from '@cosmjs/stargate';
|
||||||
|
import { fromBech32 } from '@cosmjs/encoding';
|
||||||
import { EncodeObject } from '@cosmjs/proto-signing';
|
import { EncodeObject } from '@cosmjs/proto-signing';
|
||||||
import { LaconicClient } from '@cerc-io/registry-sdk';
|
import { LaconicClient } from '@cerc-io/registry-sdk';
|
||||||
import { Buffer } from 'buffer';
|
import { Buffer } from 'buffer';
|
||||||
@@ -19,6 +20,7 @@ import { Account } from '../../types';
|
|||||||
import { getMnemonic, getPathKey } from '../misc';
|
import { getMnemonic, getPathKey } from '../misc';
|
||||||
import { getCosmosAccounts } from '../accounts';
|
import { getCosmosAccounts } from '../accounts';
|
||||||
import { COSMOS_METHODS } from './COSMOSData';
|
import { COSMOS_METHODS } from './COSMOSData';
|
||||||
|
import { COSMOS } from '../constants';
|
||||||
|
|
||||||
interface EthSendTransaction {
|
interface EthSendTransaction {
|
||||||
type: 'eth_sendTransaction';
|
type: 'eth_sendTransaction';
|
||||||
@@ -80,7 +82,13 @@ export async function approveWalletConnectRequest(
|
|||||||
const path = (await getPathKey(`${namespace}:${chainId}`, account.index))
|
const path = (await getPathKey(`${namespace}:${chainId}`, account.index))
|
||||||
.path;
|
.path;
|
||||||
const mnemonic = await getMnemonic();
|
const mnemonic = await getMnemonic();
|
||||||
const cosmosAccount = await getCosmosAccounts(mnemonic, path);
|
|
||||||
|
let addressPrefix: string | undefined
|
||||||
|
if (namespace === COSMOS) {
|
||||||
|
addressPrefix = fromBech32(account.address).prefix
|
||||||
|
}
|
||||||
|
|
||||||
|
const cosmosAccount = await getCosmosAccounts(mnemonic, path, addressPrefix);
|
||||||
const address = account.address;
|
const address = account.address;
|
||||||
|
|
||||||
switch (request.method) {
|
switch (request.method) {
|
||||||
|
|||||||
@@ -6,9 +6,11 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
CERC_SCRIPT_DEBUG: ${CERC_SCRIPT_DEBUG}
|
CERC_SCRIPT_DEBUG: ${CERC_SCRIPT_DEBUG}
|
||||||
WALLET_CONNECT_ID: ${WALLET_CONNECT_ID}
|
WALLET_CONNECT_ID: ${WALLET_CONNECT_ID}
|
||||||
|
WALLET_CONNECT_VERIFY_CODE: ${WALLET_CONNECT_VERIFY_CODE}
|
||||||
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_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,12 +10,23 @@ 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_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_DEPLOY_APP_URL=$CERC_DEPLOY_APP_URL \
|
||||||
yarn build
|
yarn build
|
||||||
|
|
||||||
|
# Define the directory and file path
|
||||||
|
FILE_PATH="/app/build/.well-known/walletconnect.txt"
|
||||||
|
|
||||||
|
# Create the directory if it doesn't exist
|
||||||
|
mkdir -p "$(dirname "$FILE_PATH")"
|
||||||
|
# Write verification code to the file
|
||||||
|
echo "$WALLET_CONNECT_VERIFY_CODE" > "$FILE_PATH"
|
||||||
|
|
||||||
|
# Serve build dir
|
||||||
http-server --proxy http://localhost:80? -p 80 /app/build
|
http-server --proxy http://localhost:80? -p 80 /app/build
|
||||||
|
|||||||
@@ -51,6 +51,9 @@ Instructions for running the `laconic-wallet-web` using [laconic-so](https://git
|
|||||||
|
|
||||||
# Optional
|
# Optional
|
||||||
|
|
||||||
|
# WalletConnect code for hostname verification
|
||||||
|
WALLET_CONNECT_VERIFY_CODE=
|
||||||
|
|
||||||
# Default gas price for txs (default: 0.025)
|
# Default gas price for txs (default: 0.025)
|
||||||
CERC_DEFAULT_GAS_PRICE=
|
CERC_DEFAULT_GAS_PRICE=
|
||||||
|
|
||||||
@@ -60,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