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

2

17

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

Radiology answered 23/3, 2018 at 12:17 Comment(3)
Hello and welcome to Stack Overflow. Please take a moment to review the following how-to resources: How to Ask and Complete Examples. – Infinite
@lavor Hi! Thank you for your feedback on the question. I added some content, what else can I add? – Radiology
Good job adding the extra information. πŸ‘ – Infinite
P
17

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);
    }
}
Pomology answered 23/3, 2018 at 14:38 Comment(1)
Thank you! It was really helpful answer :) – Radiology
M
7

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);
}
Malva answered 23/3, 2018 at 14:45 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.