Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

ERC-165 defines a standard mechanism through which smart contracts can declare the interfaces they implement and other applications can query that support.

This article translates, summarizes, and expands on the following specification.

Overview

ERC-165 standardizes four operations:

  • Identifying an interface.
  • Advertising the interfaces a contract implements.
  • Detecting whether a contract implements ERC-165 itself.
  • Querying whether a contract implements a particular interface.

Motivation

When interacting with standard interfaces such as ERC-20 or ERC-721, applications benefit from knowing whether a contract supports the expected interface and, where applicable, which interface version it supports.

Earlier proposals also considered version identifiers for ERC-20. ERC-165 establishes a common convention for identifying interfaces and discovering contract support.

Not every token standard requires ERC-165. For example, ordinary ERC-20 compatibility does not imply ERC-165 support.

An identifier is a value, name, or symbol used to distinguish one entity from another.

Specification

Identifying an interface

ERC-165 identifies an interface using function selectors defined by the Ethereum ABI.

A function selector consists of the first four bytes of the Keccak-256 hash of a canonical function signature, including the function name and parameter types.

An ERC-165 interface is a set of function selectors. Unlike the broader Solidity interface concept, the identifier does not encode return types, state mutability, or events.

The interface identifier is the bitwise XOR of the selectors belonging to the interface.

The following historical Solidity example demonstrates the calculation.

javascript
pragma solidity ^0.4.20;

interface Solidity101 {
    function hello() external pure;
    function world(int) external pure;
}

contract Selector {
    function calculateSelector() public pure returns (bytes4) {
        Solidity101 i;
        return i.hello.selector ^ i.world.selector;
    }
}

Optional functions should not be included in the identifier of an interface that does not require them. Optional extensions can define their own interface identifiers.

Advertising supported interfaces

A contract implementing ERC-165 must expose the following interface.

javascript
pragma solidity ^0.4.20;

interface ERC165 {
    function supportsInterface(bytes4 interfaceID) external view returns (bool);
}

supportsInterface

The supportsInterface function accepts an interface identifier and returns true if the contract supports it, or false otherwise.

ERC-165 requires this function to consume less than 30,000 gas.

The ERC-165 interface identifier is 0x01ffc9a7. It can be calculated using bytes4(keccak256("supportsInterface(bytes4)")) or the corresponding function selector.

A compatible implementation must:

  • Return true for 0x01ffc9a7, the ERC-165 interface ID.
  • Return false for 0xffffffff, the reserved invalid identifier.
  • Return true for the other interfaces it implements.
  • Return false for unsupported interfaces.
  • Return an ABI-encoded Boolean within the required gas bound.

Additional requirements

Detecting ERC-165 support

  1. Execute a STATICCALL to the target address with a gas allowance of 30,000 and calldata 0x01ffc9a701ffc9a700000000000000000000000000000000000000000000000000000000. This represents supportsInterface(0x01ffc9a7).
  2. If the call fails or returns false, the target is not recognized as ERC-165-compatible.
  3. If it returns true, execute a second STATICCALL using calldata 0x01ffc9a7ffffffff00000000000000000000000000000000000000000000000000000000.
  4. If the second call fails or returns true, the target is not recognized as ERC-165-compatible.
  5. Otherwise, the target passes the ERC-165 detection procedure.

The second call rejects implementations that simply return true for every interface identifier.

A robust implementation must also validate the returned data rather than treating an empty or malformed response as a valid Boolean.

Detecting an arbitrary interface

  1. Determine whether the target supports ERC-165 using the procedure above, unless this has already been established.
  2. If it does not, use another application-appropriate mechanism to determine which functions are available.
  3. If it does, call supportsInterface with the desired interface identifier and examine its result.

Interface detection reports a contract's declared support. It is not a proof that every function behaves according to the corresponding specification.

Rationale

The specification aims to remain simple, using compact identifiers and a single standardized query function.

Backward compatibility

The original proposal was designed to work with the Solidity versions available at the time. The invalid-interface check helps distinguish ERC-165 implementations from some older contracts with permissive fallback behavior.

The original article also refers to the Ethereum Name Service specification:

Existing contracts that do not expose ERC-165 are not automatically made compatible by this standard.

Tests

The specification provides an example query contract that checks whether another contract implements a given interface.

javascript
pragma solidity ^0.4.20;

contract ERC165Query {
    bytes4 constant InvalidID = 0xffffffff;
    bytes4 constant ERC165ID = 0x01ffc9a7;

    function doesContractImplementInterface(address _contract, bytes4 _interfaceId) external view returns (bool) {
        uint256 success;
        uint256 result;

        (success, result) = noThrowCall(_contract, ERC165ID);
        if ((success==0)||(result==0)) {
            return false;
        }

        (success, result) = noThrowCall(_contract, InvalidID);
        if ((success==0)||(result!=0)) {
            return false;
        }

        (success, result) = noThrowCall(_contract, _interfaceId);
        if ((success==1)&&(result==1)) {
            return true;
        }
        return false;
    }

    function noThrowCall(address _contract, bytes4 _interfaceId) constant internal returns (uint256 success, uint256 result) {
        bytes4 erc165ID = ERC165ID;

        assembly {
                let x := mload(0x40)               // Find empty storage location using "free memory pointer"
                mstore(x, erc165ID)                // Place signature at beginning of empty storage
                mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature

                success := staticcall(
                                    30000,         // 30k gas
                                    _contract,     // To addr
                                    x,             // Inputs are stored at location x
                                    0x24,          // Inputs are 36 bytes long
                                    x,             // Store output over input (saves space)
                                    0x20)          // Outputs are 32 bytes long

                result := mload(x)                 // Load the result
        }
    }
}

doesContractImplementInterface

Checks whether the specified contract declares support for an interface.

  • _contract (address)
    • The target contract address.
  • _interfaceId (bytes4)
    • The identifier of the interface being checked.

The function returns a Boolean and uses noThrowCall to perform the underlying static calls.

STATICCALL invokes contract code in a static execution context. State-modifying operations are prohibited in that context and cause an exceptional failure if attempted.

https://medium.com/coinmonks/call-staticcall-and-delegatecall-1f0e1853340

The example follows three checks:

  1. Query ERC165ID and require a successful call returning a nonzero result.
  2. Query InvalidID and require a successful call returning zero. This confirms that the target rejects the reserved invalid interface ID.
  3. Query the requested interface ID and return true if the call succeeds and the returned value is one.

The historical example does not explicitly validate the returned data length. Modern integrations should use a robust checker that handles empty, malformed, and unexpectedly large return data.

noThrowCall

Uses inline assembly to construct calldata, execute STATICCALL, and retrieve the call-success flag and returned value.

Implementation

The following mapping-based implementation stores supported interface identifiers in contract storage.

The original specification reports a query cost of 586 gas for its historical implementation. Registering interfaces requires storage writes, historically described using a 20,000-gas SSTORE cost.

These figures are historical examples, not universal costs under subsequent EVM gas schedules.

javascript
pragma solidity ^0.4.20;

import "./ERC165.sol";

contract ERC165MappingImplementation is ERC165 {
    /// @dev You must not set element 0xffffffff to true
    mapping(bytes4 => bool) internal supportedInterfaces;

    function ERC165MappingImplementation() internal {
        supportedInterfaces[this.supportsInterface.selector] = true;
    }

    function supportsInterface(bytes4 interfaceID) external view returns (bool) {
        return supportedInterfaces[interfaceID];
    }
}

interface Simpson {
    function is2D() external returns (bool);
    function skinColor() external returns (string);
}

contract Lisa is ERC165MappingImplementation, Simpson {
    function Lisa() public {
        supportedInterfaces[this.is2D.selector ^ this.skinColor.selector] = true;
    }

    function is2D() external returns (bool){}
    function skinColor() external returns (string){}
}

ERC165MappingImplementation

supportedInterfaces

Maps each interface ID to a Boolean indicating whether the interface is supported.

ERC165MappingImplementation

The historical constructor registers the selector of supportsInterface in supportedInterfaces.

supportsInterface

Returns the stored support flag for a supplied interface identifier.

Lisa

The Lisa constructor registers the XOR of the is2D and skinColor function selectors, declaring support for the Simpson interface in addition to ERC-165.

Homer

The alternative implementation checks supported interface IDs directly rather than storing them in a mapping.

The original specification reports a best-case execution cost of 236 gas for this approach. The comparison cost increases as additional interface identifiers are checked.

javascript
pragma solidity ^0.4.20;

import "./ERC165.sol";

interface Simpson {
    function is2D() external returns (bool);
    function skinColor() external returns (string);
}

contract Homer is ERC165, Simpson {
    function supportsInterface(bytes4 interfaceID) external view returns (bool) {
        return
          interfaceID == this.supportsInterface.selector || // ERC165
          interfaceID == this.is2D.selector
                         ^ this.skinColor.selector; // Simpson
    }

    function is2D() external returns (bool){}
    function skinColor() external returns (string){}
}

The original comparison suggests that a mapping-based implementation can have a lower worst-case query cost when three or more interfaces are supported, including ERC-165 itself.

The actual trade-off depends on the compiler, optimizer, number of interfaces, and applicable gas schedule, including cold and warm storage access pricing.

The code excerpts use historical Solidity syntax and are preserved unchanged. They have not been independently compiled or benchmarked as part of this translation.

Conclusion

ERC-165 standardizes how smart contracts identify interfaces, declare their support, and expose that information to other contracts and applications.

The original article notes that additional implementation examples may be added later.

Questions are welcome via Twitter @cardene777.