0
0
Blockchain / Solidityprogramming~5 mins

Interfaces in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Interfaces help define a set of rules that different parts of a blockchain program must follow. They make sure everything works together smoothly.

When you want different smart contracts to share common functions.
When you want to ensure a contract follows a specific structure.
When you want to separate the definition of functions from their implementation.
When you want to allow multiple contracts to interact using the same rules.
When you want to make your code easier to understand and maintain.
Syntax
Blockchain / Solidity
interface InterfaceName {
    function functionName(parameters) external returns (returnType);
    // more function declarations
}

Interfaces only declare function signatures, no function bodies.

Functions in interfaces are always external and cannot have implementations.

Examples
This interface defines two functions for a token contract: transfer and balanceOf.
Blockchain / Solidity
interface IToken {
    function transfer(address to, uint amount) external returns (bool);
    function balanceOf(address owner) external view returns (uint);
}
This interface defines voting functions for a voting contract.
Blockchain / Solidity
interface IVoting {
    function vote(uint proposalId) external;
    function getVotes(uint proposalId) external view returns (uint);
}
Sample Program

This program defines an interface IGreeting with one function. The Greeter contract implements this interface by providing the function body. The Test contract creates a Greeter and calls sayHello through the interface.

Blockchain / Solidity
pragma solidity ^0.8.0;

interface IGreeting {
    function sayHello() external view returns (string memory);
}

contract Greeter is IGreeting {
    function sayHello() external pure override returns (string memory) {
        return "Hello, blockchain!";
    }
}

contract Test {
    function testGreeting() public view returns (string memory) {
        IGreeting greeter = new Greeter();
        return greeter.sayHello();
    }
}
OutputSuccess
Important Notes

Interfaces cannot have state variables or constructors.

Use interfaces to interact with other contracts safely without needing their full code.

Summary

Interfaces define function rules without code.

Contracts implement interfaces to follow those rules.

Interfaces help different contracts work together clearly.