[Ethereum] How to access Objects from different Contracts

inheritancemappingsoliditystruct

Goal: I want to create a solidity programm that includes 3+ contracts. This means I have one contract (lets call it master for now) which aims at setting everything up. This means this contract has a function that ask for addresses of contracts that should interact with each other. The master stores this address information and can later pass it to other contracts. I will have 3+ other contracts that get this "contact information" from the Master contract and then those 3+ start interacting with each other(Changing other variables, calling functions of other contracts)

Example:
Contract has a Setup-Function that asks for addresses of contracts A and B. He stores those addresses and calls Function 1 of contract A. Now Function 1 of contract A does some stuff, then looks up the address of Contract B (this is where I struggle) and calls Function 2 which belongs to Contract B.

Question: Can somebody help me with this question and give me some example code? I already tried passing a struct with the addresses from the Master to A and B, tried to store them in a mapping and tried to make my Master contracts data accessible to A and B via inheritance.

If you have any trouble understanding this question feel free to ask 😉

Best Answer

Owing to time constraints I can answer indirectly with a (hopefully) clear pattern.

pragma solidity ^0.4.11;

contract A {

    function talkToMe() public constant returns(bool success) {
        return true;
    }
}

contract B {

    A a; // contract "A" called "a"

    event LogResponse(bool whatItSaid);

    function B() {
        a = new A(); // deploy B and it will make it's own A and note the address
    }

    function prove() public returns(bool success) {
        bool response = a.talkToMe();
        LogResponse(response);
        return response;
    }

    function newA(address addressA) public returns(bool success) {
        a = A(addressA); // start using previously deployed A 
        return true;
    }
}

Here it is Remix to show it working.

  1. Deploy B
  2. prove()

enter image description here

This answer addresses some more concerns like keeping track of the contracts generated by the "factory". Is There a Simple Contract Factory Pattern?

Hope it helps.

Related Topic