Solidity Development – Difference in Ways of Calling a Contract Function

contract-developmentcontract-invocationsolidityweb3js

After I get an instance of a contract, there are 3 ways to call the contract function below:

1.testInstance.testfunc({from:eth.accounts[0]})
2.testInstance.testfunc.sendTransaction({from:eth.accounts[0]})
3.testInstance.testfunc.call({from:eth.accounts[0]})

What's the difference from each other?

Best Answer

You're using web3.js:

  1. If testfunc in Solidity is labelled with constant, it will behave as a call #3. Otherwise, it will behave as a transaction #2.

  2. is an explicit transaction that will be broadcasted to the network and potentially mined into a block. The return value will always be a transaction hash. This costs ether (computed by gas used X gas price).

  3. is an explicit local invocation of testfunc that does not broadcast or publish anything on the blockchain. The return value is determined by the Solidity code of testfunc. This does not cost ether (though gas is still used).

For a detailed explanation see What is the difference between a transaction and a call?

Related Topic