0

Say i have this contract which I have deployed

contract A {
        mapping (string => uint) public someMapping;
}

Now, can I interact with the data of the deployed contractA in some other contractB i.e in contractB can I get the value of someMapping["someString"]?

I am using Truffle along with Ganache and MetaMask.

1

Yes.

There's a gotcha, though. Contracts can't yet pass around dynamic-length arguments, so strings won't work. I changed to bytes32 to make the simple example work.

With that detail out of the way ...

Contract B must have knowledge of contract's A ABI (the function signatures) and it's address.

The easiest method is to include both files in the same source file. Note that you can deploy B only if A is already out there somewhere and you have knowledge of its address.

B.sol

contract A {
  mapping (bytes32 => uint) public someMapping;
}

contract B {
  A a; // cast "a" as "contract A" defined above

  function B(address addressA) public { // pass address of "A" to the constructor
    a = A(addressA);
  }

  function getAUint(bytes32 key) public view returns(uint) {
    return a.someMapping(key);
  }
}

You will obviously have to extend this example to set values in A somehow so the test is a little more interesting.

If the keys really do need to be strings, you might consider using bytes32 hashes of the strings. This way, every unique string will create a unique fixed-size key. Stringy keys is almost always a sign of going astray in Solidity.

Hope it helps.

  • Thanks for your help. I am getting this error TypeError: Member "someMapping" not found or not visible after argument-dependent lookup in type(contract "A") I have declared someMapping as public in contract A – anuyog Apr 17 '18 at 18:23
  • someMapping() - with the brackets, because it's a function. – Rob Hitchens Apr 17 '18 at 19:16

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.