I already have searched for my question on Stack Overflow and on the documentation (https://docs.soliditylang.org/en/develop/contracts.html#visibility-and-getters), but I am not sure of the answer.
To better explain my answer, I have created an example:
pragma solidity ^0.8.17;
contract A{
bool public dummy;
function setDummy (bool x) public{
dummy = x;
}
function getDummy () public view returns(bool){
return dummy;
}
}
contract B {
A public aContract;
function initialize () public{
aContract = new A();
}
}
If I deploy B
and call initialize, I can see the address of aContract
. This means that I can interact with the aContract
(like calling setDummy
) without passing by B
.
I do not want this behavior!
I would like that only B
can call aContract
. Does make aContract
private solve this problem? Or I need to make some restriction like onlyOwner
on setDummy
?
I do not know if making aContract
private still leave some vulnerabilities.
Thank You!
Using the new
keyword in Solidity will create a new instance of your contract just as if you had deployed it from your EOA. There is no solidity language feature to restrict visibility of the deployed contract. You will have to implement yourself the access control you need.
A typical pattern in Solidity is to make the contract have an "owner" which is the only address authorized to call certain functions. For example it can be implemented with the Ownable
abstract contract from Openzeppelin.
With the code below the owner will be set by the Ownable
constructor to the deployer address, which in your case will be your B contract instance. And the onlyOwner
keyword restricts setDummy
so that it can only be called by the owner
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract A is Ownable {
bool public dummy;
function setDummy (bool x) public onlyOwner {
dummy = x;
}
function getDummy () public view returns (bool) {
return dummy;
}
}