0

Imagine I'm developing a simple function as the following:

       uint256 state;  
       event Addition(uint256 result);

       function addition(uint256 a, uint256 b)
            public       
            returns (uint256)
        {
            
            uint256 result = a + b;
            state = result;
            emit Addition(result);       
    
            return result;
        }

How can I get the returned value (result)? I know that I can get the value listening the event Addition, but in that case... Why should I return values? When I execute the function with web3.js in my javascript frontend, I can wait until the transaction finishes, but the result don't came with transaction response.

2
  • 1
    Not possible for transactions. ‚Return‘ works only between contract interaction. You can use events and then search the log in the transactionReceipt
    – Majd TL
    May 18 at 11:52
  • Listening from another Smart Contract makes sense for the return value ;)
    – AlexAcc
    May 18 at 12:07

2 Answers 2

1

I believe the problem you're describing is because you are trying to get a return variable from a function which is marked as non-static (not pure/view). Unfortunately, as far as I can tell, it's not possible to get a function result from a mined transaction.

However, you should be able to tell web3js to evaluate this function in a static context. With ethersjs this is .callstatic. With web3js this might mean that (not too familiar with web3js) you use .call instead of .send in order to get a function result.

0

Your function is neither pure nor view so it returns transaction receipt instead of the return value. This function would return result:

   function addition(uint256 a, uint256 b)
        public
        pure    
        returns (uint256)
    {
        
        uint256 result = a + b;

        return result;
    }
1
  • Yes sure, but I was talking in case of not view/pure functions (I created/modified a state variable to better illustrate the example).
    – AlexAcc
    May 18 at 12:07

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