3

I am running in a private ethereum network which I init with a genesis.json file that contains "gasLimit": "31415926" Now I am wondering how I can read that via web3, any suggestions? (I want to make sure the limit is set correctly).

2 Answers 2

12

Asking for the last block mined, it will return the gasLimit of the block https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgetblock

var block = web3.eth.getBlock("latest");
console.log("gasLimit: " + block.gasLimit);

Note for web3 v1.x: getBlock is an async function and you have to use await to get the expected result

var block = await web3.eth.getBlock("latest");
console.log("gasLimit: " + block.gasLimit);
3
  • 2
    The gas limit I am getting from this is absurdly high (For an individual transaction), but this is the gas limit for the whole block though, correct? If so, then to estimate the gas I should use on an individual transaction, do I just divide by the number of transactions in said block? Or is it safe to just always use the gasLimit minimum of 21000? Dec 12, 2018 at 1:28
  • 1
    This is giving me 'undefined', maybe there is an upgrade?
    – Anonymous
    Sep 27, 2021 at 6:33
  • 1
    @rsc05 You need to wait the function returns: await block.gasLimit Jan 10, 2022 at 5:47
3

Here is the exact answer:

var block = await web3js.eth.getBlock("latest");
var gasLimit = block.gasLimit/block.transactions.length;
3
  • The block gasLimit total is always about 30000000, but the number of transactions is variable in each block. Sometimes 1, sometimes 6..... the gasLimit is so different in each case if I take your division by the trx length
    – JTCon
    Apr 26, 2021 at 15:54
  • 1
    For python code, it should be gas_limit = int(latest_block.gasLimit / (1 if len(latest_block.transactions) == 0 else len(latest_block.transactions)))
    – M.Bonjour
    Sep 7, 2021 at 13:44
  • This is giving me 'undefined', maybe there is an upgrade?
    – Anonymous
    Sep 27, 2021 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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