1
votes

I am trying to return a value using a function of a deployed smart contract on the blockchain.

pragma solidity 0.6.2;

contract Caller {

   address cont;

   function changeAdd(address _change) public {
     cont = _change;
   }

   function caller (bytes memory test) public returns(bool, bytes memory) {
      bytes memory payload = abi.encodeWithSignature("callMe(bytes)", test);
      (bool success, bytes memory result)= address(cont).call(payload);
      return (success, (result));

   }

   function viewCont() public view returns(address) {
       return cont;
   }  
}

And the deployed test contract is this:

pragma solidity 0.6.2;

contract Store {

  uint counter;

  function callMe(bytes calldata test) external returns(bytes memory) {
     counter++;
     return abi.encode(test);
  }

  function viewCounter () public view returns(uint256) {
     return(counter);
  }

  function clearCounter() public  {
     counter = 0 ;
  }   
}

In this example, I am deploying contract "Store" on the blockchain where it is assigned a random address, which can be pointed at via the Caller.changeAdd function in order to use Caller.caller function. Thus, I am trying to send data in the form of bytes to the Store contract, which is supposed to send back the same data to the Caller contract. I am trying to isolate -only- the data that is originally sent, so I can use it to test interaction between smart contracts on the blockchain. I tried in the beginning to send an integer, but I couldn't find a way to do it. So I used bytes and it worked, but still the data I receive isn't the same that I send in the first place(e.g. I send 0x0 and I receive a big bytes number, which isn't the same as 0x0).

I could appreciate any help on how to receive and handle data between two different, unlinked smart contracts, thank you in advance.

1

1 Answers

1
votes

Do you try to use abi.decode function of Solidity.

In the below example, contract B calls setName of contract A, then decodes the result by using abi.decode function.

contract A {
    string public name;
    constructor(string memory tokenName) public {
        name = tokenName;
    }

    function setName(string memory newName) public returns ( string memory){
        name = newName;
        return newName;
    }
}


contract B  {
    event Log(string msg);
    string public myName;
    function call(address addr, string memory newName) public {
        bytes memory payload = abi.encodeWithSignature("setName(string)", newName);  
        (bool success, bytes memory result)= addr.call(payload);

        // Decode data
        string memory name = abi.decode(result, (string));

        myName = name;
        emit Log(name);
    }
}