我很难理解 Solidity 中的接口。我缺少什么?

Wow*_*Bow 6 interface ethereum solidity

我有 Java OOP 背景并了解接口。

目前正在开发一个简单的预算应用程序(https://github.com/compound-developers/compound-supply-examples),该应用程序将 ETH 或稳定币放入Compound 中并赚取利息。

我的困惑是如何使用 Solidity 接口。我有 OOP (Java) 背景,非常熟悉接口。

所以在这段代码( )中你可以看到界面中MyContracts.sol有一个函数。mint()但是,它没有实现,但您可以看到这里使用它而uint mintResult = cToken.mint(_numTokensToSupply);没有任何实现。

任何人都可以在没有实现的情况下如何使用接口函数吗?在这种情况下,当您调用mint时,实际上正在执行哪些代码?

Wow*_*Bow 20

我相信我找到了令我困惑的主要问题。

因此,如果您有 OOP 背景,那么我们对接口的了解如下:

interface IERC20 { 
   function totalSupply() external view returns (uint256);
}

contract XYZ is IERC20 {
// then implement totalSupply here 
function totalSupply() external view returns (uint256) {
// implementiation goes here. 
address public add='0x123...4'
}
Run Code Online (Sandbox Code Playgroud)

所以此时您可以致电 XYZ totalSupply(),应该没问题。

然而,还有另一种在 Solidity 中使用接口的方法。我将以复合协议中的代码为例(https://github.com/compound-developers/compound-supply-examples

如果你看到MyContracts.sol,它有以下界面:

interface CEth {
    function mint() external payable;

    function exchangeRateCurrent() external returns (uint256);

    function supplyRatePerBlock() external returns (uint256);

    function redeem(uint) external returns (uint);

    function redeemUnderlying(uint) external returns (uint);
}
Run Code Online (Sandbox Code Playgroud)

然而,我们的合约中没有任何地方使用关键字IS并实现任何方法。那么您可能会问我们的界面是如何使用的?

现在让我们回到文件MyContract中的合约MyContracts.sol并在supplyEthToCompound函数下查看此代码:

CEth cToken = CEth(_cEtherContract);
Run Code Online (Sandbox Code Playgroud)

在这里,我们提供带有Compound合约地址的CEth接口(即_cEtherContract该地址的合约有一个mint()函数。)

当您调用 cToken.exchangeRateCurrent();下一行时,会发生的情况是我们基本上是在复合合约上调用函数ExchangeRateCurrent

乍一看,exchangeRateCurrent在我们调用它的文件中似乎没有实现,但实现位于_cEtherContract地址。

我希望这能消除困惑,特别是如果您来自传统的 OOP 背景。

请随意指出我的回答中任何误导性的内容。