Solidity Functions – How to Get Return Value of a Contract Function

go-ethereumsolidity

I want to get the return value of a function for solidity contract. I deployed is using solidity browser in testnet. I am using nodejs client and it uses geth for web3 provider.Here are the details

contract ( from solidity example)

contract ShapeCalculator{
    function rectangle(uint w, uint h) returns (uint s, uint p) {
        s = w * h;
        p = 2 * (w + h);
    }
} 

client code ::

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); 
web3.eth.defaultAccount=web3.eth.accounts[0];
var abi = '[{"constant":false,"inputs":[{"name":"w","type":"uint256"},{"name":"h","type":"uint256"}],"name":"rectangle","outputs":[{"name":"s","type":"uint256"},{"name":"p","type":"uint256"}],"payable":false,"type":"function"}]';
var address = "address which I received after deployment";
var shapeCalculatorContract = web3.eth.contract( JSON.parse(abi)).at(address);
var holdReturnValue = shapeCalculatorContract.rectangle(10,20);
console.log(holdReturnValue);

At console I am getting "0x83ddb750b799c62f73013c34f89295e3ff2af5cc98755a51e41e00a13c389735", I was expecting the area and perimeter. Appreciate any help.

Best Answer

If you invoke a contract function by its name as you have done there you generate a transaction, and you won't be able to see the returned value outside of the contract (what you get is the transaction receipt). If your function needs to modify the state on the blockchain, then transactions are the right way to go, and to gain access to return values you should look into using Events. If, like in this case, you are not changing any value on the blockchain with your function, you can use a function call instead, and retrieve the returned values directly in your javascript code. In your case that would be (using promises for example)

shapeCalculatorContract.rectangle.call(10,20).then(function(s,p){
    console.log("s=%d, p=%d", s, p);
}); // insert catch error block here

for a better understanding of transactions and calls and their difference see this answer or the documentation of web3.