Enhance transaction preparation by including gas fee calculation and balance check for sufficient funds

This commit is contained in:
void-57 2025-10-25 14:47:55 +05:30
parent 9c098119b6
commit 3acfb8fdd9

View File

@ -149,18 +149,33 @@ async function prepareAvalancheTransaction(
// Check sender balance // Check sender balance
const balance = await getBalanceRPC(senderAddress); const balance = await getBalanceRPC(senderAddress);
if (parseFloat(balance.avax) < parseFloat(amountInAvax)) { const balanceAvax = parseFloat(balance.avax);
const amount = parseFloat(amountInAvax);
// Get current gas price and calculate fee
const gasPrice = await getGasPrice();
const gasLimit = 21000; // Standard gas limit for a simple AVAX transfer
const gasPriceBN = ethers.BigNumber.from(gasPrice);
const gasLimitBN = ethers.BigNumber.from(gasLimit);
const gasFee = parseFloat(
ethers.utils.formatEther(gasPriceBN.mul(gasLimitBN))
);
// Check if balance is sufficient for amount + gas fee
if (balanceAvax < amount + gasFee) {
throw new Error( throw new Error(
`Insufficient balance. You have ${balance.avax} AVAX but trying to send ${amountInAvax} AVAX` `Insufficient balance for transaction. You have ${
balance.avax
} AVAX but need ${
amount + gasFee
} AVAX (amount + gas fee). Please lower the amount to proceed.`
); );
} }
// Get transaction count (nonce) // Get transaction count (nonce)
const nonce = await getTransactionCount(senderAddress); const nonce = await getTransactionCount(senderAddress);
// Get current gas price
const gasPrice = await getGasPrice();
// Return prepared transaction data // Return prepared transaction data
return { return {
senderAddress: senderAddress, senderAddress: senderAddress,
@ -168,7 +183,7 @@ async function prepareAvalancheTransaction(
amount: amountInAvax, amount: amountInAvax,
nonce: nonce, nonce: nonce,
gasPrice: gasPrice, gasPrice: gasPrice,
gasLimit: 21000, gasLimit: gasLimit,
chainId: 43114, chainId: 43114,
balance: balance.avax, balance: balance.avax,
cleanPrivateKey: privateKey, cleanPrivateKey: privateKey,