0

I have a solidity function:

function something(bytes32 hash) public returns (bool) {
    bool success;
    success = check(hash);
    emit LogSomething(msg.sender, hash, success);
    return success;
}

and I try to show its result on Web3:

contractInstance.something(hash, params, function(error, result){
    if (error) {
        alert("Error!");
    } else {
        $("span#result").text(result);
    }
})

However, in my result span, I get the transaction hash:

0xd0039716e5834ac880f3b66e024c29e4b25cdf69e26b4f19e278f116d6a2fec2

instead of a True or False as expected from a boolean output. Why is this so? There are no error messages whatsoever and I'm confident in the code logic.

1

You get the actual returned value of a non-constant function (neither pure nor view), only when you call it on-chain (i.e., from another function in this contract or from another function in another contract).

When you call it off-chain (e.g., a web3.js script, a web3.py script, Remix, MyEtherWallet), you get the transaction receipt.

This is because when you call it on-chain, the function has completed its execution by the time it returns, but when you call it off-chain, it is only encapsulated in a transaction and passed to the miners (who may choose to execute it at any time in the future).

| improve this answer | |
  • Hi! How may I obtain the boolean I want then? – Sample_friend Apr 28 at 6:58
  • @Sample_friend: You can't. The returned value is designated to be used only by other contract functions which call your function. In order to obtain it in an off-chain script, you have the following options: 1. Before returning that value in your contract function, emit an event which contains it. Then, the receipt that you get in your script after executing the contract function will contain this event. 2. If the function changes a public state-variable in your contract, then you can simply check if the value of that variable has changed to what you expect it to after calling the function. – goodvibration Apr 28 at 7:58
0

Change your javascript to this:

contractInstance.something(hash).call({}, function(error, result){
    if (error) {
        alert("Error!");
    }else {
        console.log(result, 'result');
    }
}

You can read more about .call() web3 method here. Since your smart contract method something is just a get method you don't have to write on the blockchain and it is not needed transaction to be signed and sent to the blockchain. And because of this reason you should add view keyword to method something in your smart contract.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.