Interface in Solidity smart contracts

An interface in Solidity behaves similarly to interface agreements in traditional object-oriented programming languages. In object-oriented programming an interface is a description of all functions that an object must have in order for it to operate. The purpose of an interface is to enforce a defined set of properties and to execute specific functions in another object. For example when you flip a light switch, the light turns on. You do not care how the light turned on just that it does.

What is an interface in Solidity?

Interfaces are often found at the top of a smart contract. They are identified using the “interface” keyword. The interface contains function signatures without the function definition implementation (implementation details are less important). You can use an interface in your contract to call functions in another contract.

The example below illustrates a sample smart contract with the IERC20 interface. The function signatures of this interface are in list format and end with a semicolon. The interface does not need the body (implementation details) of each function. Adding this interface makes the IERC20 functions available for use in the sample contract.

//import the IERC20 interface
//the IERC20 interface lists functions available but no definitions
//as an example you do not know what totalSupply, balanceOf and transfer do
//because there is no function definition or function implementation listed
//you do know that the functions are available to use

pragma solidity ^0.8.7;

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address recipient, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient,uint256 amount) external returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

contract sampleContract{
     // do something     
     // do something
 }

Interfaces are most useful in scenarios where your application requires extensibility but you do not want to introduce added complexity. They reduce code duplication and overhead.

Interface characteristics

  • Create an interface with the “interface” keyword
  • Some interface names start with an “I” to make them easier to identify in the code
  • All interface functions are implicitly virtual
  • You can override an interface function
  • Contracts can inherit interfaces as they would inherit other contracts
  • Interfaces can inherit from other interfaces which is the same rules as normal inheritance
  • All functions that inherit from the interface must set the override modifier on every function that overrides an interface function. If not the compiler will throw an error
  • Data types defined inside interfaces can be accessed from other contracts. For example a contract that uses the sample interface below can access Iauto.carType and Iauto.vehicle.
pragma solidity ^0.8.7;

interface Iauto {
    enum carType { gas, electric}
    struct vehicle { string car; string truck; }
    function transfer(address recipient, uint amount) external;
}

Interface restrictions

  • They cannot inherit from other contracts, but they can inherit from other interfaces
  • Functions of an interface can be only of type external
  • They cannot declare a constructor
  • They cannot declare state variables

How to create an interface in Solidity

In this example we are going to create:

  • A contract that contains functions that return data
  • A second contract with an interfaces to the first contract
  • The second contract will access all the functions in the first contract using the interface

First, copy and deploy the contract below in Remix. This contract called dataContract contains several functions that return sample data.

pragma solidity ^0.8.6;

contract dataContract {
    
  function getAge() external pure returns(uint) {
    return 25;
  }
  
  function getHeight() external pure returns(uint) {
    return 6;
  }
  
  function getName() external pure returns(string memory) {
    return 'Bob';
  }

  function getCar() external pure returns(string memory) {
    return 'truck';
  }
}

Try it in Remix

Next copy and deploy the contract below in Remix. This contract contains an interface to the contract above. Paste the contract address above into the state variable into the contract below.

pragma solidity ^0.8.6;

//defined interface with functions that do not contain an implementation
//declared as type external

interface IDataContractInterface {
  function getAge() external pure returns(uint);
  function getHeight() external pure returns(uint);
  function getName() external pure returns(string memory);
  function getCar() external pure returns(string memory);
}


contract MainContract {
    
    // state variable called DataContractAddress that represents the address of the data contract
    
    address private constant DataContractAddress = PASTEFIRSTCONTRACTADDRESSHERE;
    
    
    // to access the functions in the data contract
    // use the interface declared above and wrap the data contract address in ()
    // example interfaceName(address).functionName
   
    

    function getAge() external pure returns(uint) {
        return IDataContractInterface(DataContractAddress).getAge();
  }
  
    function getHeight() external pure returns(uint) {
        return IDataContractInterface(DataContractAddress).getHeight();
  }
  
    function getName() external pure returns(string memory) {
        return IDataContractInterface(DataContractAddress).getName();
  } 
  
    function getCar() external pure returns(string memory) {
        return IDataContractInterface(DataContractAddress).getCar();
  }
}

Try it in Remix

Finally, after you deploy the contract above execute each of the functions. The functions use the interface to communicate with the first contract to obtain the data values.

What is the difference between an interface and a abstract contract?

Interfaces and abstract contracts are similar in many way. Interfaces tend to be more abstract than abstract contracts. All interface functions lack an implementation and in abstract contracts at least one function lacks an implementation. As a result you can not compile an interface or an abstract contract due to the missing implementation.

Abstract Contracts:

  • Help to instill coding patterns in your application
  • Define and self-document the structure of your application
  • Other contract types can inherit from abstract contracts
  • Conversely, in a smart contract interfaces are used as representations

What is the difference between an interface and a library?

Interfaces and libraries are similar in that they provide abstraction for upgradability which can be reviewed in multiple ways to upgrade a Solidity smart contract. However they are different and solve different use cases.

Interfaces:

  • Can not contain logic just the interface definition
  • Mainly useful as imports to interact with other contracts
  • Interfaces are smaller to deploy/import

Libraries:

  • Contain logic
  • Extract code away from the contract for maintainability and reuse purposes
  • Deployed once and then referenced in contracts
  • Bytecode is deployed separately and is not part of the contracts that references them

Resources

Blockchain Networks

Below is a list of EVM compatible Mainnet and Testnet blockchain networks. Each link contains network configuration, links to multiple faucets for test ETH and tokens, bridge details, and technical resources for each blockchain. Basically everything you need to test and deploy smart contracts or decentralized applications on each chain. For a list of popular Ethereum forums and chat applications click here.

Ethereum test network configuration and test ETH faucet information
Optimistic Ethereum Mainnet and Testnet configuration, bridge details, etc.
Polygon network Mainnet and Testnet configuration, faucets for test MATIC tokens, bridge details, etc.
Binance Smart Chain Mainnet and Testnet configuration, faucets for test BNB tokens, bridge details, etc.
Fanton networt Mainnet and Testnet configuration, faucets for test FTM tokens, bridge details, etc.
Kucoin Chain Mainnet and Testnet configuration, faucets for test KCS tokens, bridge details, etc.

Web3 Software Libraries

You can use the following libraries to interact with an EVM compatible blockchain.

Nodes

Learn how to run a Geth node. Read getting started with Geth to run an Ethereum node.

Fix a transaction

How to fix a pending transaction stuck on Ethereum or EVM compatible chain

Next Review – New keyword in Solidity smart contracts

Leave a Reply