1

In Solidity, is it possible to change states via function calls in other contracts?

For example, let's consider the code below, where we have three assumptions:

  1. The function test2 is defined in the contract C2.
  2. The contract object c2 of the type C2 is created at somewhere within C1.
  3. We deployed C1 as a root contract.

Then, is it possible for the function call statement c2.test2() to change the values of variables in C1 (e.g., x1, x2, x3, etc)?

Contract C1 {
  uint x1;
  uint x2;
  uint x3;

  ...

  function test1 () public{
     /* can c2.test2() change the values of variables */
     /*   within C1? (e.g., x1,x2,x3, etc) */
     c2.test2 (); 
  }  
}

1 Answer 1

2

A contract's state variables can only be changed by that contract. But of course the contract can expose a method that other contracts can call, e.g.:

contract C1 {
    uint256 foo;
    function setFoo(uint256 value) external {
        foo = value;
    }
}

Now anyone (and any contract) can call setFoo to change the value of C1's foo state variable.

Your Answer

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

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