diff --git a/frontend/src/page/ReceivedInvoice.jsx b/frontend/src/page/ReceivedInvoice.jsx index 1bac242f..fce355f2 100644 --- a/frontend/src/page/ReceivedInvoice.jsx +++ b/frontend/src/page/ReceivedInvoice.jsx @@ -234,19 +234,25 @@ function ReceivedInvoice() { }; // UNIFORM BALANCE CHECK - const checkBalance = async (tokenAddress, amount, symbol, signer) => { + const checkBalance = async (tokenAddress, amount, symbol, signer, invoiceCount = 1) => { const userAddress = await signer.getAddress(); + + // Add a reasonable buffer for gas fees (e.g., 0.002 ETH). + // You can adjust this value depending on the typical network gas costs you expect. + const gasBuffer = ethers.parseEther("0.002"); if (tokenAddress === ethers.ZeroAddress) { const balance = await signer.provider.getBalance(userAddress); + + // Include gas buffer in the total required ETH calculation const totalRequired = - ethers.parseUnits(amount.toString(), 18) + BigInt(fee); + ethers.parseUnits(amount.toString(), 18) + (BigInt(fee) * BigInt(invoiceCount)) + gasBuffer; if (balance < totalRequired) { const requiredEth = ethers.formatEther(totalRequired); const availableEth = ethers.formatEther(balance); throw new Error( - `Insufficient ETH balance. Required: ${requiredEth} ETH, Available: ${availableEth} ETH` + `Insufficient ETH balance. Required: ~${Number(requiredEth).toFixed(4)} ETH (including gas), Available: ${Number(availableEth).toFixed(4)} ETH` ); } } else { @@ -263,11 +269,15 @@ function ReceivedInvoice() { } const ethBalance = await signer.provider.getBalance(userAddress); - if (ethBalance < BigInt(fee)) { - const requiredEthFee = ethers.formatEther(fee); + + // Add gas buffer for ERC20 payments as well (to cover approval/payment gas + network fee) + const totalEthRequired = (BigInt(fee) * BigInt(invoiceCount)) + gasBuffer; + + if (ethBalance < totalEthRequired) { + const requiredEthFee = ethers.formatEther(totalEthRequired); const availableEth = ethers.formatEther(ethBalance); throw new Error( - `Insufficient ETH for fees. Required: ${requiredEthFee} ETH, Available: ${availableEth} ETH` + `Insufficient ETH for fees and gas. Required: ~${Number(requiredEthFee).toFixed(4)} ETH, Available: ${Number(availableEth).toFixed(4)} ETH` ); } } @@ -515,7 +525,8 @@ function ReceivedInvoice() { group.tokenAddress, group.totalAmount, group.symbol, - signer + signer, + group.invoices.length ); } catch (error) { setPaymentError(error.message);