1

Assume I have deployed ContractA and want to call the function updateX. I can use create an instance of the ContractA or I can use an interface. When you use which one? Both updateXFromB and updateXFromBUsingInterface works perfectly fine...

pragma solidity ^0.8.0;


interface IContract {
    function updateX(uint _x) external;
}

contract ContractA{ 
    uint public x;

    function updateX(uint _x) public {
        x = _x;
    }
}


contract B {
    function updateXFromB(address _A, uint _x) public {
        ContractA c = ContractA(_A);
        c.updateX(_x);
    }

    function updateXFromBUsingInterface(address _A, uint _x) public {
       IContract(_A).updateX(_x);
    }
}

1 Answer 1

0

You don't see a difference because you are on the same file when you deploy.

If you had separated contractA and B into two file and deployed contractA and tried to call a function updateX from contract B using an instance, your code would give an error. However, interface option would work just fine. Use interface when you don't have access to the code (you need function signature and contract address). Otherwise, you need to copy contractA to your contract B.

In a way,interface brings you the functionality without increasing the complexity (You don't need to copy the function).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.