2

I have a general question about Solidity. Right now I'm looking at a bunch of different contract examples to try and learn the basics, and one thing I'm totally not understanding is why a Contract A is allowed to call into a Contract B using an Interface X if Contract B doesn't implement that Interface X. I'll give an example:

Here is a Contract B:

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract B {
    uint public totalSupply;
    
    function incrementTotalSupply() public {
        totalSupply++;
    }
    
    function getTotalSupply() public view returns (uint) {
        return totalSupply;
    }
}

And here is a Contract A that uses an interface X to call functions in Contract B:

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

interface X {
    function getTotalSupply() external view returns (uint);
}

contract A {
    X state;
    
    function initializeState(address _address) public {
        state = X(_address);
    }
    
    function getTotalSupplyFromB() public view returns (uint) {
        return state.getTotalSupply();
    }
}

This may seem like a dumb question, but isn't it super weird that Contract A can call into Contract B even if B doesn't explicitly say contract B is X or something like that? Does anyone mind expanding on this? Thanks.

A secondary question I have is, well, what is the point of interfaces then? What are they generally used for?

1 Answer 1

0

Interfaces are designed to be easy to extend and use!

Wouldn't it be convenient to have an interface if you wanted to use other deployed contracts?

You just need to care about what methods it has, not how to implement it internally, let alone import its source code, okay!

Interfaces are very important in object-oriented programming languages. I think you should know that. You should learn more as a novice!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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