0

I would like to pull the latest gasUsed from a block. When I run a console.log I get the required output in the terminal. However, I am trying to use the gasUsed from the latest block and put that into a variable so I can use it elsewhere. Any thought?

dotenv.config();

const Web3 = require("web3");
const web3 = new Web3("https://rinkeby.infura.io/v3/" + process.env.INFURA_KEY);

web3.eth.getBlock("latest").then(console.log);
let gasUsedLast = web3.eth.getBlock("latest").then((blockInfo) => {
  console.log(blockInfo.gasUsed);
  return blockInfo.gasUsed;
});

console.log(gasUsedLast);
0

You can do something like this.

Const gasUsed = async()=>{
       const result = await web3.eth.getblock("latest")
       
       return result }
;(async()=>{
       const gasFees = await gasUsed()
       console.log(gasFees) }

The function would look something like this. I'm also learning solidity & ether but this is how i would do it.

0

I think Wallet has to be a var not a const - you can’t update or re-declare a const. So:

dotenv.config();

var Web3 = require("web3");
var web3 = new Web3("https://rinkeby.infura.io/v3/" + process.env.INFURA_KEY);

web3.eth.getBlock("latest").then(console.log);
let gasUsedLast = web3.eth.getBlock("latest").then((blockInfo) => {
  console.log(blockInfo.gasUsed);
  return blockInfo.gasUsed;
});

console.log(gasUsedLast);
1
  • Using var instead of const just changes the scoping rules applied. The promise behavior won't change.
    – Ismael
    Oct 8 at 17:48

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.