blockchainethereumsoliditysmartcontractsether

Restrict function access ONLY to one other specific contract in Solidity


I have a security problem in my Solidity contracts and I can't figure out how to fix it.

The flow goes like this:

My problem is:

Can you please offer me advice on how to fix this problem or explain another approach on this? I am new to Solidity. Thank you!


Solution

  • I cannot make a modifier to check the address.

    You can, but the address needs to be in a variable, set after the contract B has been deployed.

    pragma solidity ^0.8;
    
    contract ContractA {
        address contractB;
        
        modifier onlyContractB {
            require(msg.sender == contractB);
            _;
        }
    
        function foo() external onlyContractB {
        }
        
        function setContractBAddress(address _contractB) external {
            contractB = _contractB;
        }
    }
    
    pragma solidity ^0.8;
    
    interface IContractA {
        function foo() external;
    }
    
    contract ContractB {
        IContractA contractA;
        
        constructor(address _contractA) {
            contractA = IContractA(_contractA);
        }
    
        function callFoo() external {
            contractA.foo();
        }
    
    }
    
    1. Deploy contract A
    2. Deploy contract B, passing it the "A" address in the constructor
    3. Set the contractB value in "Contract A".

    I left out any auth mechanism while setting the contractB address in ContractA for simplicity. In this example, anyone can set the address, which you probably don't want, and you should add a mechanism allowing only authorized senders to set the contractB value in ContractA.