[Ethereum] Estimating gas cost of a transaction function with web3

gasweb3js

I am trying to use the estimateGas function in Web3 to estimate how much gas it would cost to run a function in my contract. As an example of how this would normally be used, in geth I can run a command like the following and get something back (21001):

web3.eth.estimateGas({from: eth.accounts[0], to: "0xEDA8A2E1dfA5B93692D2a9dDF833B6D7DF6D5f93", amount: web3.toWei(1, "ether")})

However, running the same command on a webpage with web3 (eg. trying the following):

console.log(web3.eth.estimateGas({from: eth.accounts[0], to: "0xEDA8A2E1dfA5B93692D2a9dDF833B6D7DF6D5f93", amount: web3.toWei(1, "ether")}))

Will result in this error:

eth is not defined

I am having trouble getting this to work in any case. For example, say in my contract I have the following function:

function SetMessage (bytes32 _message) returns (bool success) {
    message = _message;
    return true;
    }

Which may be executed in Web3 as follows:

MyContract.deployed().then(function (contractInstance) {    
      return contractInstance.SetMessage(_message, { gas: 200000, from: web3.eth.accounts[0] })
    })

What would be the exact syntax to estimate the gas of sending a transaction to this function?

Best Answer

Try the below code in a browser. Note that account selection is done with web3.eth.accounts[0] instead of eth.accounts[0].

console.log(web3.eth.estimateGas({from: web3.eth.accounts[0], to: "0xEDA8A2E1dfA5B93692D2a9dDF833B6D7DF6D5f93", amount: web3.toWei(1, "ether")}))