8

What is a basic example of one contract invoking a method in another (non-calling) contract? Would the address of the contract having that method always need to be hardcoded?

1 Answer 1

10

The contract address does not need to be hardcoded.

Here's an example:

contract C1 {
    function f1() returns(uint) {
        return(10);
    }
}

contract C2 {
    function f2(address addrC1) returns(uint) {
        C1 c1 = C1(addrC1);
        return c1.f1();
    }
}

To quickly test, paste the code in https://ethereum.github.io/browser-solidity

Then click on "Create" for C1 and C2. Then in C2's input box for "f2", put the address of C1 in quotes, and click on "f2" to invoke it.

You'll see (10 equals "a" in hexadecimal):

Result: "0x000000000000000000000000000000000000000000000000000000000000000a"
Cost: 548 gas. 

EDIT: In case you try to invoke f1 or f2 by using web3.js, you will not get the return value unless you explicitly use .call or add constant in the Solidity.

Example of ".call": contractInstance.f2.call(someAddress)

Example of "constant": function f2(address addrC1) constant returns(uint)

6
  • Where in the documentation is it described, that I create a contract object by Constructor(address)? Also, would address be before or after other, explicitly stated arguments of the constructor? And, are there other implicit arguments to an implicit constructor?
    – TMOTTM
    Jul 15, 2016 at 3:28
  • @TMOTTM In this example, C1 is already deployed. For an example of creating a contract, which uses new, see TokenCreator solidity.readthedocs.io/en/latest/…
    – eth
    Jul 15, 2016 at 5:25
  • Ok, so C1 is already deployed. And you would have to write down it's address when it got mined so you can provide it to f2 as an argument?
    – TMOTTM
    Jul 18, 2016 at 16:33
  • @TMOTTM Yes, an address is needed.
    – eth
    Jul 18, 2016 at 22:56
  • @eth I was trying to run the above code, but instead of say the integer 10, if I were to return string, i see the error on the online solidity compiler: return argument type inaccessible dynamic type is not implicitly convertible to expected type (type of first return variable) string memory. Any idea how this error can be avoided? - this is at the line in the second contract which calls the first contract.
    – skarred14
    Sep 29, 2016 at 17:10

Your Answer

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

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