4

I have a contract deployed on the blockchain that returns multiple values.

contract Test{
   function getAandB( uint x )returns ( uint a, uint b ){

       uint y = x * 2 ;
       return ( x , y )
   }
   }

The question is how do I access both returning values when calling the contract externally from web3?

    var  ( a , b ) = myContractInstance.getAandB( x );      

gives me an error

   var   value  = myContractInstance.getAandB( x );
   console.log ( value.a )

comes back as undefined

6

With new Destructuring assignment syntax you can do this in one line:

let [a, b] = myContractInstance.getAandB.call(2);
console.log("a=", a);
console.log("b=", b);

Output is as expected:

a=2
b=4
4

In the case of multiple return values, Web3 return an array of object.

var value = myContractInstance.getAandB.call(2);
console.log("a="+value[0]);
console.log("b="+value[1]);

The output is:

a=2
b=4
1

From the web3 documentation on MyContract.method.call()

If it returns a single value, it’s returned as is. If it has multiple return values they are returned as an object with properties and indices:

Therefore you should use ES6 Object Destructuring Basic Assignment like so:

let {a, b} = await test.methods.getAandB(x).call();

Be careful: for this basic assignment from object destructuring you need to name the variables identically to the returned object keys -> a and b.

I am not sure if you should call it let {a, b} or let {x,y}. You should actually clean up your code here first. Your code should not have different variable names inside the return statement as compared to the variable names you return from inside the function block. Maybe like so:

   contract Test{
       function getAandB(uint x)
           public
           view
           returns ( uint a, uint b )
       {
          a = x * 2;
          b = x;
       }
   }

I have not tested your code using this, but I used it in similar code before and it worked well for me. Albeit it is a bit pointless to just return the parameter passed to the function.

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.