From 65c9014a5d00215d7591df74ce1de005a1d96523 Mon Sep 17 00:00:00 2001 From: Adw8 Date: Mon, 11 Nov 2024 12:11:13 +0530 Subject: [PATCH] Add check for insufficient funds --- src/screens/WalletEmbed.tsx | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/src/screens/WalletEmbed.tsx b/src/screens/WalletEmbed.tsx index 894d6b0..0ca16d9 100644 --- a/src/screens/WalletEmbed.tsx +++ b/src/screens/WalletEmbed.tsx @@ -76,6 +76,13 @@ export const WalletEmbed = () => { source?.postMessage({ type, data }, origin); }; + const checkSufficientFunds = (amount: string, balance: string) => { + const amountBigNum = BigNumber.from(String(amount)); + const balanceBigNum = BigNumber.from(balance); + + return balanceBigNum.gt(amountBigNum); + }; + useEffect(() => { const handleGetAccounts = async (event: MessageEvent) => { if (event.data.type !== 'REQUEST_WALLET_ACCOUNTS') return; @@ -172,16 +179,6 @@ export const WalletEmbed = () => { }, }; - 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); - setTransactionDetails({ chainId, fromAddress, @@ -192,6 +189,21 @@ export const WalletEmbed = () => { 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)) { @@ -346,7 +358,8 @@ export const WalletEmbed = () => { hideDialog={() => { setTxError(null) if (window.parent) { - window.parent.postMessage('closeIframe', '*'); + sendMessage(window.parent, 'TRANSACTION_RESPONSE', null, '*'); + sendMessage(window.parent, 'closeIframe', null, '*'); } }} />