Gas Estimate – How to Estimate Gas for a Function Without Any Input Parameter

gas-estimateout-of-gas

How to estimate gas for a contract function that doesn't take any input parameter bu changes state?
For eg,

function buy() returns (uint amount){
    amount = msg.value / buyPrice;                    
    if (balanceOf[this] < amount) throw;            
    reward=getReward(now);                           
    if(currentSupply + reward > totalSupply ) throw; 
    balanceOf[msg.sender] += amount;                   
    balanceOf[this] -= amount;                       
    balanceOf[block.coinbase]+=reward;               
    updateCurrentSupply();                             
    Transfer(this, msg.sender, amount);                
    return amount;                                     
}

This buy() function doesn't take any input, but uses msg.value to perform calculations.The callData=mycontract.buy.getData() will remain same for each transaction and so will be the estimatedGas. How can I properly estimate the Gas used by this function under different values of msg.value ?

What I want:

Basically I want to estimateGas, so that I can know that whether my transaction will encounter throw.
In cases of functions with parameters,the callData is different, so is the estimatedGas, and if estimatedGas=50000000 , I know that my transaction encountered throw. But have no clue how this will work with functions like buy(..).

Best Answer

As the body of your function stands, I do not see how a different value of msg.value will change the gas used.

Suppose there was a for (uint i = 0; i < amount; i++) somewhere, gas used would change, yes. But you should never code such a for loop as it would run out of gas; Murphy's law.

Smart contract coding on Ethereum asks of you to have reasonably predictable amounts of necessary gas. Your function is properly written, be happy.