0

i have two contracts the first one has a function which must be called only by the second contract :

contract A {
    address contractBAddress;
    uint256 number;
    modifier onlyB() {
        require(msg.sender == contractBAddress, "caller must be contruct B");
        _;
    }
    constructor(address _contractBAddress) {
        contractBAddress= _contractBAddress;
    }
    function setNumber(uint256 _number) public onlyB {
         number = _number;
}

contract B { A a; constructor(address _contractAaddress) { a = A(_contractAaddress); } function setNumber(uint256 _number) public { a.setNumber(_number); }

So, the contract A needs contract B address for the modifier and the contract B needs the contract A for calling setNumber function . does that cause a recursive dependency problem ? is the any other alternative to implement this ? Thank you and happy christmas .

noro meb
  • 338
  • 1
  • 12

1 Answers1

1

Yes, the above code introduces a recursive dependency between contract A and contract B, as each contract depends on the other to function correctly. you can use a factory or proxy pattern to avoid this.

Factory You can use a factory contract to deploy both contract A and contract B at the same time, and pass the addresses of each contract to the other as arguments in their constructors.

Proxy The contract A is deployed first and a proxy contract (contract C) is deployed that delegates calls to contract A. Contract B can then call contract C, which will forward the call to contract A. Learn more : https://blog.openzeppelin.com/proxy-patterns/

Badr Bellaj
  • 18,780
  • 4
  • 58
  • 75