Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to modify a variable value from another contract?

I could get the information about access another contract's variable from here

But I couldn't find how to modify another contract's variable.

Here is the example of contract A,

contract A {
    uint public target;
}

And this is the example of contract B

contract B {
    function edit_A_a() public {
        A.target = 1;  // some kind of this
    }
}

I want to modify the value of target variable from contract B.

Also, assuming that all operations are executed in a solidity contract level.

Thanks

like image 448
Henry Kim Avatar asked Mar 23 '18 12:03

Henry Kim


2 Answers

Declaring a state variable as public generates a public getter, but not a setter. If you want another contract to modify your contract's state variable, you'll have to write a function to do that yourself:

contract A {
    uint public target;
    function setTarget(uint _target) public {
        target = _target;
    }
}

contract B {
    A a = Test(0x123abc...);  // address of deployed A
    function editA() public {
        a.setTarget(1);
    }
}
like image 193
user94559 Avatar answered Nov 20 '22 17:11

user94559


No, you can't directly edit a variable of a contract. That would be a security nightmare.

You can only use public/external functions provided by an external contract through interfaces. If that function itself is a setter and allows you to change a variable, only then it is possible.

Contract A:

contract A {
    uint myVariable = 1

    function setMyVariable(uint _newVar) public {
        myVariable = _newVar;
    }
}

Contract B:

interface A {
    function getMyVariable() view public returns(uint);
}

function setMyVariable(uint _newVar) public onlyOwner {
    A a = A([CONTRACT A ADDRESS HERE])
    a.setMyVariable(_newVar);
}
like image 8
ReyHaynes Avatar answered Nov 20 '22 17:11

ReyHaynes