Throw error if balance is zero

This commit is contained in:
Shreerang Kale 2025-05-06 10:40:04 +05:30
parent 610939cea5
commit 9df58b9511
6 changed files with 36 additions and 31 deletions

View File

@ -390,7 +390,7 @@ const App = (): React.JSX.Element => {
}}
/>
<Stack.Screen
name="sign-tx-embed"
name="sign-tx-request-embed"
component={SignTxEmbed}
options={{
header: () => <></>,
@ -404,7 +404,7 @@ const App = (): React.JSX.Element => {
}}
/>
<Stack.Screen
name="sign-request-embed"
name="sign-message-request-embed"
component={SignRequestEmbed}
options={{
header: () => <Header title="Wallet" />,

View File

@ -19,7 +19,7 @@ import { useNetworks } from '../context/NetworksContext';
const REACT_APP_ALLOWED_URLS = process.env.REACT_APP_ALLOWED_URLS;
type SignRequestProps = NativeStackScreenProps<StackParamsList, 'sign-request-embed'>;
type SignRequestProps = NativeStackScreenProps<StackParamsList, 'sign-message-request-embed'>;
const SignRequestEmbed = ({ route }: SignRequestProps) => {
const [displayAccount, setDisplayAccount] = useState<Account>();

View File

@ -19,7 +19,7 @@ import { getMnemonic, getPathKey, sendMessage } from '../utils/misc';
import { useNetworks } from '../context/NetworksContext';
import TxErrorDialog from '../components/TxErrorDialog';
import { Account, NetworksDataState } from '../types';
import { REQUEST_SIGN_TX, REQUEST_COSMOS_ACCOUNTS_DATA, COSMOS_ACCOUNTS_RESPONSE, SIGN_TX_RESPONSE } from '../utils/constants';
import { REQUEST_SIGN_TX, REQUEST_COSMOS_ACCOUNTS, COSMOS_ACCOUNTS_RESPONSE, SIGN_TX_RESPONSE } from '../utils/constants';
// Type Definitions
interface GetAccountsRequestData {
@ -36,7 +36,7 @@ type IncomingMessageData = SignTxRequestData | GetAccountsRequestData;
interface IncomingMessageEventData {
id: string;
type: typeof REQUEST_SIGN_TX | typeof REQUEST_COSMOS_ACCOUNTS_DATA;
type: typeof REQUEST_SIGN_TX | typeof REQUEST_COSMOS_ACCOUNTS;
data: IncomingMessageData;
}
@ -60,6 +60,8 @@ interface GetAccountsResponse {
}>;
}
const REACT_APP_ALLOWED_URLS = process.env.REACT_APP_ALLOWED_URLS;
export const SignTxEmbed = () => {
const [isTxApprovalVisible, setIsTxApprovalVisible] = useState<boolean>(false);
const [transactionDetails, setTransactionDetails] = useState<TransactionDetails | null>(null);
@ -77,7 +79,6 @@ export const SignTxEmbed = () => {
const requestData = data as GetAccountsRequestData;
const mnemonic = await getMnemonic();
console.log(`Received ${REQUEST_COSMOS_ACCOUNTS_DATA}`);
try {
const requestedNetworkData = networksData.find(networkData => networkData.chainId === requestData.chainId)
@ -104,7 +105,7 @@ export const SignTxEmbed = () => {
const response: GetAccountsResponse = { accounts: responseAccounts };
sendMessage(source, COSMOS_ACCOUNTS_RESPONSE, {data: response}, origin);
} catch (error: unknown) {
console.error(`Error handling ${REQUEST_COSMOS_ACCOUNTS_DATA}:`, error);
console.error(`Error handling ${REQUEST_COSMOS_ACCOUNTS}:`, error);
const errorMsg = error instanceof Error ? error.message : String(error);
sendMessage(source, COSMOS_ACCOUNTS_RESPONSE, { error: `Failed to get accounts: ${errorMsg}` }, origin);
@ -117,7 +118,6 @@ export const SignTxEmbed = () => {
const origin = event.origin;
const requestData = data as SignTxRequestData;
console.log(`Received ${REQUEST_SIGN_TX}`);
setIsTxApprovalVisible(false);
setTransactionDetails(null);
setTxError(null);
@ -132,20 +132,18 @@ export const SignTxEmbed = () => {
if (!account) throw new Error(`Account not found for address "${signerAddress}" on chain "${signDoc.chainId}".`);
// Balance Check
let balanceAmount = 'N/A';
try {
// Use a temporary read-only client for balance
const tempWallet = await DirectSecp256k1Wallet.fromKey(
new Uint8Array(Buffer.from((await getPathKey(`${network.namespace}:${network.chainId}`, account.index)).privKey.replace(/^0x/, ''), 'hex')),
network.addressPrefix
);
// Use a temporary read-only client for balance
const tempWallet = await DirectSecp256k1Wallet.fromKey(
new Uint8Array(Buffer.from((await getPathKey(`${network.namespace}:${network.chainId}`, account.index)).privKey.replace(/^0x/, ''), 'hex')),
network.addressPrefix
);
const client = await SigningStargateClient.connectWithSigner(network.rpcUrl!, tempWallet);
const balance = await client.getBalance(account.address, network.nativeDenom!);
balanceAmount = balance.amount;
client.disconnect();
} catch (balanceError) {
console.warn("Could not retrieve balance:", balanceError);
const client = await SigningStargateClient.connectWithSigner(network.rpcUrl!, tempWallet);
const balance = await client.getBalance(account.address, network.nativeDenom!);
client.disconnect();
if (!balance || balance.amount === "0") {
throw new Error(`${account.address} does not have any balance`)
}
setTransactionDetails({
@ -155,7 +153,7 @@ export const SignTxEmbed = () => {
chainId: signDoc.chainId,
account,
requestedNetwork: network,
balance: balanceAmount,
balance: balance.amount,
signDoc,
txBody
});
@ -176,10 +174,22 @@ export const SignTxEmbed = () => {
return; // Basic validation
}
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 messageData = event.data as IncomingMessageEventData;
switch (messageData.type) {
case REQUEST_COSMOS_ACCOUNTS_DATA:
case REQUEST_COSMOS_ACCOUNTS:
handleGetCosmosAccountsRequest(event as MessageEvent<IncomingMessageEventData>);
break;
case REQUEST_SIGN_TX:
@ -192,10 +202,8 @@ export const SignTxEmbed = () => {
useEffect(() => {
window.addEventListener('message', handleIncomingMessage);
console.log("SendTxEmbed: Message listener added.");
return () => {
window.removeEventListener('message', handleIncomingMessage);
console.log("SendTxEmbed: Message listener removed.");
};
}, [handleIncomingMessage]);
@ -221,7 +229,6 @@ export const SignTxEmbed = () => {
const signResponse = await wallet.signDirect(signerAddress, signDoc);
sendMessage(source as Window, SIGN_TX_RESPONSE, {data: signResponse}, origin);
console.log("Sent signDirect response");
setIsTxApprovalVisible(false);
setTransactionDetails(null);
@ -240,7 +247,6 @@ export const SignTxEmbed = () => {
const rejectRequestHandler = () => {
if (!transactionDetails) return;
const { source, origin } = transactionDetails;
console.log("Rejecting request");
sendMessage(source as Window, SIGN_TX_RESPONSE, { error: "User rejected the signature request." }, origin);
setIsTxApprovalVisible(false);

View File

@ -140,7 +140,6 @@ export const WalletEmbed = () => {
});
if (!checkSufficientFunds(amount, balance.amount)) {
console.log("Insufficient funds detected. Throwing error.");
throw new Error('Insufficient funds');
}

View File

@ -40,8 +40,8 @@ export type StackParamsList = {
};
"wallet-embed": undefined;
"auto-sign-in": undefined;
"sign-request-embed": undefined;
"sign-tx-embed": undefined;
"sign-message-request-embed": undefined;
"sign-tx-request-embed": undefined;
};
export type Account = {

View File

@ -76,7 +76,7 @@ export const IS_NUMBER_REGEX = /^\d+$/;
export const IS_IMPORT_WALLET_ENABLED = false;
// iframe request types
export const REQUEST_COSMOS_ACCOUNTS_DATA = 'REQUEST_COSMOS_ACCOUNTS_DATA';
export const REQUEST_COSMOS_ACCOUNTS = 'REQUEST_COSMOS_ACCOUNTS';
export const REQUEST_SIGN_TX = 'REQUEST_SIGN_TX';
export const REQUEST_SIGN_MESSAGE = 'REQUEST_SIGN_MESSAGE';
export const REQUEST_WALLET_ACCOUNTS = 'REQUEST_WALLET_ACCOUNTS';