BudiBadu Logo
Samplebadu

Solidity by Example: Interfaces

0.8.x

Contract interaction patterns with this code example showing interface definitions for external contracts, the IERC20 token standard, casting addresses to interface types, and calling functions on deployed contracts without knowing their implementation.

Code

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

// Define interface for an ERC20 token
interface IERC20 {
    function transfer(address recipient, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

contract MyContract {
    // Call function on another contract using interface
    function sendTokens(address _tokenAddress, address _to, uint256 _amount) public {
        // Initialize interface with address
        IERC20 token = IERC20(_tokenAddress);
        
        // Call the function
        token.transfer(_to, _amount);
    }
    
    function checkBalance(address _token, address _user) public view returns (uint256) {
        return IERC20(_token).balanceOf(_user);
    }
}

Explanation

Interfaces define a contract's external API without any implementation code, enabling contracts to interact with each other in a type-safe manner. An interface looks like a contract but cannot have function implementations, state variables, constructors, or inherit from other contracts. All functions must be declared as external, and interfaces serve as a blueprint that other contracts can implement or interact with.

To interact with another deployed contract, you cast its address to the interface type using syntax like IERC20(tokenAddress). This gives you a typed handle to call the functions defined in the interface. This pattern is fundamental to DeFi and blockchain composability, allowing contracts to interact with tokens (ERC20, ERC721, ERC1155), decentralized exchanges (Uniswap, SushiSwap), lending protocols (Aave, Compound), and any other deployed contract.

Interfaces enforce standardization across the ecosystem. The ERC20 interface, for example, ensures that all fungible tokens implement the same functions like transfer(), balanceOf(), and approve(). This allows wallets, exchanges, and other contracts to interact with any ERC20 token using the same code. If a contract claims to implement an interface, it must provide implementations for all declared functions, ensuring compliance with the standard.

Code Breakdown

5-8
interface IERC20 lists function signatures without implementation.
6
external visibility is required for all interface functions.
14
IERC20(_tokenAddress) casts address to interface type for function calls.
17
token.transfer() calls the external contract's transfer function.