0

With respect to the following code:

pragma solidity ^0.4.23;

contract xyz {
   uint x = 0;

   function setX(uint pX) public {
       x = pX;
   }

   function getX() public view returns(uint){
       return x;
   }
}

contract abc{
    xyz public obj = new xyz();

    function getValueOfObj() public view returns(uint){
        return obj.getX();
    }

    function setValueOfObj(uint pX) public{
        obj.setX(pX);
    }
}

I am working in truffle console and I use:

var abcDeployed = abc.deployed().then((i) => {abcDeployed = i});
var xyzDeployed = xyz.deployed().then((i) => {xyzDeployed = i});
var contractXYZ = web3.eth.contract(xyzDeployed.abi, xyzDeployed.address);
var contractXYZInstance = contractXYZ.at(abcDeployed.obj());

And when I try to call:

contractXYZInstance.getX()
Error: invalid address

How do I access the properties of contract xyz from the contract abc in truffle console or using web3?

  • 1
    You might want to print out the return value of abcDeployed.obj() to see what that's returning. – user19510 Jul 21 '18 at 22:48
  • For example: abcDeployed.obj() is returning this 0x23cba2a17c44171894a7cd2ae9b807282bd1c323 – Prabhanjan Naib Jul 22 '18 at 1:30
  • That address looks fine. Perhaps it's the from address of the transaction? Maybe use an explicit from address. – user19510 Jul 22 '18 at 2:29
  • How to do that? – Prabhanjan Naib Jul 22 '18 at 19:27
-1

If you are deploying both contracts, you will need to have the second contract reference the address of the first contract.

Something like this:

pragma solidity ^0.4.23;

contract Contract1 {
   uint x = 0;

   function setX(uint pX) public {
       x = pX;
   }

   function getX() public view returns(uint){
       return x;
   }
}

contract Contract2{
    Contract1 contract1;

    function setContract1 (address addr) public {
        contract1 = Contract1(addr);
    }

    function getValueOfObj() public view returns(uint){
        return contract1.getX();
    }

    function setValueOfObj(uint pX) public{
        contract1.setX(pX);
    }
}

Then, once you set the correct address within the second contract, you can simply call the functions from the second contract, which will pull and push to the first contract.

  • This doesn't seem to relate to the question, where one contract is deployed by the other. – user19510 Jul 21 '18 at 22:49
  • I think I misunderstood then – Shawn Tabrizi Jul 21 '18 at 22:50
  • This method is not feasible if I have many contract objects and if they also have many properties. – Prabhanjan Naib Jul 22 '18 at 1:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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