2

I replace my MetaMask's web3 with web3.js 1.0.0-beta.34, and getGasPrice always returns null under every network --

window.web3 = new Web3(web3.currentProvider);
console.log('web3.version = ' + web3.version);
web3.eth.getGasPrice(gasPrice => {
    console.log('gasPrice = ' + gasPrice);
});

i.e., from mainnet to Ropsten to my private network ( ganache-cli ) log --

web3.version = 1.0.0-beta.34
gasPrice = null

Does anyone else have the same experience? What could have gone wrong?

1

It turns out the correct syntax for web3 1.0 should be --

web3.eth.getGasPrice().then(gasPrice => {
   console.log('gasPrice = ' + gasPrice);
});

which logs --

gasPrice = 20000000000
1

Another async way:

  let transaction = await any_function;
  let gasUsed = transaction.receipt.gasUsed;
  let txInfo = await web3.eth.getTransaction(transaction.tx);
  let gasPrice = txInfo.gasPrice;
  console.log(gasPrice);
  • 1
    While it's good to learn about the gasPrice for a transaction, web3.eth.getGasPrice() returns the average gas price without having to have a transaction. The difference is subtle but important as getGasPrice() is commonly used to gauge the gas price to be used for a future transaction – Jerry Ji Apr 5 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.