Search code examples
javascriptethereumweb3jsmetamaskether

Why does estimateGas always return null or zero?


I am having some issue with the following... it might be my code or might simply be that the transactions require no gas?

They always return null or zero.

var gas = 0;
const eth = new Eth(web3.currentProvider);
const contract = new EthContract(eth);
const myContract= contract(abi);
var me = myContract.at(contractAddress);
eth.estimateGas({
        from: eth.accounts[0], 
        to: "0x0Fe18f369c7F34208922cAEBbd5d21E131E44692", 
        amount: web3.toWei(1, "ether")}, function(d){
        var gas = web3.toBigNumber(gas).toString();
        console.log(gas);                            
        if(gas.toString() != "null"){
                   gas = d; 
                    console.log("Gas: " + d);
       }
 });

Returns zero always... or null. Is this an error with my code? Or do these transactions require no gas?


Solution

  • The Web3 API uses error first style callbacks.

    Your call should look like this:

    eth.estimateGas({
        from: eth.accounts[0], 
        to: "0x0Fe18f369c7F34208922cAEBbd5d21E131E44692", 
        value: web3.toWei(1, "ether")
      }, 
      function(e, d) {
        var gas = web3.toBigNumber(gas).toString();
        console.log(gas);
    
        if (gas.toString() != "null") {
          gas = d; 
          console.log("Gas: " + d);
        }
     });