ERC-165
ERC165¶
ERC165 is a standard on Ethereum and compatible EVM blockchains used to detect whether a smart contract implements certain interfaces (or functions). It defines a standard method to query whether a contract implements a specific interface, thereby improving contract interoperability and extensibility.
ERC165 defines a standard function supportsInterface, allowing smart contracts to declare the interfaces they support. Other contracts or applications can call this function to check if a contract supports a specific interface.
ERC165 Interface¶
pragma solidity ^0.8.0;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
- supportsInterface: Accepts an interface identifier (
interfaceId) and returns a boolean indicating whether the contract implements that interface.
Example Implementation¶
Below is a simple ERC165 contract implementation example:
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
contract ERC165Example is IERC165 {
// Mapping of interface id to whether or not it's supported.
mapping(bytes4 => bool) private _supportedInterfaces;
constructor() {
// Register the support of the ERC165 interface
_registerInterface(type(IERC165).interfaceId);
}
// Implementation of the supportsInterface method as per the ERC165 standard.
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
// Internal method for registering interface support
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
In this example, we implement the supportsInterface function and use an internal function _registerInterface to register supported interfaces.
Usage Example¶
Suppose a contract implements the ERC165 interface. Other contracts can call supportsInterface to check if it supports a specific interface.
pragma solidity ^0.8.0;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
contract InterfaceChecker {
function checkInterface(address contractAddress, bytes4 interfaceId) external view returns (bool) {
IERC165 erc165 = IERC165(contractAddress);
return erc165.supportsInterface(interfaceId);
}
}
In this example, the InterfaceChecker contract contains a checkInterface function used to check whether a given contract address supports a specific interface.
Summary¶
The ERC165 standard, by defining a standard interface detection mechanism, enables smart contracts to declare which interfaces they implement and allows other contracts and applications to easily query this information. This improves contract interoperability and extensibility, making it an important tool for building complex and composable smart contract systems.