Question:

Cyclic dependency in smart contracts?

Olivia: 24 May 2022

How can we manage cyclic dependency in solidity smart contracts?

for example:

contact A {
   B b = B();

}

contract B {
 A a = A()
}

Answer:
Ava: 24 May 2022

Option #1 - if you want to support initialization only from the off-chain:

File IA.sol:

pragma solidity ^0.4.24;

interface IA {
    // Declare here every function which you want to invoke
    // from other contracts (i.e., not from the off-chain).
}

File A.sol:

pragma solidity ^0.4.24;
import "./IA.sol";
import "./IB.sol";

contract A is IA {
    IB public b;
    function set(IB _b) external {b = _b;}
    // Implement the rest of the contract here.
}

File IB.sol:

pragma solidity ^0.4.24;

interface IB {
    // Declare here every function which you want to invoke
    // from other contracts (i.e., not from the off-chain).
}

File B.sol:

pragma solidity ^0.4.24;
import "./IA.sol";
import "./IB.sol";

contract B is IB {
    IA public a;
    function set(IA _a) external {a = _a;}
    // Implement the rest of the contract here.
}

Option #2 - if you want to support initialization from both the off-chain and the on-chain:

File IA.sol:

pragma solidity ^0.4.24;

interface IA {
    // Declare here every function which you want to invoke
    // from other contracts (i.e., not from the off-chain).
    function set(address _b) external;
}

File A.sol:

pragma solidity ^0.4.24;
import "./IA.sol";
import "./IB.sol";

contract A is IA {
    IB public b;
    function set(address _b) external {b = IB(_b);}
    // Implement the rest of the contract here.
}

File IB.sol:

pragma solidity ^0.4.24;

interface IB {
    // Declare here every function which you want to invoke
    // from other contracts (i.e., not from the off-chain).
    function set(address _a) external;
}

File B.sol:

pragma solidity ^0.4.24;
import "./IA.sol";
import "./IB.sol";

contract B is IB {
    IA public a;
    function set(address _a) external {a = IA(_a);}
    // Implement the rest of the contract here.
}