web3js, typescript – Calculate Gas Fee of Smart Contract Function Call and Convert to USD

typescriptweb3js

How Does One Estimate The Gas Fee Of Particular Smart Contract Function Call?

I Am Aware Of Using web3.eth.estimateGas

How Can One Take This Estimated Gas Result and Depending on Network Connected For Example "Binance Smart Chain" Calculate The Total Cost In USD This Transaction Gas Fees Would Cost?

Any Feedback Would Be Appreciated

Thank You

Best Answer

I Have Solved It, The First Thing I did was understand

What is Gas? If you are unclear on what gas is, I recommend reading the answers to the StackOverflow question "what is gas?".

Calculating the Transaction Fee The total cost of a transaction is the product of the gas limit and gas price:

(gas limit x gas price) = transaction fee

with this understanding I then Added The Following Package To My Project which is React and Typescript

"coingecko-api": "^1.0.10",

And Used it like this in my Estimated Gas Function

  const CoinGecko = require ('coingecko-api');
  const coinGeckoClient = new CoinGecko();
  const responseBNB = await coinGeckoClient.coins.fetch('binancecoin',{});
  let currentPriceBNB = 
  parseFloat(responseBNB.data.market_data.current_price.usd);

This Would Give Me The Current Price Of BNB

The Next Step Would Be To Get The Gas Price Of My Smart Contract Call Which I Did Using The Below

I Created My Contract Using web3

  var mySmartContract = await new web3.eth.Contract(abiManager.ADD_ABI_HERE as 
  any,window.CONTRACT_ADDRESS);

Once I Have My Contract I Then Use The Below Function to get Estimated Gas

  const resGasMethod = await mySmartContract.methods.myMethod()
            .estimateGas({ from: ownerAddress });

The Next Step is to get the Gas Limit For the Latest Block Which I Achieved Using The Below

  const latestBlock : any = await web3.eth.getBlock('latest');
  const blockGas = latestBlock.gasLimit;

Now That I Have The Gas Limit I Can Get The Total Cost Of Transaction by doing The Following

  const finalGas = (blockGas * resGasMethod);

This Will Return 'GWEI' So The Next step would be to convert to 'Ether'

  const finalGasInEther = web3.utils.fromWei(finalGas.toString(), 'ether');

And The Final Step Would Be To Get The Total Cost In USD this Ether Will Cost For the Transaction Based On The Current Price OF BNB

  const USDResult = (Number(finalGasInEther) * currentPriceBNB) * 100;

Lastly I Would Return Value And Set My State With Response So Its Visible in Frontend

I Really Hope This Can Help Someone And Would Really Appreciate Any Feedback if There Is A Improved Way To Do This

Thank You Team

Related Topic