5

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.

user1687711
  • 249
  • 3
  • 9

1 Answers1

8

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.

Stan James
  • 472
  • 5
  • 9
manuhalo
  • 812
  • 7
  • 18
  • hi @manuhalo which is recommended way using event or invoking via call, appreciate your view – user1687711 May 01 '17 at 16:19
  • 1
    @user1687711 as mentioned above it depends on what you are trying to achieve. For this particular function it looks like a call is perfectly fine, as you are not changing any variable in your contract, just using the input arguments to generate some output that is not stored. However if you wanted to save the calculated area to a private member of your contract for some reason then you would need to use transactions and events. See http://truffleframework.com/docs/getting_started/contracts#reading-amp-writing-data for a better explanation of this. – manuhalo May 01 '17 at 16:30