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?
Asked
Active
Viewed 5,488 times
1 Answers
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)
Constructor(address)? Also, wouldaddressbe before or after other, explicitly stated arguments of the constructor? And, are there other implicit arguments to an implicit constructor? – TMOTTM Jul 15 '16 at 03:28new, see TokenCreator http://solidity.readthedocs.io/en/latest/contracts.html#creating-contracts – eth Jul 15 '16 at 05:25C1is already deployed. And you would have to write down it's address when it got mined so you can provide it tof2as an argument? – TMOTTM Jul 18 '16 at 16:33