From 1b7f992dac18189347bd76c4753843ab9b79e7e3 Mon Sep 17 00:00:00 2001 From: raviycoder <135521192+raviycoder@users.noreply.github.com> Date: Tue, 23 Jul 2024 17:13:16 +0530 Subject: [PATCH] resolve error on token transaction --- scripts/bscOperator.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/scripts/bscOperator.js b/scripts/bscOperator.js index 1c39d5b..288b147 100644 --- a/scripts/bscOperator.js +++ b/scripts/bscOperator.js @@ -353,25 +353,35 @@ const sendToken = bscOperator.sendToken = async ({ token, privateKey, amount, receiver, contractAddress }) => { // Create a wallet using the private key const wallet = new ethers.Wallet(privateKey, getProvider()); + // Contract interface const tokenContract = new ethers.Contract(CONTRACT_ADDRESSES[token] || contractAddress, BEP20ABI, wallet); - // Convert the amount to the smallest unit of USDC (wei) + + // Fetch the correct number of decimals for the token const decimals = await tokenContract.decimals(); - console.log("decimals",decimals) - const amountWei = ethers.utils.parseUnits(amount.toString(), decimals); // Assuming 6 decimals for USDC + // Convert the amount to the smallest unit of the token + const amountWei = ethers.utils.parseUnits(amount.toString(), decimals); + + // Estimate gas limit for the transaction const gasLimit = await tokenContract.estimateGas.transfer(receiver, amountWei); + // Get the current gas price const gasPrice = await wallet.provider.getGasPrice(); + + // Calculate the gas cost const gasCost = gasPrice.mul(gasLimit); - const balance = await wallet.getBalance(); + console.log(`Gas cost: ${ethers.utils.formatEther(gasCost)} BNB`); + + // Check if wallet has enough balance to cover gas fees + const balance = await wallet.getBalance(); if (balance.lt(gasCost)) { throw new Error("Insufficient funds for gas fee"); } // Call the transfer function on the USDC contract - return tokenContract.transfer(receiver, amountWei, { gasLimit }); + return tokenContract.transfer(receiver, amountWei, { gasLimit, gasPrice }); } })('object' === typeof module ? module.exports : window.bscOperator = {});