Solidity – Function Doesn’t Return Data When Executed with Injected Web3 MetaMask

blockchainmetamaskropstensolidity

There is my code. getRight function doesn't return data when I run this code with injected web3 metamask but it returns data when I run it with JavaScript VM. I did it find where is the problem in order to fix it.

pragma experimental ABIEncoderV2;
contract AccessControlManagment
{
    string idReq;
    string actionn;
    string idRes;
    struct  right {
       string idRequester;
       string idResource;
       string action;
    }

    function addReq(string memory id) public{
         idReq =id;
   }
    function addRes(string memory id) public{
         idRes =id;
   }
   function addRight(string memory idRequester,string memory idResource, string memory action) public{
         right memory r = right(idRequester,idResource,action);
         idReq =idRequester;
          idRes =idResource;
         actionn = action;
   }
   function getidReq() public  returns (string memory){
       return idReq;
   }
   function getidRes() public  returns (string memory){
       return idRes;
   }
   function getaction() public returns (string memory)
   {
       return actionn;
   }
   
   function getRight() public  returns (string memory, string memory,string memory) {
       
       return (idReq,idRes,actionn);
       
   }
}

Best Answer

To get a return value with Web3 from a solidity function you have one of two options:

  • First, you can mark the function view, which means that function cannot update the state or ledger, and then the return value will be returned to Web3 when using call()
  • Second, if your function updates state, then you can emit an event with the data you want to retrieve, and then later in the web3.js retrieve the data from the event. (see this web3 method: https://web3js.readthedocs.io/en/v1.3.4/web3-eth-contract.html#getpastevents)

Based on the code provided, it seems like you would need to mark getRight() as view, and that would return the data you are looking for. You might also want to return it as an array value instead of tuple. I'm not sure that Web3.js would know how to handle a tuple return type.

Related Topic