Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49a20712f4 |
+1
-5
@@ -1,9 +1,5 @@
|
||||
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
|
||||
|
||||
# Example: https://example-url-1.com,https://example-url-2.com
|
||||
REACT_APP_ALLOWED_URLS=
|
||||
REACT_APP_LACONICD_RPC_URL=https://laconicd.laconic.com
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
build
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "web-wallet",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.2",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@cerc-io/registry-sdk": "^0.2.5",
|
||||
|
||||
-89
@@ -4,8 +4,6 @@ import { TxBody, AuthInfo } from "cosmjs-types/cosmos/tx/v1beta1/tx";
|
||||
|
||||
import { SignClientTypes } from "@walletconnect/types";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { DirectSecp256k1Wallet } from "@cosmjs/proto-signing";
|
||||
import { SigningStargateClient } from "@cosmjs/stargate";
|
||||
import {
|
||||
createStackNavigator,
|
||||
StackNavigationProp,
|
||||
@@ -36,14 +34,6 @@ import { NETWORK_METHODS } from "./utils/wallet-connect/common-data";
|
||||
import { COSMOS_METHODS } from "./utils/wallet-connect/COSMOSData";
|
||||
import styles from "./styles/stylesheet";
|
||||
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 SignRequestEmbed from "./screens/SignRequestEmbed";
|
||||
import useAddAccountEmbed from "./hooks/useAddAccountEmbed";
|
||||
import useExportPKEmbed from "./hooks/useExportPrivateKeyEmbed";
|
||||
|
||||
const Stack = createStackNavigator<StackParamsList>();
|
||||
|
||||
@@ -53,8 +43,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<
|
||||
@@ -229,64 +217,8 @@ 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]);
|
||||
|
||||
useWebViewHandler();
|
||||
useAddAccountEmbed();
|
||||
useExportPKEmbed();
|
||||
|
||||
return (
|
||||
<Surface style={styles.appSurface}>
|
||||
<Stack.Navigator
|
||||
@@ -381,27 +313,6 @@ const App = (): React.JSX.Element => {
|
||||
header: () => <Header title="Wallet" />,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="wallet-embed"
|
||||
component={WalletEmbed}
|
||||
options={{
|
||||
header: () => <></>,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="auto-sign-in"
|
||||
component={AutoSignIn}
|
||||
options={{
|
||||
header: () => <></>,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="sign-request-embed"
|
||||
component={SignRequestEmbed}
|
||||
options={{
|
||||
header: () => <Header title="Wallet" />,
|
||||
}}
|
||||
/>
|
||||
</Stack.Navigator>
|
||||
<PairingModal
|
||||
visible={modalVisible}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Account } from '../types';
|
||||
|
||||
const AccountsContext = createContext<{
|
||||
accounts: Account[];
|
||||
setAccounts: React.Dispatch<React.SetStateAction<Account[]>>;
|
||||
setAccounts: (account: Account[]) => void;
|
||||
currentIndex: number;
|
||||
setCurrentIndex: (index: number) => void;
|
||||
}>({
|
||||
|
||||
@@ -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
-24
@@ -1,24 +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;
|
||||
};
|
||||
|
||||
// Handles incoming signature requests from Android
|
||||
receiveSignRequestFromAndroid?: (message: 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,58 +0,0 @@
|
||||
import { useEffect, useCallback } from 'react';
|
||||
|
||||
import { useNetworks } from '../context/NetworksContext';
|
||||
import { sendMessage } from '../utils/misc';
|
||||
import useAccountsData from '../hooks/useAccountsData';
|
||||
import { addAccount } from '../utils/accounts';
|
||||
import { useAccounts } from '../context/AccountsContext';
|
||||
import { Account, NetworksDataState } from '../types';
|
||||
|
||||
const REACT_APP_ALLOWED_URLS = process.env.REACT_APP_ALLOWED_URLS;
|
||||
|
||||
const useAddAccountEmbed = () => {
|
||||
const { networksData } = useNetworks();
|
||||
const { setAccounts, setCurrentIndex } = useAccounts();
|
||||
const { getAccountsData } = useAccountsData();
|
||||
|
||||
const addAccountHandler = useCallback(async (network: NetworksDataState) => {
|
||||
const newAccount = await addAccount(network);
|
||||
if (newAccount) {
|
||||
setAccounts(prev => [...prev, newAccount]);
|
||||
setCurrentIndex(newAccount.index);
|
||||
}
|
||||
}, [setAccounts, setCurrentIndex]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleAddAccount = async (event: MessageEvent) => {
|
||||
if (event.data.type !== 'ADD_ACCOUNT') return;
|
||||
|
||||
if (!REACT_APP_ALLOWED_URLS) {
|
||||
console.log('Unauthorized app origin:', event.origin);
|
||||
return;
|
||||
}
|
||||
|
||||
const allowedUrls = REACT_APP_ALLOWED_URLS.split(',').map(url => url.trim());
|
||||
|
||||
if (!allowedUrls.includes(event.origin)) {
|
||||
console.log('Unauthorized app.');
|
||||
return;
|
||||
}
|
||||
|
||||
const network = networksData.find(network => network.chainId === event.data.chainId);
|
||||
|
||||
await addAccountHandler(network!);
|
||||
const updatedAccounts = await getAccountsData(event.data.chainId);
|
||||
const addresses = updatedAccounts.map((account: Account) => account.address);
|
||||
|
||||
sendMessage(event.source as Window, 'ADD_ACCOUNT_RESPONSE', addresses, event.origin);
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleAddAccount);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('message', handleAddAccount);
|
||||
};
|
||||
}, [networksData, getAccountsData, addAccountHandler]);
|
||||
};
|
||||
|
||||
export default useAddAccountEmbed;
|
||||
@@ -1,42 +0,0 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import { useAccounts } from '../context/AccountsContext';
|
||||
import { getPathKey, sendMessage } from '../utils/misc';
|
||||
|
||||
const useExportPKEmbed = () => {
|
||||
const { accounts } = useAccounts();
|
||||
|
||||
useEffect(() => {
|
||||
const handleMessage = async (event: MessageEvent) => {
|
||||
const { type, chainId, address } = event.data;
|
||||
|
||||
if (type !== 'REQUEST_ACCOUNT_PK') return;
|
||||
|
||||
try {
|
||||
const selectedAccount = accounts.find(account => account.address === address);
|
||||
if (!selectedAccount) {
|
||||
throw new Error("Account not found")
|
||||
}
|
||||
|
||||
const pathKey = await getPathKey(chainId, selectedAccount.index);
|
||||
const privateKey = pathKey.privKey;
|
||||
|
||||
sendMessage(
|
||||
event.source as Window,
|
||||
'ACCOUNT_PK_DATA',
|
||||
{ privateKey },
|
||||
event.origin,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error fetching private key:', error);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleMessage);
|
||||
return () => {
|
||||
window.removeEventListener('message', handleMessage);
|
||||
};
|
||||
}, [accounts]);
|
||||
};
|
||||
|
||||
export default useExportPKEmbed;
|
||||
@@ -1,90 +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";
|
||||
import { useAccounts } from "../context/AccountsContext";
|
||||
|
||||
const REACT_APP_ALLOWED_URLS = process.env.REACT_APP_ALLOWED_URLS;
|
||||
|
||||
const useGetOrCreateAccounts = () => {
|
||||
const { networksData } = useNetworks();
|
||||
const { getAccountsData } = useAccountsData();
|
||||
const { setAccounts } = useAccounts();
|
||||
|
||||
// Wrap the function in useCallback to prevent recreation on each render
|
||||
const getOrCreateAccountsForChain = useCallback(async (chainId: string) => {
|
||||
let accountsData = await getAccountsData(chainId);
|
||||
|
||||
if (accountsData.length === 0) {
|
||||
console.log("Accounts not found, creating wallet...");
|
||||
await createWallet(networksData);
|
||||
accountsData = await getAccountsData(chainId);
|
||||
}
|
||||
|
||||
// Update the AccountsContext with the new accounts
|
||||
setAccounts(accountsData);
|
||||
|
||||
return accountsData;
|
||||
}, [networksData, getAccountsData, setAccounts]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleCreateAccounts = async (event: MessageEvent) => {
|
||||
if (event.data.type !== 'REQUEST_CREATE_OR_GET_ACCOUNTS') return;
|
||||
|
||||
if (!REACT_APP_ALLOWED_URLS) {
|
||||
console.log('Allowed URLs are not set');
|
||||
return;
|
||||
}
|
||||
|
||||
const allowedUrls = REACT_APP_ALLOWED_URLS.split(',').map(url => url.trim());
|
||||
|
||||
if (!allowedUrls.includes(event.origin)) {
|
||||
console.log('Unauthorized app.');
|
||||
return;
|
||||
}
|
||||
|
||||
const accountsData = await getOrCreateAccountsForChain(event.data.chainId);
|
||||
const accountsAddressList = accountsData.map(account => account.address);
|
||||
console.log('Sending WALLET_ACCOUNTS_DATA accounts:', accountsAddressList);
|
||||
|
||||
sendMessage(
|
||||
event.source as Window, 'WALLET_ACCOUNTS_DATA',
|
||||
accountsAddressList,
|
||||
event.origin
|
||||
);
|
||||
};
|
||||
|
||||
const autoCreateAccounts = async () => {
|
||||
const defaultChainId = networksData[0]?.chainId;
|
||||
|
||||
if (!defaultChainId) {
|
||||
console.log('useGetOrCreateAccounts: No default chainId found');
|
||||
return;
|
||||
}
|
||||
const accounts = await getOrCreateAccountsForChain(defaultChainId);
|
||||
|
||||
// Only notify Android when we actually have accounts
|
||||
if (accounts.length > 0 && window.Android?.onAccountsReady) {
|
||||
window.Android.onAccountsReady();
|
||||
} else {
|
||||
console.log('No accounts created or Android bridge not available');
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleCreateAccounts);
|
||||
|
||||
const isAndroidWebView = !!(window.Android);
|
||||
|
||||
if (isAndroidWebView) {
|
||||
autoCreateAccounts();
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('message', handleCreateAccounts);
|
||||
};
|
||||
}, [networksData, getAccountsData, getOrCreateAccountsForChain]);
|
||||
};
|
||||
|
||||
export default useGetOrCreateAccounts;
|
||||
@@ -1,81 +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';
|
||||
|
||||
export const useWebViewHandler = () => {
|
||||
// Navigation and context hooks
|
||||
const navigation = useNavigation<NativeStackNavigationProp<StackParamsList>>();
|
||||
const { selectedNetwork } = useNetworks();
|
||||
const { accounts, currentIndex } = useAccounts();
|
||||
|
||||
// Initialize accounts
|
||||
useGetOrCreateAccounts();
|
||||
|
||||
// Core navigation handler
|
||||
const navigateToSignRequest = useCallback((message: string) => {
|
||||
try {
|
||||
// Validation checks
|
||||
if (!selectedNetwork?.namespace || !selectedNetwork?.chainId) {
|
||||
window.Android?.onSignatureError?.('Invalid network configuration');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!accounts?.length) {
|
||||
window.Android?.onSignatureError?.('No accounts available');
|
||||
return;
|
||||
}
|
||||
|
||||
const currentAccount = accounts[currentIndex];
|
||||
if (!currentAccount) {
|
||||
window.Android?.onSignatureError?.('Current account not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the path and validate with regex
|
||||
const path = `/sign/${selectedNetwork.namespace}/${selectedNetwork.chainId}/${currentAccount.address}/${encodeURIComponent(message)}`;
|
||||
const pathRegex = /^\/sign\/(eip155|cosmos)\/(.+)\/(.+)\/(.+)$/;
|
||||
const match = path.match(pathRegex);
|
||||
|
||||
if (!match) {
|
||||
window.Android?.onSignatureError?.('Invalid signing path');
|
||||
return;
|
||||
}
|
||||
|
||||
const [, pathNamespace, pathChainId, pathAddress, pathMessage] = match;
|
||||
|
||||
// Reset navigation stack and navigate to sign request
|
||||
navigation.reset({
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: 'SignRequest',
|
||||
path,
|
||||
params: {
|
||||
namespace: pathNamespace,
|
||||
chainId: pathChainId,
|
||||
address: pathAddress,
|
||||
message: decodeURIComponent(pathMessage),
|
||||
accountInfo: currentAccount,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
} catch (error) {
|
||||
window.Android?.onSignatureError?.(`Navigation error: ${error}`);
|
||||
}
|
||||
}, [selectedNetwork, accounts, currentIndex, navigation]);
|
||||
|
||||
useEffect(() => {
|
||||
// Assign the function to the window object
|
||||
window.receiveSignRequestFromAndroid = navigateToSignRequest;
|
||||
|
||||
return () => {
|
||||
window.receiveSignRequestFromAndroid = undefined;
|
||||
};
|
||||
}, [navigateToSignRequest]); // Only the function reference as dependency
|
||||
};
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
EMPTY_FIELD_ERROR,
|
||||
INVALID_URL_ERROR,
|
||||
IS_NUMBER_REGEX,
|
||||
LACONIC,
|
||||
} from "../utils/constants";
|
||||
import { getCosmosAccounts } from "../utils/accounts";
|
||||
import ETH_CHAINS from "../assets/ethereum-chains.json";
|
||||
@@ -162,6 +163,7 @@ const AddNetwork = () => {
|
||||
break;
|
||||
|
||||
case COSMOS:
|
||||
case LACONIC:
|
||||
address = (
|
||||
await getCosmosAccounts(
|
||||
mnemonic,
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
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';
|
||||
|
||||
const REACT_APP_ALLOWED_URLS = process.env.REACT_APP_ALLOWED_URLS;
|
||||
|
||||
export const AutoSignIn = () => {
|
||||
const { networksData } = useNetworks();
|
||||
|
||||
const { getAccountsData } = useAccountsData();
|
||||
|
||||
useEffect(() => {
|
||||
const handleSignIn = async (event: MessageEvent) => {
|
||||
if (event.data.type !== 'AUTO_SIGN_IN') return;
|
||||
|
||||
if (!REACT_APP_ALLOWED_URLS) {
|
||||
console.log('Allowed URLs are not set');
|
||||
return;
|
||||
}
|
||||
|
||||
const allowedUrls = REACT_APP_ALLOWED_URLS.split(',').map(url => url.trim());
|
||||
|
||||
if (!allowedUrls.includes(event.origin)) {
|
||||
console.log('Unauthorized app.');
|
||||
return;
|
||||
}
|
||||
|
||||
const accountsData = await 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,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(() => {
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { ScrollView, View } from 'react-native';
|
||||
import { ActivityIndicator, Button, Text, Appbar } from 'react-native-paper';
|
||||
|
||||
import { useNavigation } from '@react-navigation/native';
|
||||
import {
|
||||
NativeStackNavigationProp,
|
||||
NativeStackScreenProps,
|
||||
} from '@react-navigation/native-stack';
|
||||
import { getHeaderTitle } from '@react-navigation/elements';
|
||||
|
||||
import { Account, StackParamsList } from '../types';
|
||||
import AccountDetails from '../components/AccountDetails';
|
||||
import styles from '../styles/stylesheet';
|
||||
import { getCosmosAccounts, retrieveSingleAccount } from '../utils/accounts';
|
||||
import { getMnemonic, getPathKey, sendMessage } from '../utils/misc';
|
||||
import { COSMOS } from '../utils/constants';
|
||||
|
||||
const REACT_APP_ALLOWED_URLS = process.env.REACT_APP_ALLOWED_URLS;
|
||||
|
||||
type SignRequestProps = NativeStackScreenProps<StackParamsList, 'sign-request-embed'>;
|
||||
|
||||
const SignRequestEmbed = ({ route }: SignRequestProps) => {
|
||||
const [displayAccount, setDisplayAccount] = useState<Account>();
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [chainId, setChainId] = useState<string>('');
|
||||
const [signDoc, setSignDoc] = useState<any>(null);
|
||||
const [signerAddress, setSignerAddress] = useState<string>('');
|
||||
const [origin, setOrigin] = useState<string>('');
|
||||
const [sourceWindow, setSourceWindow] = useState<Window | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isApproving, setIsApproving] = useState(false);
|
||||
|
||||
const navigation =
|
||||
useNavigation<NativeStackNavigationProp<StackParamsList>>();
|
||||
|
||||
const signMessageHandler = async () => {
|
||||
if (!signDoc || !signerAddress || !sourceWindow) return;
|
||||
|
||||
setIsApproving(true);
|
||||
try {
|
||||
const requestAccount = await retrieveSingleAccount(COSMOS, chainId, signerAddress);
|
||||
const path = (await getPathKey(`${COSMOS}:${chainId}`, requestAccount!.index)).path;
|
||||
const mnemonic = await getMnemonic();
|
||||
const cosmosAccount = await getCosmosAccounts(mnemonic, path, 'zenith');
|
||||
|
||||
const cosmosAminoSignature = await cosmosAccount.cosmosWallet.signAmino(
|
||||
signerAddress,
|
||||
signDoc,
|
||||
);
|
||||
|
||||
const signature = cosmosAminoSignature.signature.signature;
|
||||
|
||||
sendMessage(
|
||||
sourceWindow,
|
||||
'ZENITH_SIGNED_MESSAGE',
|
||||
{ signature },
|
||||
origin,
|
||||
);
|
||||
|
||||
navigation.navigate('Home');
|
||||
} catch (err) {
|
||||
console.error('Signing failed:', err);
|
||||
sendMessage(
|
||||
sourceWindow!,
|
||||
'ZENITH_SIGNED_MESSAGE',
|
||||
{ error: err },
|
||||
origin,
|
||||
);
|
||||
} finally {
|
||||
setIsApproving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const rejectRequestHandler = useCallback(async () => {
|
||||
if (sourceWindow && origin) {
|
||||
sendMessage(
|
||||
sourceWindow,
|
||||
'ZENITH_SIGNED_MESSAGE',
|
||||
{ error: 'User rejected the request' },
|
||||
origin,
|
||||
);
|
||||
}
|
||||
}, [sourceWindow, origin]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleCosmosSignMessage = async (event: MessageEvent) => {
|
||||
if (event.data.type !== 'SIGN_ZENITH_MESSAGE') return;
|
||||
|
||||
|
||||
if (!REACT_APP_ALLOWED_URLS) {
|
||||
console.log('Allowed URLs are not set');
|
||||
return;
|
||||
}
|
||||
|
||||
const allowedUrls = REACT_APP_ALLOWED_URLS.split(',').map(url => url.trim());
|
||||
|
||||
if (!allowedUrls.includes(event.origin)) {
|
||||
console.log('Unauthorized app.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { signerAddress, signDoc } = event.data.params;
|
||||
|
||||
setSignerAddress(signerAddress);
|
||||
setSignDoc(signDoc);
|
||||
setMessage(signDoc.memo || '');
|
||||
setOrigin(event.origin);
|
||||
setSourceWindow(event.source as Window);
|
||||
setChainId(event.data.chainId);
|
||||
|
||||
const requestAccount = await retrieveSingleAccount(
|
||||
COSMOS,
|
||||
event.data.chainId,
|
||||
signerAddress,
|
||||
);
|
||||
|
||||
setDisplayAccount(requestAccount);
|
||||
setIsLoading(false);
|
||||
} catch (err) {
|
||||
console.error('Error preparing sign request:', err);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleCosmosSignMessage);
|
||||
return () => window.removeEventListener('message', handleCosmosSignMessage);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
navigation.setOptions({
|
||||
// eslint-disable-next-line react/no-unstable-nested-components
|
||||
header: ({ options, back }) => {
|
||||
const title = getHeaderTitle(options, 'Sign Message');
|
||||
|
||||
return (
|
||||
<Appbar.Header>
|
||||
{back && (
|
||||
<Appbar.BackAction
|
||||
onPress={async () => {
|
||||
await rejectRequestHandler();
|
||||
navigation.navigate('Home');
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<Appbar.Content title={title} />
|
||||
</Appbar.Header>
|
||||
);
|
||||
},
|
||||
});
|
||||
}, [navigation, rejectRequestHandler]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isLoading ? (
|
||||
<View style={styles.spinnerContainer}>
|
||||
<ActivityIndicator size="large" color="#0000ff" />
|
||||
</View>
|
||||
) : (
|
||||
<>
|
||||
<ScrollView contentContainerStyle={styles.appContainer}>
|
||||
<AccountDetails account={displayAccount} />
|
||||
<View style={styles.requestMessage}>
|
||||
<Text variant="bodyLarge">{message}</Text>
|
||||
</View>
|
||||
</ScrollView>
|
||||
<View style={styles.buttonContainer}>
|
||||
<Button
|
||||
mode="contained"
|
||||
onPress={signMessageHandler}
|
||||
loading={isApproving}
|
||||
disabled={isApproving}>
|
||||
Yes
|
||||
</Button>
|
||||
<Button
|
||||
mode="contained"
|
||||
onPress={rejectRequestHandler}
|
||||
buttonColor="#B82B0D">
|
||||
No
|
||||
</Button>
|
||||
</View>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default SignRequestEmbed;
|
||||
@@ -1,317 +0,0 @@
|
||||
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,
|
||||
fontWeight: "bold",
|
||||
marginBottom: 3,
|
||||
color: "white",
|
||||
color: "black",
|
||||
},
|
||||
dataBox: {
|
||||
borderWidth: 1,
|
||||
|
||||
@@ -13,10 +13,8 @@ export type StackParamsList = {
|
||||
};
|
||||
SignRequest: {
|
||||
namespace: string;
|
||||
chainId?: string;
|
||||
address: string;
|
||||
message: string;
|
||||
accountInfo?: Account;
|
||||
requestEvent?: Web3WalletTypes.SessionRequest;
|
||||
requestSessionData?: SessionTypes.Struct;
|
||||
};
|
||||
@@ -38,9 +36,6 @@ export type StackParamsList = {
|
||||
requestEvent: Web3WalletTypes.SessionRequest;
|
||||
requestSessionData: SessionTypes.Struct;
|
||||
};
|
||||
"wallet-embed": undefined;
|
||||
"auto-sign-in": undefined;
|
||||
"sign-request-embed": undefined;
|
||||
};
|
||||
|
||||
export type Account = {
|
||||
|
||||
+6
-31
@@ -1,46 +1,21 @@
|
||||
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 LACONIC = 'laconic';
|
||||
export const DEFAULT_NETWORKS = [
|
||||
{
|
||||
chainId: 'laconic-testnet-2',
|
||||
networkName: 'laconicd testnet-2',
|
||||
namespace: COSMOS,
|
||||
chainId: 'laconic_9000-1',
|
||||
networkName: 'laconicd',
|
||||
namespace: LACONIC,
|
||||
rpcUrl: process.env.REACT_APP_LACONICD_RPC_URL!,
|
||||
blockExplorerUrl: '',
|
||||
nativeDenom: 'alnt',
|
||||
addressPrefix: 'laconic',
|
||||
coinType: '118',
|
||||
gasPrice: '0.001',
|
||||
isDefault: true,
|
||||
},
|
||||
{
|
||||
chainId: 'zenith-testnet',
|
||||
networkName: 'zenithd testnet',
|
||||
namespace: COSMOS,
|
||||
rpcUrl: 'https://zenith-node-rpc.com',
|
||||
blockExplorerUrl: '',
|
||||
nativeDenom: 'znt',
|
||||
addressPrefix: 'zenith',
|
||||
coinType: '118',
|
||||
gasPrice: '0.01',
|
||||
isDefault: true,
|
||||
},
|
||||
{
|
||||
chainId: 'laconic_9000-1',
|
||||
networkName: 'laconicd',
|
||||
namespace: COSMOS,
|
||||
rpcUrl: "https://laconicd.laconic.com",
|
||||
blockExplorerUrl: '',
|
||||
nativeDenom: 'alnt',
|
||||
addressPrefix: 'laconic',
|
||||
coinType: '118',
|
||||
gasPrice: '1',
|
||||
isDefault: false,
|
||||
isDefault: true,
|
||||
},
|
||||
{
|
||||
chainId: '1',
|
||||
|
||||
+4
-22
@@ -1,11 +1,7 @@
|
||||
/* 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" */
|
||||
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 {
|
||||
@@ -13,6 +9,10 @@ import {
|
||||
resetInternetCredentials,
|
||||
setInternetCredentials,
|
||||
} from './key-store';
|
||||
|
||||
import { AccountData } from '@cosmjs/amino';
|
||||
import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing';
|
||||
import { stringToPath } from '@cosmjs/crypto';
|
||||
import { EIP155 } from './constants';
|
||||
import { NetworksDataState } from '../types';
|
||||
|
||||
@@ -149,28 +149,10 @@ 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 {
|
||||
getMnemonic,
|
||||
getPathKey,
|
||||
updateAccountIndices,
|
||||
getHDPath,
|
||||
resetKeyServers,
|
||||
sendMessage,
|
||||
checkSufficientFunds,
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Account, NetworksDataState } from '../../types';
|
||||
import { EIP155_SIGNING_METHODS } from './EIP155Data';
|
||||
import { mergeWith } from 'lodash';
|
||||
import { retrieveAccounts } from '../accounts';
|
||||
import { COSMOS, EIP155 } from '../constants';
|
||||
import { COSMOS, EIP155, LACONIC } from '../constants';
|
||||
import { NETWORK_METHODS } from './common-data';
|
||||
import { COSMOS_METHODS } from './COSMOSData';
|
||||
|
||||
@@ -131,6 +131,20 @@ export const getNamespaces = async (
|
||||
],
|
||||
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;
|
||||
@@ -161,6 +175,12 @@ export const getNamespaces = async (
|
||||
events: [],
|
||||
accounts: [],
|
||||
},
|
||||
laconic: {
|
||||
chains: [],
|
||||
methods: [],
|
||||
events: [],
|
||||
accounts: [],
|
||||
},
|
||||
};
|
||||
case COSMOS:
|
||||
return {
|
||||
@@ -186,6 +206,43 @@ export const getNamespaces = async (
|
||||
events: [],
|
||||
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:
|
||||
break;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -6,15 +6,12 @@ services:
|
||||
environment:
|
||||
CERC_SCRIPT_DEBUG: ${CERC_SCRIPT_DEBUG}
|
||||
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_GAS_ADJUSTMENT: ${CERC_GAS_ADJUSTMENT:-2}
|
||||
CERC_LACONICD_RPC_URL: ${CERC_LACONICD_RPC_URL:-https://laconicd.laconic.com}
|
||||
CERC_ALLOWED_URLS: ${CERC_ALLOWED_URLS}
|
||||
command: ["bash", "/scripts/run.sh"]
|
||||
volumes:
|
||||
- ../config/app/run.sh:/scripts/run.sh
|
||||
- ../config/app/serve.json:/app/serve.json
|
||||
ports:
|
||||
- "80"
|
||||
healthcheck:
|
||||
|
||||
@@ -10,23 +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_ALLOWED_URLS: ${CERC_ALLOWED_URLS}"
|
||||
|
||||
# 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_ALLOWED_URLS=$CERC_ALLOWED_URLS \
|
||||
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 with explicit config
|
||||
serve -s -l 80 -c /app/serve.json /app/build
|
||||
http-server --proxy http://localhost:80? -p 80 /app/build
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"headers": [
|
||||
{
|
||||
"source": "/index.html",
|
||||
"headers": [
|
||||
{
|
||||
"key": "Cache-Control",
|
||||
"value": "no-cache, must-revalidate"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"source": "/static/**/*.{js,css,png,jpg,jpeg,gif,svg,ico}",
|
||||
"headers": [
|
||||
{
|
||||
"key": "Cache-Control",
|
||||
"value": "public, max-age=31536000, immutable"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -33,7 +33,7 @@ RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
|
||||
RUN mkdir -p /scripts
|
||||
|
||||
# Install simple web server for now (use nginx perhaps later)
|
||||
RUN yarn global add serve
|
||||
RUN yarn global add http-server
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
|
||||
@@ -49,14 +49,8 @@ Instructions for running the `laconic-wallet-web` using [laconic-so](https://git
|
||||
# WalletConnect project ID, same should be used in the laconic-wallet
|
||||
WALLET_CONNECT_ID=
|
||||
|
||||
# Allowed urls is a comma separated list of allowed urls
|
||||
CERC_ALLOWED_URLS=
|
||||
|
||||
# Optional
|
||||
|
||||
# WalletConnect code for hostname verification
|
||||
WALLET_CONNECT_VERIFY_CODE=
|
||||
|
||||
# Default gas price for txs (default: 0.025)
|
||||
CERC_DEFAULT_GAS_PRICE=
|
||||
|
||||
|
||||
Reference in New Issue
Block a user