TExcelTAD
Home › Solidity › Abstract Contracts & Interfaces

Abstract Contracts & Interfaces

Big systems are built from contracts that agree on how to talk to each other. Solidity has two tools for describing such agreements: abstract contracts, which may leave some functions unimplemented, and interfaces, which contain only function signatures.

Abstract contract Interface
Can be deployed no no
Implemented functions allowed not allowed
State variables allowed not allowed
Constructor allowed not allowed
Functions any visibility must be external
Can inherit contracts, interfaces only interfaces
Typical use shared base logic with "hooks" a standard, or a contract you call

Abstract contracts

Mark a contract abstract when at least one function has no body. Children must implement the missing pieces before they can be deployed. This is the template method pattern: the base defines the workflow, the child fills in the details.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

abstract contract PriceFeed {
    // implemented: shared logic
    function priceWithMargin(uint256 marginBps) public view returns (uint256) {
        uint256 p = latestPrice();
        return p + p * marginBps / 10_000;
    }

    // not implemented: each feed decides
    function latestPrice() public view virtual returns (uint256);
}

contract FixedFeed is PriceFeed {
    uint256 private immutable price;

    constructor(uint256 price_) {
        price = price_;
    }

    function latestPrice() public view override returns (uint256) {
        return price;
    }
}

contract Main {
    function main() external {
        FixedFeed feed = new FixedFeed(2000);
        console.log("price          :", feed.latestPrice());
        console.log("with 1.5% margin:", feed.priceWithMargin(150));
        // new PriceFeed();   // compile error: abstract contracts can't be deployed
    }
}
price          : 2000
with 1.5% margin: 2030

Interfaces

An interface lists external functions (and may declare events, errors, structs and enums) without any implementation. It's the Solidity equivalent of an API specification. Token standards are published as interfaces, for instance IERC20.

solidity
interface IERC20 {
    event Transfer(address indexed from, address indexed to, uint256 value);

    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 value) external returns (bool);
}

By convention interface names start with I.

Coding against an interface

The big win: your contract can call any contract that implements the interface, without knowing its code. You simply convert the address: ICounter(addr).increment().

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

interface IScore {
    function score(address player) external view returns (uint256);
}

contract ArcadeScores is IScore {
    function score(address) external pure override returns (uint256) {
        return 870;
    }
}

contract QuizScores is IScore {
    mapping(address => uint256) private points;

    function setPoints(address player, uint256 p) external {
        points[player] = p;
    }

    function score(address player) external view returns (uint256) {
        return points[player];
    }
}

contract Leaderboard {
    function best(IScore[] calldata games, address player) external view returns (uint256 top) {
        for (uint256 i = 0; i < games.length; i++) {
            uint256 s = games[i].score(player);
            if (s > top) top = s;
        }
    }
}

contract Main {
    function main() external {
        address player = address(0xA11CE);
        QuizScores quiz = new QuizScores();
        quiz.setPoints(player, 925);

        IScore[] memory games = new IScore[](2);
        games[0] = new ArcadeScores();
        games[1] = IScore(address(quiz));          // treat an address as an IScore

        Leaderboard board = new Leaderboard();
        console.log("best score:", board.best(games, player));
    }
}
best score: 925

Since Solidity 0.8.8, override is optional when implementing an interface function, which is why QuizScores.score compiles without it.

Warning: Calling through an interface trusts the target address. If the address points at a contract with a different (or malicious) implementation, your call will happily run its code. Only call addresses you have reason to trust, and treat every external call as a possible failure point.

Interface IDs (ERC-165)

type(I).interfaceId is the XOR of all the interface's function selectors. Contracts implementing ERC-165 expose supportsInterface(bytes4) so others can check which standards they support. NFT marketplaces use it to detect ERC-721 contracts.

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

interface IERC165 {
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

interface IGreeter {
    function greet() external view returns (string memory);
}

contract Greeter is IERC165, IGreeter {
    function greet() external pure returns (string memory) {
        return "hi";
    }

    function supportsInterface(bytes4 id) external pure returns (bool) {
        return id == type(IERC165).interfaceId || id == type(IGreeter).interfaceId;
    }
}

contract Main {
    function main() external {
        Greeter g = new Greeter();
        console.logBytes4(type(IGreeter).interfaceId);
        console.log("supports IGreeter?", g.supportsInterface(type(IGreeter).interfaceId));
        console.log("supports 0xffffffff?", g.supportsInterface(0xffffffff));
    }
}
0xcfae3217
supports IGreeter? true
supports 0xffffffff? false

The id of IGreeter is the selector of greet(), since it is the interface's only function.

Test yourself

Which of these is allowed in an interface?

  1. A state variable
  2. A constructor
  3. An external function without a body
  4. An implemented internal function

How do you call increment() on a contract at address a that implements ICounter?

  1. a.increment()
  2. ICounter(a).increment()
  3. new ICounter(a).increment()
  4. ICounter.increment(a)

Why can't you deploy an abstract contract?

  1. It has no constructor
  2. Some of its functions have no implementation
  3. It has no state
  4. Abstract contracts are deprecated