0

If I have two contracts, contract A and contract B. How can I change the content of a publicly declared state variables in Contract A from Contract B?

1 Answer 1

2

It's not important that the variable is public. It implies many things but it doesn't imply that anyone or any contract can come along and overwrite it.

contract A will have to explose a function. contract B will need knowledge of this function as well as knowledge of contract A's address. This is more than one way to address each of those concerns. As a starting point, consider.

In contract A, create a function that actually writes to the state variable.

function setValue(uint newValue) public returns(bool success) {
  someValue = newValue;
  return true;
}

in contract B.sol, inform B about the interface and location of A and instantiate an instance.

contract AInterface {
  function setValue(uint newValue) public returns(bool success);
}

contract B {

  AInterface a;

  function B(address addressContractA) public {
    a = AInterface(addressContractA);
  }

  function setThatThing(uint newNumber) public returns(bool success) {
    return a.setValue(newNumber);
  }
}

Hope it helps.

2
  • Hi Rob, so without the interface approach, technically, state variables can't be overwritten by external contracts?
    – NowsyMe
    Apr 22, 2018 at 0:58
  • 1
    Right. No. The internal contract state is 100% under the control of the contract itself and no one gets around that. public is doing a few things, one of which is a "free" getter. It doesn't imply there is a free setter. This convenience function makes sense because there are no access control concerns on read-only functions ... everything is visible to everyone, so it makes sense to make it more convenient. Setters very often do have use-case specific access control concerns, so it makes sense to leave it to the author to decide what is acceptable. Apr 22, 2018 at 1:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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