2

Currently I am getting the transaction receipt instead of return value from a contract function using web3. Is there anyway to get the actual return value from a contract function call using web3

example code

Solidity

pragma solidity ^0.4.22;
contract Testing {
    string name;
    function setName(string name) public returns(string) {
        name =name;
        return name;
    }

    function getName() public returns(string) {
        return name;
    }
}

JavaScript

myContract.methods.setName(Hello).send({
    from: 0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db,
    gas: 470000,
})
.then((receipt) => {
    console.log(receipt)  ==> not getting the result
    }
})

marked as duplicate by Soham Lawar, Ismael, shane, Achala Dissanayake, eth Sep 11 '18 at 10:43

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • I think getting return value from a contract function is straight-forward. please provide your source code. – Ha ĐANG Sep 7 '18 at 5:11
0

If you are issuing a transaction to the contract, you will always just get a receipt as the transaction has to be first processed by the blockchain. After it has been processed you can query for the result with the transaction information (web3 has some shortcuts for this).

Seeing as your getName function is just reading data, you can denote it with the view keyword. When a function is a view function it does not access the blockchain and it's able to read the value directly from your node. Then you will get the result immediately instead of a transaction receipt.

0

If you want to return the value of the Solidity function using Web3, you need to use the call() method rather than send().

In your case the change should be simple:

myContract.methods.setName(Hello).call({
    from: 0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db,
    gas: 470000,
})
.then((result) => {
    console.log(result)
    }
})

However, it is important to note that call() does not actually send a real transaction. Instead, it executes the operation in your ethereum provider's EVM, and returns any errors or values that would result.

One option is to do both a call() and send() to first check that the result is what you expect, then actually send the real transaction.

The other option is to wait for your transaction to be included in a block, and then read from the contract the state of the variable you are interested in. This might be most effective by emitting an event from the function, and listening for that event to check when the transaction has been executed.

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