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
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);
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With