1

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.

Alexander Herranz
  • 1,858
  • 2
  • 17
  • 35

2 Answers2

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.

phaze
  • 1,575
  • 4
  • 12
1

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;
}

MantasFam
  • 327
  • 3
  • 13