Is there any way to get return value from my method/function using web3?

    function sell(address _seller, uint256 _amount) public returns (uint256 _ethUserShouldReceive) {   
        uint256 _etherAmount = _amount.div(sellPrice);
        uint256 _ownerBalance = owner.balance;
        require(_ownerBalance >= _ownerBalance.sub(_etherAmount));         
        require(balances[owner] >= _amount);                                    
        _transfer(_seller, owner, _amount);
        Sell(_seller, _amount, sellPrice);   

        return _etherAmount;

Above code is part of my Smart contract which return value. I want to call the function to execute _transer() and then get the value.

I tried the send() function like below.

    .sell(address, amount)
    .send({ from : tokenOwner})
    .then(res => {
      console.log("res: ", res);
    .catch(err => {
      console.log("err: ", err);

But I got JSON RPC error.

err:  Error: Invalid JSON RPC response: ""
at Object.InvalidResponse (errors.js:42)
at XMLHttpRequest.request.onreadystatechange (index.js:73)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:546)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:387)
at XMLHttpRequest.js:493
at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
at MessageQueue.__callFunction (MessageQueue.js:353)
at MessageQueue.js:118
at MessageQueue.__guardSafe (MessageQueue.js:316)

I thought the _transfer function need a signed Serialized Transaction so I changed like below.

const data = myContract.methods.sell(address, amount).encodeABI();

I signed the transaction with that data above. It works well but I can't get the return value which I really want to know about. How can I deal with this? Is there any way to get the return value right away after _transfer() is succeed?

Please give me some idea How to optimize or fix this.

  • So the function which changes the state of Blockchain can't return value. I tried the event myContract.events.MyEvent([options][, callback]) but I couldn't use it in some reason. I got an error. so I decided the event emitter when I sendSignedTransaction. web3.eth.sendSignedTransaction("serializedTX", (err, txHash) => {}).on("confirmation", confirmation => {}).then("receipt", receipt => {}).catch(err => {});The receipt is always returned whether the transaction is success or failed. If the transaction failed, the status value will be 0 and it contained the logs which is the event logs. Apr 4, 2018 at 2:16


Browse other questions tagged or ask your own question.