I read from many questions (example: How to estimate the cost to call a Smart Contract method?) that web3.eth has a method estimateGas that can provide an estimate of the gas usage of a transaction/function call.

I am trying to get an estimate for calling a function using my Java wrapper class generated by the web3j CLI.

Web3j web3 = Web3j.build(new HttpService(endpoint));
Credentials creds = Credentials.create(privateKey);
DefaultGasProvider gasProvider = new DefaultGasProvider();
MyNFT contract = MyNFT.load(contractAddress, web3, creds, gasProvider);
// I am interested in estimating how much gas the following call will use
TransactionReceipt receipt = contract.mintNFT(recipient, tokenUri).send();

How should I go about doing this in Java? Is there a Java equivalent for estimateGas?

1 Answer 1


To estimate Gas Price :

public BigInteger estimateGas() throws IOException {

    EthGasPrice gas=web3j.ethGasPrice().send();
    return gas.getGasPrice();

Following code gives total gas used by LATEST block, so that is total is divided by the number of transactions, which gives you average Gas Limit of LATEST block on the chain.

To Estimate Gas Limit:

public BigInteger getGasLimit() throws IOException {
    EthBlock.Block block=web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false).send().getBlock();
    return block.getGasLimit().divide(new BigInteger(String.valueOf(block.getTransactions().size())));

Final Total Gas:

gasPrice multiplied by Gas Limit
  • The web3js function estimateGas calculates how much gas a function call requires. You are calculating the cost, which is another thing.
    – Ismael
    Commented Nov 3, 2022 at 6:25
  • @Ismael He specifically asked "Java Equivalent", Web3JS is not a Java library. Commented Nov 3, 2022 at 11:45
  • The question asks about the java equivalent to web3.eth.estimateGas. It links to an existing answer that uses web3.eth.estimateGas to determine the cost of calling a contract function.
    – Ismael
    Commented Nov 3, 2022 at 18:17
  • @Ismael If you notice, I have also given a method of estimating the gas, which takes latest block, find the average gas used. Estimating total cost is additional. Commented Nov 4, 2022 at 9:24
  • You are calculating the cost using previous block gas limit, BLOCK_GAS_LIMIT * GAS_PRICE. It is not the same as calling web3.eth.estimateGas, which simulates the function call and it returns the exact gas limit required.
    – Ismael
    Commented Nov 4, 2022 at 14:03

Your Answer

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

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