6

How would I call one contract's function from within another contract? I tried to find documentation on this all morning and wasn't able to find anything.

4
  • Here? solidity.readthedocs.io/en/develop/…
    – vincentLg
    Jun 7, 2017 at 14:20
  • @vincentLg , so I can use JavaScript API inside a contract being written in Solidity language? Jun 7, 2017 at 14:31
  • 1
    web3js is for the frontend inwhich you could call the function in solidity contract (backend)
    – Badr Bellaj
    Jun 7, 2017 at 15:08
  • 2
    This looks like it was downvoted a bit, but I actually found this rather tough to find in the docs even after a thorough read Sep 14, 2017 at 23:17

2 Answers 2

4

Please find an example here (call part of this section) in solidity documentation where calling an already deployed contract from inside another contract is shown. We can call functions in other deployed contracts using

address nameReg = 0x72ba7d8e73fe8eb666ea66babc8116a41bfb10e2;
nameReg.call(bytes4(keccak256("fun(uint256)")), a);

Here the first parameter is the function signature and the next parameters are arguments for the function.

3
1

Try to employ this approach here as it is easier to read and is promoted for uses, such as ERC20 token interaction:

contract Called{
    uint public myuint;

    function set(uint _var) {
        myuint = _var;
    }

    function get() view returns (uint){
        return myuint;
    }
}

interface Called{
    function set(uint);
    function get() view returns (uint);
}

contract Caller {

    Called public called_address;

    function set_address(address _addy) {
        called_address = Called(_addy);
    }

    function set(uint256 _var) {
        called_address.set(_var);
    } 

    function set_call(address _called, uint256 _var) {
        require(_called.call(bytes4(sha3("set(uint256)")), _var));
    }
}

Here you have an already deployed contract "Called" and can access it with an interface block included as part of your contract file. The last function set_call is same to previous answers on this page and is left for comparison.

Be aware that all calls from your contract cost gas, even if the functions are marked view.

Credit to @eli-drion for providing code that I didn't need to drum up from scratch: https://ethereum.stackexchange.com/a/44384/36872

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.