0

My question is a variation of this one (old question).

In contract Test, the variable myval is created. In contract Other, an instance of the Test contract is created, and I access the instance variable with the getter function.

However, what if I want to access the same instance from another contract, Other2? If I try to use the same instance name, testContract, an error is raised about undeclared identifier so it must be a visibility issue. I do not want to create a new instance of Test because at some point, the value of myval will change and I need to access its value from multiple contracts.

  1. Is this possible?

  2. Is there an easier way? Note, the structure of Other2 will be much different than Other, so I don't want to just create a child and inherit the same stuff from it.

pragma solidity ^0.4.18;

contract Test { bool public myval; }

contract Other {

Test public testContract;  

function setAddress2() {
    testContract = new Test();
}

function getVal() constant public returns (bool) {
    return testContract.myval();
}

}

contract Other2 { //what to put here?** }

Mat
  • 5
  • 1

2 Answers2

0

pass address of the Test contract as a parameter in constructors of both Other and Other2 contracts. Then access myval attribute as Test(testAddress).myval

Vas Treck
  • 412
  • 10
  • Can this pass be executed programatically instead of manually copying the Test address and pasting it into the Other constructor? – Mat Oct 02 '23 at 15:30
  • Nm, I think I figured it out, thanks. – Mat Oct 03 '23 at 23:14
0

Alternative to the above answer:


contract Other2 {
Test public testContract;  

function setAddressFromOther(Other other){
    testContract = other.testContract();
}

function getVal() constant public returns (bool) {
    return testContract.myval();
}   

}

Just submit tx which calls setAddressFromOther(other_addr) with the address of the Other contract deployed

minhhn2910
  • 1,740
  • 4
  • 14
  • So this works, thanks. How do you accomplish this automatically? Ideally, I don't want to fiddle around with manually copying the address of Other and pasting it into the setAddressFromOther function. I'd like to have the address ready to access within Other2. – Mat Oct 02 '23 at 13:50