Solidity – How to Get Return Values When One Contract Calls Another

solidity

Suppose I have two Solidity contracts: an App contract and a Data contract:

pragma solidity ^0.4.25;

contract AppContract {
    DataContract dataContract;

    constructor(address _dataContract) {
        dataContract = _dataContract;
    }

    function setData(uint a, uint b) public {
        dataContract.setData(a,b);
    }

    function setData2(uint a, uint b) public returns (uint ab) {
        return dataContract.setData2(a,b);
    }

}

contract DataContract {
    uint stored_a = 0;
    uint stored_b = 0;

    function setData(uint a, uint b) external {
        stored_a = a;
        stored_b = b;
    }

    function setData2(uint a, uint b) external {
        stored_a = a;
        stored_b = b;
        return a*b;
    }

    function getData2() external pure {
        return stored_a*stored_b;
    }
}

So, AppContract has a reference to DataContract and can call functions of DataContract.

I'm confused about return values. I know when using web3 to call Solidity functions, using call() will give you access to the return values but using sendTransaction() will not. If the function changes state then you can't use call. But here it is not web3, it is one contract calling another. Will AppContract always be able to get the return values from all function calls to DataContract functions?

Best Answer

Between contracts, the return values can always be utilized. So if contract A calls contract B, A gets and can utilize the return values.

You are correct in saying that the return values can't be returned outside the blockchain for a transaction. So function return values are just useful for:

  1. Interaction between different contracts

  2. Interaction inside a contract

  3. In view and pure functions, which are called statically from a local node without a transaction. Or when doing such a static call to any function, but knowing that the state changes are not persisted.

Related Topic