Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 47 ยท Object-Oriented Solidity

Interfaces and Libraries

Learn Solidity interfaces and libraries: calling other contracts through an interface, internal vs external libraries, using for, and a duck-typed JS stand-in.

Contracts on Ethereum constantly talk to each other: a lending app calls a token, a marketplace calls an NFT, a wallet calls whatever you tell it to. To make such a call you do not need the other contract's source code, only a description of the functions you want to call. That description is an interface. And when many contracts need the same helper logic, such as math or a data structure, you put it in a library so that it is written once and reused.

This lesson covers both: how to declare and use interfaces, how to call another contract through one, how libraries differ from contracts, the two kinds of library functions, and the using ... for ... syntax.

Interface or library?

Interface A list of function signatures. No code, no state.
Library Reusable code with no state of its own.
Call by interface Talk to any contract that matches the list.
using for Make library functions read like methods.
1 / 2

Interfaces

An interface lists functions without bodies. It is a promise: "a contract that implements these can be used like this".

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface IGreeter {
    event Greeted(address indexed who);
    error TooLong(uint256 length);

    function greet(string calldata name) external returns (string memory);
    function count() external view returns (uint256);
}

The rules for an interface are strict:

  • Every function is external (and implicitly virtual), with no body.
  • No state variables, no constructor, no function bodies.
  • It may declare events, errors, structs and enums.
  • It can inherit from other interfaces.

A contract implements an interface with is, and must define every function. Since Solidity 0.8.8 the override keyword is not required for functions that implement an interface (it is still needed when overriding a base contract's function):

SOLIDITY
contract Greeter is IGreeter {
    uint256 public count;      // a public state variable can implement an external view function

    function greet(string calldata name) external returns (string memory) {
        count += 1;
        emit Greeted(msg.sender);
        return string.concat("Hello, ", name);
    }
}

The public state variable count generates a getter that satisfies count() external view returns (uint256). Interfaces are how standards such as ERC-20 are written: the standard is the interface, and every token contract promises to follow it. See Building an ERC-20 Token.

Calling another contract through an interface

To call a contract you know only by address, wrap the address in the interface type:

SOLIDITY
contract Visitor {
    function sayHello(address greeter) external returns (string memory) {
        return IGreeter(greeter).greet("Ada");
    }

    function visits(address greeter) external view returns (uint256) {
        return IGreeter(greeter).count();
    }
}

IGreeter(greeter) does not check anything about the address by itself; it just tells the compiler how to encode the call. The compiler produces an ABI-encoded external call (see ABI Encoding and Low-Level Calls). A few points to remember:

  • The call is a real message to another contract, so it costs gas and hands control to that code. A malicious or buggy callee can call back into you, which is the entry point of the reentrancy attacks in Reentrancy Step by Step.
  • If the callee reverts, the revert bubbles up and undoes your transaction too, unless you use try/catch (covered in Control Flow, require, revert and Custom Errors).
  • Before a high-level call, the compiler checks that the address has code. Calling an address that holds no contract reverts, instead of silently doing nothing.
  • If the address points to a contract that does not really implement the function, the call fails or behaves in unexpected ways. The interface is a convenience, not a guarantee. Standards such as ERC-165 let contracts announce which interfaces they support.

type(IGreeter).interfaceId gives a four-byte identifier built from the function selectors, which is what ERC-165 uses (ERC-1155, ERC-4626 and Friends).

Libraries

A library is like a contract with several restrictions: it has no state variables of its own, cannot inherit or be inherited, and cannot receive ether. In return it gives you reusable functions.

SOLIDITY
library MathLib {
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }

    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        return (a & b) + ((a ^ b) >> 1);   // no overflow even near the maximum
    }
}

contract Pricing {
    function best(uint256 a, uint256 b) external pure returns (uint256) {
        return MathLib.max(a, b);
    }
}

Internal versus external library functions

  • Internal library functions are compiled into the calling contract, like ordinary helper functions. No separate deployment, and no extra call cost beyond a jump. This is by far the most common kind.
  • Public or external library functions live in a separately deployed library contract. The calling contract links to its address and calls it with delegatecall, which runs the library code against the caller's storage and with the caller's msg.sender. This saves bytecode size when a library is large and used by many contracts, but it needs a deployment and linking step.

Internal functions can take reference types in storage, which lets a library work directly on a data structure that belongs to the caller:

SOLIDITY
library Set {
    struct Data { uint256[] items; mapping(uint256 => bool) seen; }

    function add(Data storage self, uint256 v) internal returns (bool) {
        if (self.seen[v]) return false;
        self.seen[v] = true;
        self.items.push(v);
        return true;
    }
}

using ... for ...

The directive using Set for Set.Data; attaches the library's functions to a type, so the first argument becomes the thing before the dot:

SOLIDITY
contract Club {
    using Set for Set.Data;
    Set.Data private members;

    function join(uint256 id) external returns (bool) {
        return members.add(id);        // same as Set.add(members, id)
    }
}

You can also attach individual functions, using {max, average} for uint256;, and since Solidity 0.8.13 a using ... for ... global; at file level makes the attachment available everywhere for a user-defined type. OpenZeppelin uses this style heavily, for example using SafeERC20 for IERC20;, which is why you see token.safeTransfer(...) in real code (Using OpenZeppelin).

Before Solidity 0.8, a library called SafeMath was needed to stop integer overflow. Since 0.8 the compiler checks arithmetic itself (Integers, Overflow and Checked Math), so you will see SafeMath only in older code.

An external library with delegatecall runs in your storage, so a library that is not what you think it is can overwrite your state. Link only to libraries you deployed and trust. Libraries also cannot be paused or owned: they hold no state.

Duck typing as a stand-in for interfaces

JavaScript has no interface keyword, but you can imitate one. The stand-in below describes an interface as a list of function names, checks that an object offers them, and returns a restricted view of the object, so that only interface functions can be called. This mirrors what IGreeter(addr) does, except that Solidity checks signatures at compile time and the EVM only discovers a missing function at run time. The stand-in is not the EVM; it just shows the idea.

JS An interface as a restricted view

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The view hides secretReset, just as an interface type exposes only the declared functions (the real contract may have more, and anyone can still call them directly). The wrong cast fails when the call is made, not when it is written.

Now a library stand-in. A library is a bag of functions with no state; using Set for Data becomes a small helper that binds the first argument. The data structure belongs to the caller, as with a storage parameter.

JS A library and using-for binding

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: interfaces have only external signatures, libraries have no state and work on the caller's data, and using for makes the first parameter the receiver. Stand-in: the interface check here happens at run time in JavaScript, while Solidity checks it when compiling, and the bound helper does not model delegatecall, linking or gas.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these can an interface contain?

    Interfaces declare external functions without bodies, and may declare events, errors, structs and enums. They cannot have state variables, constructors or implementations.
  2. 2. What does IERC20(token).transfer(to, 5) do if token is an address that holds no code?

    Solidity adds a code-existence check to high-level external calls, so calling an empty address reverts instead of appearing to succeed.
  3. 3. How does an internal library function differ from a public one?

    Internal functions become part of the caller's bytecode. Public and external ones are deployed separately, linked, and run through delegatecall in the caller's context.
  4. 4. What does using Set for Set.Data; allow you to write?

    using-for attaches the library's functions to a type, so the value before the dot becomes the first argument.

Summary

  • An interface is a list of external function signatures (plus events, errors and types) with no bodies, state or constructor; implementing contracts promise to follow it.
  • IFoo(addr).bar() makes a real external call: it costs gas, passes control to the callee, bubbles up reverts and reverts if the address has no code.
  • A library has no state of its own, cannot be inherited and cannot receive ether.
  • Internal library functions are compiled into the caller; public and external ones are deployed separately and reached with delegatecall.
  • using Lib for Type; lets library functions read like methods, and a storage parameter lets a library change the caller's data.
  • Solidity 0.8 checks arithmetic itself, so SafeMath is legacy.

Next: ABI Encoding and Low-Level Calls.