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.

This article examines ERC820, a standard proposing a mechanism to discover whether an address supports a particular interface and where that interface is implemented.

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

For other ERC articles, see the proposal index.

Overview

This standard defines a shared system for registering and discovering the functionality provided by smart contracts and accounts. To determine whether an address supports a particular interface and where it is implemented, query this registry.

Specifically, the standard defines a universal registry contract. Any address, whether a smart contract or an ordinary account, can register the interfaces it supports and the contracts responsible for implementing them.

For example, you can consult the registry to determine whether a smart contract supports a particular standard, such as ERC20 or ERC721. An interface identifier whose last 28 bytes are zero is recognized as an ERC165 interface, in which case the registry queries the relevant contract to determine whether it implements the specified interface.

For more information on ERC20, see the following article.

https://chaldene.net/erc20

For more information on ERC721, see the following article.

https://chaldene.net/erc721

The contract also reduces the gas cost of subsequent queries by caching ERC165 results. Once a result has been cached, it can be returned for the same query without repeating the computation.

For more information on ERC165, see the following article.

[ERC165] Checking Whether a Contract Supports an Interface

The registry can be deployed on different blockchains at the same address using the deployment approach described below. This allows the functionality of smart contracts and accounts to be discovered consistently across different chains.

Motivation

Several approaches to pseudo-introspection in Ethereum have been proposed, each with drawbacks. The first approach, ERC165, has a major limitation: it cannot be used directly with ordinary accounts. The subsequent proposal, ERC672, uses reverse resolution through ENS (Ethereum Name Service). However, it is overly complex, and ENS was controlled by a multisignature contract in the historical system discussed by the proposal, meaning it could theoretically be changed.

pseudo-introspection

Introspection is the process by which a program obtains information about its own structure or properties. Many high-level programming languages provide this feature, allowing a program to inspect the methods and attributes of an object at runtime.

Not all programming languages or environments support introspection, however. In particular, retrieving information about objects at runtime in systems such as smart contracts can introduce performance issues or security risks.

This is where pseudo-introspection comes in. Pseudo-introspection provides a mechanism for discovering the interfaces or functionality supported by an object or contract in environments where true introspection is unavailable. Ethereum smart contract standards such as ERC165 and ERC820 provide approaches to pseudo-introspection. They define mechanisms by which external callers can determine whether a contract supports a particular interface.

Rather than providing true introspection, pseudo-introspection allows a contract to declare its supported functionality and other contracts or accounts to query those declarations. This can improve interoperability and flexibility without sacrificing system performance.

The standard discussed here is substantially simpler than ERC672 and takes a decentralized approach. It also provides a common registry address across blockchains, eliminating the need to discover the correct registry address separately on each chain.

In other words, the standard simplifies and improves the efficiency of discovering the functionality of Ethereum contracts and accounts, while providing consistency across different chains. Developers can readily determine which contracts provide which interfaces without relying on a centralized system. This is expected to make the Ethereum ecosystem more transparent, decentralized, and accessible.

Specification

ERC820 registry smart contract

This is an exact copy of the code of the ERC820 registry smart contract.

This is an exact copy of the ERC820 registry smart contract code.

javascript
/* ERC820 Pseudo-introspection Registry Contract
 * This standard defines a universal registry smart contract where any address
 * (contract or regular account) can register which interface it supports and
 * which smart contract is responsible for its implementation.
 *
 * Written in 2018 by Jordi Baylina and Jacques Dafflon
 *
 * To the extent possible under law, the author(s) have dedicated all copyright
 * and related and neighboring rights to this software to the public domain
 * worldwide. This software is distributed without any warranty.
 *
 * You should have received a copy of the CC0 Public Domain Dedication along
 * with this software. If not, see
 * <https://creativecommons.org/publicdomain/zero/1.0/>.
 *
 *    ███████╗██████╗  ██████╗ █████╗ ██████╗  ██████╗
 *    ██╔════╝██╔══██╗██╔════╝██╔══██╗╚════██╗██╔═████╗
 *    █████╗  ██████╔╝██║     ╚█████╔╝ █████╔╝██║██╔██║
 *    ██╔══╝  ██╔══██╗██║     ██╔══██╗██╔═══╝ ████╔╝██║
 *    ███████╗██║  ██║╚██████╗╚█████╔╝███████╗╚██████╔╝
 *    ╚══════╝╚═╝  ╚═╝ ╚═════╝ ╚════╝ ╚══════╝ ╚═════╝
 *
 *    ██████╗ ███████╗ ██████╗ ██╗███████╗████████╗██████╗ ██╗   ██╗
 *    ██╔══██╗██╔════╝██╔════╝ ██║██╔════╝╚══██╔══╝██╔══██╗╚██╗ ██╔╝
 *    ██████╔╝█████╗  ██║  ███╗██║███████╗   ██║   ██████╔╝ ╚████╔╝
 *    ██╔══██╗██╔══╝  ██║   ██║██║╚════██║   ██║   ██╔══██╗  ╚██╔╝
 *    ██║  ██║███████╗╚██████╔╝██║███████║   ██║   ██║  ██║   ██║
 *    ╚═╝  ╚═╝╚══════╝ ╚═════╝ ╚═╝╚══════╝   ╚═╝   ╚═╝  ╚═╝   ╚═╝
 *
 */
pragma solidity 0.4.24;
// IV is value needed to have a vanity address starting with `0x820`.
// IV: 9513

/// @dev The interface a contract MUST implement if it is the implementer of
/// some (other) interface for any address other than itself.
interface ERC820ImplementerInterface {
    /// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `addr` or not.
    /// @param interfaceHash keccak256 hash of the name of the interface
    /// @param addr Address for which the contract will implement the interface
    /// @return ERC820_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `addr`.
    function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32);
}


/// @title ERC820 Pseudo-introspection Registry Contract
/// @author Jordi Baylina and Jacques Dafflon
/// @notice This contract is the official implementation of the ERC820 Registry.
/// @notice For more details, see https://eips.ethereum.org/EIPS/eip-820
contract ERC820Registry {
    /// @notice ERC165 Invalid ID.
    bytes4 constant INVALID_ID = 0xffffffff;
    /// @notice Method ID for the ERC165 supportsInterface method (= `bytes4(keccak256('supportsInterface(bytes4)'))`).
    bytes4 constant ERC165ID = 0x01ffc9a7;
    /// @notice Magic value which is returned if a contract implements an interface on behalf of some other address.
    bytes32 constant ERC820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC820_ACCEPT_MAGIC"));

    mapping (address => mapping(bytes32 => address)) interfaces;
    mapping (address => address) managers;
    mapping (address => mapping(bytes4 => bool)) erc165Cached;

    /// @notice Indicates a contract is the `implementer` of `interfaceHash` for `addr`.
    event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer);
    /// @notice Indicates `newManager` is the address of the new manager for `addr`.
    event ManagerChanged(address indexed addr, address indexed newManager);

    /// @notice Query if an address implements an interface and through which contract.
    /// @param _addr Address being queried for the implementer of an interface.
    /// (If `_addr == 0` then `msg.sender` is assumed.)
    /// @param _interfaceHash keccak256 hash of the name of the interface as a string.
    /// E.g., `web3.utils.keccak256('ERC777Token')`.
    /// @return The address of the contract which implements the interface `_interfaceHash` for `_addr`
    /// or `0x0` if `_addr` did not register an implementer for this interface.
    function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) {
        address addr = _addr == 0 ? msg.sender : _addr;
        if (isERC165Interface(_interfaceHash)) {
            bytes4 erc165InterfaceHash = bytes4(_interfaceHash);
            return implementsERC165Interface(addr, erc165InterfaceHash) ? addr : 0;
        }
        return interfaces[addr][_interfaceHash];
    }

    /// @notice Sets the contract which implements a specific interface for an address.
    /// Only the manager defined for that address can set it.
    /// (Each address is the manager for itself until it sets a new manager.)
    /// @param _addr Address to define the interface for. (If `_addr == 0` then `msg.sender` is assumed.)
    /// @param _interfaceHash keccak256 hash of the name of the interface as a string.
    /// For example, `web3.utils.keccak256('ERC777TokensRecipient')` for the `ERC777TokensRecipient` interface.
    /// @param _implementer Contract address implementing _interfaceHash for _addr.
    function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external {
        address addr = _addr == 0 ? msg.sender : _addr;
        require(getManager(addr) == msg.sender, "Not the manager");

        require(!isERC165Interface(_interfaceHash), "Must not be a ERC165 hash");
        if (_implementer != 0 && _implementer != msg.sender) {
            require(
                ERC820ImplementerInterface(_implementer)
                    .canImplementInterfaceForAddress(_interfaceHash, addr) == ERC820_ACCEPT_MAGIC,
                "Does not implement the interface"
            );
        }
        interfaces[addr][_interfaceHash] = _implementer;
        emit InterfaceImplementerSet(addr, _interfaceHash, _implementer);
    }

    /// @notice Sets the `_newManager` as manager for the `_addr` address.
    /// The new manager will be able to call `setInterfaceImplementer` for `_addr`.
    /// @param _addr Address for which to set the new manager.
    /// @param _newManager Address of the new manager for `addr`.
    function setManager(address _addr, address _newManager) external {
        require(getManager(_addr) == msg.sender, "Not the manager");
        managers[_addr] = _newManager == _addr ? 0 : _newManager;
        emit ManagerChanged(_addr, _newManager);
    }

    /// @notice Get the manager of an address.
    /// @param _addr Address for which to return the manager.
    /// @return Address of the manager for a given address.
    function getManager(address _addr) public view returns(address) {
        // By default the manager of an address is the same address
        if (managers[_addr] == 0) {
            return _addr;
        } else {
            return managers[_addr];
        }
    }

    /// @notice Compute the keccak256 hash of an interface given its name.
    /// @param _interfaceName Name of the interface.
    /// @return The keccak256 hash of an interface name.
    function interfaceHash(string _interfaceName) external pure returns(bytes32) {
        return keccak256(abi.encodePacked(_interfaceName));
    }

    /* --- ERC165 Related Functions --- */
    /* --- Developed in collaboration with William Entriken. --- */

    /// @notice Updates the cache with whether the contract implements an ERC165 interface or not.
    /// @param _contract Address of the contract for which to update the cache.
    /// @param _interfaceId ERC165 interface for which to update the cache.
    function updateERC165Cache(address _contract, bytes4 _interfaceId) external {
        interfaces[_contract][_interfaceId] = implementsERC165InterfaceNoCache(_contract, _interfaceId) ? _contract : 0;
        erc165Cached[_contract][_interfaceId] = true;
    }

    /// @notice Checks whether a contract implements an ERC165 interface or not.
    /// The result may be cached, if not a direct lookup is performed.
    /// @param _contract Address of the contract to check.
    /// @param _interfaceId ERC165 interface to check.
    /// @return `true` if `_contract` implements `_interfaceId`, false otherwise.
    function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) {
        if (!erc165Cached[_contract][_interfaceId]) {
            return implementsERC165InterfaceNoCache(_contract, _interfaceId);
        }
        return interfaces[_contract][_interfaceId] == _contract;
    }

    /// @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
    /// @param _contract Address of the contract to check.
    /// @param _interfaceId ERC165 interface to check.
    /// @return `true` if `_contract` implements `_interfaceId`, false otherwise.
    function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) {
        uint256 success;
        uint256 result;

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

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

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

    /// @notice Checks whether the hash is a ERC165 interface (ending with 28 zeroes) or not.
    /// @param _interfaceHash The hash to check.
    /// @return `true` if the hash is a ERC165 interface (ending with 28 zeroes), `false` otherwise.
    function isERC165Interface(bytes32 _interfaceHash) internal pure returns (bool) {
        return _interfaceHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0;
    }

    /// @dev Make a call on a contract without throwing if the function does not exist.
    function noThrowCall(address _contract, bytes4 _interfaceId)
        internal view 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
                    0x08,                          // Inputs are 8 bytes long
                    x,                             // Store output over input (saves space)
                    0x20                           // Outputs are 32 bytes long
                )

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

Variables

INVALID_ID

javascript
bytes4 constant INVALID_ID = 0xffffffff;

Overview

An invalid ERC165 interface ID.

Details

This constant identifies an invalid ERC165 interface identifier. ERC165 is a standard for detecting whether a contract supports a particular interface.


ERC165ID

javascript
bytes4 constant ERC165ID = 0x01ffc9a7;

Overview

The method ID of the ERC165 supportsInterface method.

Details

This constant is the ERC165 function selector used when checking whether a contract exposes the supportsInterface function. The function is used to determine whether the contract supports a particular interface.


ERC820_ACCEPT_MAGIC

javascript
bytes32 constant ERC820_ACCEPT_MAGIC = keccak256(abi.encodePacked("ERC820_ACCEPT_MAGIC"));

Overview

The value returned when a contract agrees to implement an interface on behalf of a particular address.

Details

This constant is used as a return value of the canImplementInterfaceForAddress function defined in ERC820. A contract implementing an interface on behalf of an address returns this special value to indicate its acceptance.


interfaces

javascript
mapping (address => mapping(bytes32 => address)) interfaces;

Overview

A mapping from addresses and interface hashes to implementers.

Details

This mapping tracks the interfaces supported by a particular address and the contracts through which those interfaces are implemented. The keys are the address and interface hash, and the value is the address of the contract implementing the interface.

Parameters

  • address
    • The address whose interface implementer is being queried.
  • bytes32
    • The interface hash.

managers

javascript
mapping (address => address) managers;

Overview

A mapping that tracks the manager of each address.

Details

Each address may have a manager responsible for managing its interface registrations. This mapping identifies the manager of a particular address.

Parameters

  • address
    • The address whose manager is being queried.

erc165Cached

javascript
mapping (address => mapping(bytes4 => bool)) erc165Cached;

Overview

A mapping that caches the results of ERC165 interface queries.

Details

This cache speeds up queries about whether a contract implements a particular ERC165 interface. It must be updated manually.

Parameters

  • address
    • The address of the contract whose interface support is being queried.
  • bytes4
    • The ERC165 interface ID.

InterfaceImplementerSet

javascript
event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer);

Overview

An event emitted when an interface implementer is set.

Details

This event is emitted when the implementer of a particular interface for an address is set or changed. It enables external observers to track which contract implements an interface.

Parameters

  • addr
    • The address for which an interface implementer was set.
  • interfaceHash
    • The interface hash.
  • implementer
    • The address of the contract implementing the interface.

ManagerChanged

javascript
event ManagerChanged(address indexed addr, address indexed newManager);

Overview

An event emitted when the manager of an address changes.

Details

This event is emitted when the manager of a particular address changes to a new address. It enables external observers to track manager changes.

Parameters

  • addr
    • The address whose manager changed.
  • newManager
    • The new manager's address.

Functions

getInterfaceImplementer

javascript
function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address)

Overview

Queries whether an address supports an interface and which contract implements it.

Details

If _addr is 0, msg.sender is used. If _interfaceHash identifies an ERC165 interface, the relevant contract is queried to determine whether it implements that interface. Otherwise, the address of the implementing contract is retrieved from the interfaces mapping.

Arguments

  • _addr
    • The address whose interface implementer is being queried.
  • _interfaceHash
    • The keccak256 hash of the interface name.

Return value

  • Address
    • The address of the contract implementing the interface specified by _interfaceHash.
    • 0x0 if no implementer is registered.

setInterfaceImplementer

javascript
function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external

Overview

Sets the contract that implements a particular interface for an address.

Details

If _addr is 0, msg.sender is used. Only the manager of the address can call this function. _interfaceHash must not identify an ERC165 interface, and _implementer must accept implementation of the specified interface as required by the registry.

Arguments

  • _addr
    • The address for which the interface is registered.
  • _interfaceHash
    • The keccak256 hash of the interface name.
  • _implementer
    • The address of the contract implementing _interfaceHash.

setManager

javascript
function setManager(address _addr, address _newManager) external

Overview

Sets a new manager for a particular address.

Details

Only the current manager can call this function. If _newManager is 0x0, the manager is reset to _addr itself.

Arguments

  • _addr
    • The address for which the new manager is being set.
  • _newManager
    • The address of the new manager.

getManager

javascript
function getManager(address _addr) public view returns(address)

Overview

Retrieves the manager of a particular address.

Details

By default, an address is its own manager. If no manager has been set, the address itself is returned.

Arguments

  • _addr
    • The address whose manager is being retrieved.

Return value

  • Address
    • The manager's address for the specified address.

interfaceHash

javascript
function interfaceHash(string _interfaceName) external pure returns(bytes32)

Overview

Computes the keccak256 hash of an interface name.

Details

This function returns the keccak256 hash of an interface name supplied as a string. The hash acts as an identifier for the interface.

Arguments

  • _interfaceName
    • The interface name.

Return value

  • bytes
    • The keccak256 hash of the interface name.

Deployment transaction

text
0xf90a2a8085174876e800830c35008080b909d7608060405234801561001057600080fd5b506109b7806100206000396000f30060806040526004361061008d5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166329965a1d81146100925780633d584063146100bf5780635df8122f146100fc57806365ba36c114610123578063a41e7d5114610155578063aabbb8ca14610183578063b7056765146101a7578063f712f3e8146101e9575b600080fd5b34801561009e57600080fd5b506100bd600160a060020a036004358116906024359060443516610217565b005b3480156100cb57600080fd5b506100e0600160a060020a0360043516610512565b60408051600160a060020a039092168252519081900360200190f35b34801561010857600080fd5b506100bd600160a060020a036004358116906024351661055e565b34801561012f57600080fd5b506101436004803560248101910135610655565b60408051918252519081900360200190f35b34801561016157600080fd5b506100bd600160a060020a0360043516600160e060020a0319602435166106e3565b34801561018f57600080fd5b506100e0600160a060020a036004351660243561076d565b3480156101b357600080fd5b506101d5600160a060020a0360043516600160e060020a0319602435166107e7565b604080519115158252519081900360200190f35b3480156101f557600080fd5b506101d5600160a060020a0360043516600160e060020a03196024351661089c565b6000600160a060020a0384161561022e5783610230565b335b90503361023c82610512565b600160a060020a03161461029a576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b6102a38361091c565b156102f8576040805160e560020a62461bcd02815260206004820152601960248201527f4d757374206e6f74206265206120455243313635206861736800000000000000604482015290519081900360640190fd5b600160a060020a038216158015906103195750600160a060020a0382163314155b156104a15760405160200180807f4552433832305f4143434550545f4d414749430000000000000000000000000081525060130190506040516020818303038152906040526040518082805190602001908083835b6020831061038d5780518252601f19909201916020918201910161036e565b51815160209384036101000a6000190180199092169116179052604080519290940182900382207f249cb3fa000000000000000000000000000000000000000000000000000000008352600483018a9052600160a060020a0388811660248501529451909650938816945063249cb3fa936044808401945091929091908290030181600087803b15801561042057600080fd5b505af1158015610434573d6000803e3d6000fd5b505050506040513d602081101561044a57600080fd5b5051146104a1576040805160e560020a62461bcd02815260206004820181905260248201527f446f6573206e6f7420696d706c656d656e742074686520696e74657266616365604482015290519081900360640190fd5b600160a060020a03818116600081815260208181526040808320888452909152808220805473ffffffffffffffffffffffffffffffffffffffff19169487169485179055518692917f93baa6efbd2244243bfee6ce4cfdd1d04fc4c0e9a786abd3a41313bd352db15391a450505050565b600160a060020a03808216600090815260016020526040812054909116151561053c575080610559565b50600160a060020a03808216600090815260016020526040902054165b919050565b3361056883610512565b600160a060020a0316146105c6576040805160e560020a62461bcd02815260206004820152600f60248201527f4e6f7420746865206d616e616765720000000000000000000000000000000000604482015290519081900360640190fd5b81600160a060020a031681600160a060020a0316146105e557806105e8565b60005b600160a060020a03838116600081815260016020526040808220805473ffffffffffffffffffffffffffffffffffffffff19169585169590951790945592519184169290917f605c2dbf762e5f7d60a546d42e7205dcb1b011ebc62a61736a57c9089d3a43509190a35050565b60008282604051602001808383808284378201915050925050506040516020818303038152906040526040518082805190602001908083835b602083106106ad5780518252601f19909201916020918201910161068e565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051809103902090505b92915050565b6106ed82826107e7565b6106f85760006106fa565b815b600160a060020a03928316600081815260208181526040808320600160e060020a031996909616808452958252808320805473ffffffffffffffffffffffffffffffffffffffff19169590971694909417909555908152600284528181209281529190925220805460ff19166001179055565b60008080600160a060020a038516156107865784610788565b335b91506107938461091c565b156107b85750826107a4828261089c565b6107af5760006107b1565b815b92506107df565b600160a060020a038083166000908152602081815260408083208884529091529020541692505b505092915050565b60008080610815857f01ffc9a70000000000000000000000000000000000000000000000000000000061093e565b9092509050811580610825575080155b1561083357600092506107df565b61084585600160e060020a031961093e565b909250905081158061085657508015155b1561086457600092506107df565b61086e858561093e565b90925090506001821480156108835750806001145b1561089157600192506107df565b506000949350505050565b600160a060020a0382166000908152600260209081526040808320600160e060020a03198516845290915281205460ff1615156108e4576108dd83836107e7565b90506106dd565b50600160a060020a03808316600081815260208181526040808320600160e060020a0319871684529091529020549091161492915050565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff161590565b6040517f01ffc9a7000000000000000000000000000000000000000000000000000000008082526004820183905260009182919060208160088189617530fa9051909690955093505050505600a165627a7a723058204fc4461c9d5a247b0eafe0f9c508057bc0ad72bc24668cb2a35ea65850e10d3100291ba08208208208208208208208208208208208208208208208208208208208208200a00820820820820820820820820820820820820820820820820820820820820820

The data above is used to deploy the smart contract implementing the ERC820 registry on a blockchain. This is the data used to deploy the contract on Ethereum or another compatible chain.

The number 820 at the end of the transaction data forms part of the signature. The signature is important for validating the transaction. The particular signature pattern is intended to demonstrate a keyless deployment, where the private key of the recovered sender is not known.

The data in this example constitutes the instructions for deploying a smart contract on a blockchain. The distinctive signature pattern is part of the intended trust-minimizing deployment approach. The aim is to deploy the expected contract without allowing unintended transactions from the deployment account.

Deployment method

Keyless deployment, also known as Nick's method, is a particular technique for deploying smart contracts on a blockchain. The method deploys a contract from a one-time account (a temporary address). It proceeds as follows.

1. Generating a deployment transaction

First, construct a transaction that deploys the contract from a new, effectively random account. The transaction does not use EIP155, so it can be broadcast on compatible chains without a chain-specific signature.

For more information on ERC155, see the following article.

[EIP155] Preventing Replay Attacks Across Ethereum Networks

2. Setting the gas price

The transaction uses a relatively high gas price (100 Gwei in this example) to facilitate deployment on different chains.

3. Setting the signature

Set the transaction signature values v, r, and s to specific numbers. The r and s values contain a predictable repeating pattern, '820'. They serve as deliberately constructed, apparently random numerical values.

text
v: 27
r: 0x8208208208208208208208208208208208208208208208208208208208208200
s: 0x0820820820820820820820820820820820820820820820820820820820820820

The values of r and s must be 32 bytes long each—or 64 characters in hexadecimal. Since 820 is 3 characters long and 3 is not a divisor of 64, but it is a divisor of 63, the r and s values are padded with one extra character. The s value is prefixed with a single zero (0). The 0 prefix also guarantees that s < secp256k1n ÷ 2 + 1. The r value, cannot be prefixed with a zero, as the transaction becomes invalid. Instead it is suffixed with a zero (0) which still respects the condition s < secp256k1n.

Each r and s value must be 32 bytes long, or 64 hexadecimal characters. '820' contains three characters. Three divides 63, not 64, so the r and s values require one additional padding character. The s value has a single leading zero (0). This prefix also helps satisfy the condition s < secp256k1n ÷ 2 + 1. The r value cannot be prefixed with a zero because that would make the transaction invalid in this encoding. Instead, a trailing zero (0) is used; the condition stated in the original explanation is s < secp256k1n.

4. Adjusting the lengths

The r and s values are adjusted to 32 bytes each and filled with the '820' pattern. One additional padding character is added to satisfy the 64-character requirement.

5. Prefix and suffix

Prefix s with 0 and suffix r with 0. This is intended to satisfy the required cryptographic and encoding conditions and produce a valid transaction.

The process determines the transaction sender, which is the one-time deployment account. The transaction can be broadcast from this account without anyone knowing its private key.

Thus we obtain an account that can broadcast that transaction, but we also have the warranty that nobody knows the private key of that account.

This gives us an account from which the transaction can be broadcast, while providing assurance that nobody knows that account's private key.

Next, send 0.08 ETH to this one-time account.

Finally, broadcast the deployment transaction on the relevant chains. With this approach, the contract has the same address on each compatible chain, and the deployment address is intended not to be used for a different contract.

One-time registry deployment account

text
0xE6C244a1C10Aa0085b0cf92f04cdaD947C2988b8

This address is a special account intended to be used only once, to deploy the smart contract. The account is recovered from the signature data. Its private key is not known, but the deployment transaction can be validated against the recovered sender.

To deploy the contract using this special account, first transfer 0.08 ETH to it. The transfer supplies sufficient funds for the account to pay for the contract deployment transaction under the stated gas assumptions. The contract is then deployed on the blockchain through the one-time account.

To deploy the registry, 0.08 ethers MUST be sent to this account first.

To deploy the registry, first send 0.08 ETH to this account.

Registry contract address

text
0x820b586C8C28125366C998641B09DCbE7d4cBF06

The registry contract has the address shown above on every chain on which it is deployed using the specified transaction.

ERC820Registry contract metadata
json
{ "compiler": { "version": "0.4.24+commit.e67f0147" }, "language": "Solidity", "output": { "abi": [ { "constant": false, "inputs": [ { "name": "_addr", "type": "address" }, { "name": "_interfaceHash", "type": "bytes32" }, { "name": "_implementer", "type": "address" } ], "name": "setInterfaceImplementer", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "_addr", "type": "address" } ], "name": "getManager", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_addr", "type": "address" }, { "name": "_newManager", "type": "address" } ], "name": "setManager", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "_interfaceName", "type": "string" } ], "name": "interfaceHash", "outputs": [ { "name": "", "type": "bytes32" } ], "payable": false, "stateMutability": "pure", "type": "function" }, { "constant": false, "inputs": [ { "name": "_contract", "type": "address" }, { "name": "_interfaceId", "type": "bytes4" } ], "name": "updateERC165Cache", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "_addr", "type": "address" }, { "name": "_interfaceHash", "type": "bytes32" } ], "name": "getInterfaceImplementer", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "_contract", "type": "address" }, { "name": "_interfaceId", "type": "bytes4" } ], "name": "implementsERC165InterfaceNoCache", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "_contract", "type": "address" }, { "name": "_interfaceId", "type": "bytes4" } ], "name": "implementsERC165Interface", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "addr", "type": "address" }, { "indexed": true, "name": "interfaceHash", "type": "bytes32" }, { "indexed": true, "name": "implementer", "type": "address" } ], "name": "InterfaceImplementerSet", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "addr", "type": "address" }, { "indexed": true, "name": "newManager", "type": "address" } ], "name": "ManagerChanged", "type": "event" } ], "devdoc": { "author": "Jordi Baylina and Jacques Dafflon", "methods": { "getInterfaceImplementer(address,bytes32)": { "params": { "_addr": "Address being queried for the implementer of an interface. (If `_addr == 0` then `msg.sender` is assumed.)", "_interfaceHash": "keccak256 hash of the name of the interface as a string. E.g., `web3.utils.keccak256('ERC777Token')`." }, "return": "The address of the contract which implements the interface `_interfaceHash` for `_addr` or `0x0` if `_addr` did not register an implementer for this interface." }, "getManager(address)": { "params": { "_addr": "Address for which to return the manager." }, "return": "Address of the manager for a given address." }, "implementsERC165Interface(address,bytes4)": { "params": { "_contract": "Address of the contract to check.", "_interfaceId": "ERC165 interface to check." }, "return": "`true` if `_contract` implements `_interfaceId`, false otherwise." }, "implementsERC165InterfaceNoCache(address,bytes4)": { "params": { "_contract": "Address of the contract to check.", "_interfaceId": "ERC165 interface to check." }, "return": "`true` if `_contract` implements `_interfaceId`, false otherwise." }, "interfaceHash(string)": { "params": { "_interfaceName": "Name of the interface." }, "return": "The keccak256 hash of an interface name." }, "setInterfaceImplementer(address,bytes32,address)": { "params": { "_addr": "Address to define the interface for. (If `_addr == 0` then `msg.sender` is assumed.)", "_implementer": "Contract address implementing _interfaceHash for _addr.", "_interfaceHash": "keccak256 hash of the name of the interface as a string. For example, `web3.utils.keccak256('ERC777TokensRecipient')` for the `ERC777TokensRecipient` interface." } }, "setManager(address,address)": { "params": { "_addr": "Address for which to set the new manager.", "_newManager": "Address of the new manager for `addr`." } }, "updateERC165Cache(address,bytes4)": { "params": { "_contract": "Address of the contract for which to update the cache.", "_interfaceId": "ERC165 interface for which to update the cache." } } }, "title": "ERC820 Pseudo-introspection Registry Contract" }, "userdoc": { "methods": { "getInterfaceImplementer(address,bytes32)": { "notice": "Query if an address implements an interface and through which contract." }, "getManager(address)": { "notice": "Get the manager of an address." }, "implementsERC165Interface(address,bytes4)": { "notice": "Checks whether a contract implements an ERC165 interface or not. The result may be cached, if not a direct lookup is performed." }, "implementsERC165InterfaceNoCache(address,bytes4)": { "notice": "Checks whether a contract implements an ERC165 interface or not without using nor updating the cache." }, "interfaceHash(string)": { "notice": "Compute the keccak256 hash of an interface given its name." }, "setInterfaceImplementer(address,bytes32,address)": { "notice": "Sets the contract which implements a specific interface for an address. Only the manager defined for that address can set it. (Each address is the manager for itself until it sets a new manager.)" }, "setManager(address,address)": { "notice": "Sets the `_newManager` as manager for the `_addr` address. The new manager will be able to call `setInterfaceImplementer` for `_addr`." }, "updateERC165Cache(address,bytes4)": { "notice": "Updates the cache with whether the contract implements an ERC165 interface or not." } } } }, "settings": { "compilationTarget": { "./contracts/ERC820Registry.sol": "ERC820Registry" }, "evmVersion": "byzantium", "libraries": {}, "optimizer": { "enabled": true, "runs": 200 }, "remappings": [] }, "sources": { "./contracts/ERC820Registry.sol": { "content": "/* ERC820 Pseudo-introspection Registry Contract\n * This standard defines a universal registry smart contract where any address\n * (contract or regular account) can register which interface it supports and\n * which smart contract is responsible for its implementation.\n *\n * Written in 2018 by Jordi Baylina and Jacques Dafflon\n *\n * To the extent possible under law, the author(s) have dedicated all copyright\n * and related and neighboring rights to this software to the public domain\n * worldwide. This software is distributed without any warranty.\n *\n * You should have received a copy of the CC0 Public Domain Dedication along\n * with this software. If not, see\n * <https://creativecommons.org/publicdomain/zero/1.0/>.\n *\n * ███████╗██████╗ ██████╗ █████╗ ██████╗ ██████╗\n * ██╔════╝██╔══██╗██╔════╝██╔══██╗╚════██╗██╔═████╗\n * █████╗ ██████╔╝██║ ╚█████╔╝ █████╔╝██║██╔██║\n * ██╔══╝ ██╔══██╗██║ ██╔══██╗██╔═══╝ ████╔╝██║\n * ███████╗██║ ██║╚██████╗╚█████╔╝███████╗╚██████╔╝\n * ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚════╝ ╚══════╝ ╚═════╝\n *\n * ██████╗ ███████╗ ██████╗ ██╗███████╗████████╗██████╗ ██╗ ██╗\n * ██╔══██╗██╔════╝██╔════╝ ██║██╔════╝╚══██╔══╝██╔══██╗╚██╗ ██╔╝\n * ██████╔╝█████╗ ██║ ███╗██║███████╗ ██║ ██████╔╝ ╚████╔╝\n * ██╔══██╗██╔══╝ ██║ ██║██║╚════██║ ██║ ██╔══██╗ ╚██╔╝\n * ██║ ██║███████╗╚██████╔╝██║███████║ ██║ ██║ ██║ ██║\n * ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝\n *\n */\npragma solidity 0.4.24;\n// IV is value needed to have a vanity address starting with `0x820`.\n// IV: 9513\n\n/// @dev The interface a contract MUST implement if it is the implementer of\n/// some (other) interface for any address other than itself.\ninterface ERC820ImplementerInterface {\n /// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `addr` or not.\n /// @param interfaceHash keccak256 hash of the name of the interface\n /// @param addr Address for which the contract will implement the interface\n /// @return ERC820_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `addr`.\n function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32);\n}\n\n\n/// @title ERC820 Pseudo-introspection Registry Contract\n/// @author Jordi Baylina and Jacques Dafflon\n/// @notice This contract is the official implementation of the ERC820 Registry.\n/// @notice For more details, see https://eips.ethereum.org/EIPS/eip-820\ncontract ERC820Registry {\n /// @notice ERC165 Invalid ID.\n bytes4 constant INVALID_ID = 0xffffffff;\n /// @notice Method ID for the ERC165 supportsInterface method (= `bytes4(keccak256('supportsInterface(bytes4)'))`).\n bytes4 constant ERC165ID = 0x01ffc9a7;\n /// @notice Magic value which is returned if a contract implements an interface on behalf of some other address.\n bytes32 constant ERC820_ACCEPT_MAGIC = keccak256(abi.encodePacked(\"ERC820_ACCEPT_MAGIC\"));\n\n mapping (address => mapping(bytes32 => address)) interfaces;\n mapping (address => address) managers;\n mapping (address => mapping(bytes4 => bool)) erc165Cached;\n\n /// @notice Indicates a contract is the `implementer` of `interfaceHash` for `addr`.\n event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer);\n /// @notice Indicates `newManager` is the address of the new manager for `addr`.\n event ManagerChanged(address indexed addr, address indexed newManager);\n\n /// @notice Query if an address implements an interface and through which contract.\n /// @param _addr Address being queried for the implementer of an interface.\n /// (If `_addr == 0` then `msg.sender` is assumed.)\n /// @param _interfaceHash keccak256 hash of the name of the interface as a string.\n /// E.g., `web3.utils.keccak256('ERC777Token')`.\n /// @return The address of the contract which implements the interface `_interfaceHash` for `_addr`\n /// or `0x0` if `_addr` did not register an implementer for this interface.\n function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) {\n address addr = _addr == 0 ? msg.sender : _addr;\n if (isERC165Interface(_interfaceHash)) {\n bytes4 erc165InterfaceHash = bytes4(_interfaceHash);\n return implementsERC165Interface(addr, erc165InterfaceHash) ? addr : 0;\n }\n return interfaces[addr][_interfaceHash];\n }\n\n /// @notice Sets the contract which implements a specific interface for an address.\n /// Only the manager defined for that address can set it.\n /// (Each address is the manager for itself until it sets a new manager.)\n /// @param _addr Address to define the interface for. (If `_addr == 0` then `msg.sender` is assumed.)\n /// @param _interfaceHash keccak256 hash of the name of the interface as a string.\n /// For example, `web3.utils.keccak256('ERC777TokensRecipient')` for the `ERC777TokensRecipient` interface.\n /// @param _implementer Contract address implementing _interfaceHash for _addr.\n function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external {\n address addr = _addr == 0 ? msg.sender : _addr;\n require(getManager(addr) == msg.sender, \"Not the manager\");\n\n require(!isERC165Interface(_interfaceHash), \"Must not be a ERC165 hash\");\n if (_implementer != 0 && _implementer != msg.sender) {\n require(\n ERC820ImplementerInterface(_implementer)\n .canImplementInterfaceForAddress(_interfaceHash, addr) == ERC820_ACCEPT_MAGIC,\n \"Does not implement the interface\"\n );\n }\n interfaces[addr][_interfaceHash] = _implementer;\n emit InterfaceImplementerSet(addr, _interfaceHash, _implementer);\n }\n\n /// @notice Sets the `_newManager` as manager for the `_addr` address.\n /// The new manager will be able to call `setInterfaceImplementer` for `_addr`.\n /// @param _addr Address for which to set the new manager.\n /// @param _newManager Address of the new manager for `addr`.\n function setManager(address _addr, address _newManager) external {\n require(getManager(_addr) == msg.sender, \"Not the manager\");\n managers[_addr] = _newManager == _addr ? 0 : _newManager;\n emit ManagerChanged(_addr, _newManager);\n }\n\n /// @notice Get the manager of an address.\n /// @param _addr Address for which to return the manager.\n /// @return Address of the manager for a given address.\n function getManager(address _addr) public view returns(address) {\n // By default the manager of an address is the same address\n if (managers[_addr] == 0) {\n return _addr;\n } else {\n return managers[_addr];\n }\n }\n\n /// @notice Compute the keccak256 hash of an interface given its name.\n /// @param _interfaceName Name of the interface.\n /// @return The keccak256 hash of an interface name.\n function interfaceHash(string _interfaceName) external pure returns(bytes32) {\n return keccak256(abi.encodePacked(_interfaceName));\n }\n\n /* --- ERC165 Related Functions --- */\n /* --- Developed in collaboration with William Entriken. --- */\n\n /// @notice Updates the cache with whether the contract implements an ERC165 interface or not.\n /// @param _contract Address of the contract for which to update the cache.\n /// @param _interfaceId ERC165 interface for which to update the cache.\n function updateERC165Cache(address _contract, bytes4 _interfaceId) external {\n interfaces[_contract][_interfaceId] = implementsERC165InterfaceNoCache(_contract, _interfaceId) ? _contract : 0;\n erc165Cached[_contract][_interfaceId] = true;\n }\n\n /// @notice Checks whether a contract implements an ERC165 interface or not.\n /// The result may be cached, if not a direct lookup is performed.\n /// @param _contract Address of the contract to check.\n /// @param _interfaceId ERC165 interface to check.\n /// @return `true` if `_contract` implements `_interfaceId`, false otherwise.\n function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) {\n if (!erc165Cached[_contract][_interfaceId]) {\n return implementsERC165InterfaceNoCache(_contract, _interfaceId);\n }\n return interfaces[_contract][_interfaceId] == _contract;\n }\n\n /// @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.\n /// @param _contract Address of the contract to check.\n /// @param _interfaceId ERC165 interface to check.\n /// @return `true` if `_contract` implements `_interfaceId`, false otherwise.\n function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) {\n uint256 success;\n uint256 result;\n\n (success, result) = noThrowCall(_contract, ERC165ID);\n if (success == 0 || result == 0) {\n return false;\n }\n\n (success, result) = noThrowCall(_contract, INVALID_ID);\n if (success == 0 || result != 0) {\n return false;\n }\n\n (success, result) = noThrowCall(_contract, _interfaceId);\n if (success == 1 && result == 1) {\n return true;\n }\n return false;\n }\n\n /// @notice Checks whether the hash is a ERC165 interface (ending with 28 zeroes) or not.\n /// @param _interfaceHash The hash to check.\n /// @return `true` if the hash is a ERC165 interface (ending with 28 zeroes), `false` otherwise.\n function isERC165Interface(bytes32 _interfaceHash) internal pure returns (bool) {\n return _interfaceHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0;\n }\n\n /// @dev Make a call on a contract without throwing if the function does not exist.\n function noThrowCall(address _contract, bytes4 _interfaceId)\n internal view returns (uint256 success, uint256 result)\n {\n bytes4 erc165ID = ERC165ID;\n\n assembly {\n let x := mload(0x40) // Find empty storage location using \"free memory pointer\"\n mstore(x, erc165ID) // Place signature at beginning of empty storage\n mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature\n\n success := staticcall(\n 30000, // 30k gas\n _contract, // To addr\n x, // Inputs are stored at location x\n 0x08, // Inputs are 8 bytes long\n x, // Store output over input (saves space)\n 0x20 // Outputs are 32 bytes long\n )\n\n result := mload(x) // Load the result\n }\n }\n}\n", "keccak256": "0x8eecce3912a15087b3f5845d5a74af7712c93d0a8fcd6f2d40f07ed5032022ab" } }, "version": 1 } 

Interface names

To identify which functionality a smart contract provides, compute a unique identifier from the interface name using the keccak256 hash function and pass it to getInterfaceImplementer().

If an interface belongs to a standard, it is recommended to state the interface name clearly and provide a link to the publicly available ERC820 specification. This gives other developers access to the relevant information without having to search separately for the rules.

The registry also provides the convenient interfaceHash(string _interfaceName) function for computing interface-name hashes directly on-chain.

javascript
function interfaceHash(string _interfaceName) public pure returns(bytes32)

Supplying the interface name returns its corresponding keccak256 hash. The hash is used to query the registry for a particular interface implementation. Developers can use this functionality to identify the contract implementing a given interface.

identifier: 65ba36c1 parameters _interfaceName: Name of the interface. returns: The keccak256 hash of an interface name.

Accepted ERCs

If the interface is part of an official Ethereum Request for Comments (ERC) standard, its name must follow the format ERC###XXXXX. Here, ### represents the ERC number, and XXXXX represents the interface name in camel case. This naming convention makes the standard associated with an interface clear. The meaning and usage of the interface are defined in the corresponding ERC document.

Examples include ERC20Token, ERC777Token, ERC777TokensSender, and ERC777TokensRecipient. These names are associated with particular standards such as ERC20 and ERC777. To identify these interfaces, compute a distinct hash from each interface name using the keccak256 function. The resulting hash is used to look up the corresponding implementer in the registry.

For more information on ERC777, see the following article.

[ERC777] Understanding the Standard Token Contract Interface

ERC-165-compatible interfaces

ERC165 compatibility was designed and developed with William Entriken and includes an ERC165 cache. An interface identifier whose last 28 bytes are zero (0) should be treated as an ERC165 interface.

Querying ERC165

Anyone can use the registry to explicitly check whether a contract implements an ERC165 interface. To do so, call either of the following two functions.

javascript
function implementsERC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool)

Checks whether a contract implements an ERC165 interface. The result is cached. If the cache is outdated, call updateERC165Cache to update it (see the ERC165 cache section for details).

identifier: f712f3e8 parameters _contract: Address of the contract to check. _interfaceId: ERC-165 interface to check. returns: true if _contract implements _interfaceId, false otherwise.

javascript
function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool)

Checks whether a contract implements an ERC165 interface without using the cache.

identifier: b7056765 parameters _contract: Address of the contract to check. _interfaceId: ERC-165 interface to check. returns: true if _contract implements _interfaceId, false otherwise.

ERC165 cache

The result of checking whether a contract implements an ERC165 interface can be cached manually to save gas. If a contract dynamically changes its interfaces and relies on the ERC165 cache in the ERC820 registry, the cache must be updated manually. There is no automatic cache invalidation or refresh. Ideally, a contract updates its cache whenever its interfaces change, but anyone can update the cache on the contract's behalf.

The cache must be updated through the updateERC165Cache function.

javascript
function updateERC165Cache(address _contract, bytes4 _interfaceId) public

Specify the address of the contract whose cache is being updated and the ERC-165 interface to update.

identifier: a41e7d51 parameters _contract: Address of the contract for which to update the cache. _interfaceId: ERC-165 interface for which to update the cache.

Private user-defined interfaces

The system is designed to be freely extensible. You can define your own interface name and encourage others to implement it. You can then check whether an implementation exists. This provides a way to experiment with and develop new functionality. Care must be taken, however, to avoid collisions with reserved names, such as existing official standards including ERC20 and ERC721.

When creating custom interfaces, respect existing standards and naming conventions and avoid confusion or collisions.

Setting an interface implementer for an address

This section explains how to use the ERC820 registry to specify the contract that implements a particular interface for an address. This registration is performed with the setInterfaceImplementer function.

javascript
function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) public

Specifically, it identifies which contract implements the selected interface on behalf of the address.

To call this function, you must be the manager of the address. By default, each address manages itself; see the managers section for more details.

When the registered address and the implementing contract differ, note that the implementing contract must satisfy the ERC820ImplementerInterface check as specified by the registry. Calling canImplementInterfaceForAddress on that contract must return the special value ERC820_ACCEPT_MAGIC when the acceptance check applies.

The specified interface hash (_interfaceHash) must also differ from identifiers reserved for ERC165 interfaces. In other words, its last 28 bytes must not all be 0.

If the _addr parameter is 0, the caller (msg.sender) is used as the address. This is a convenience for keeping transaction data constant in workflows such as multisignature signing.

Developers can use this function to register and discover which contracts implement particular interfaces on behalf of blockchain addresses.

identifier: 29965a1d parameters _addr: Address to define the interface for (if _addr == 0 them msg.sender: is assumed) _interfaceHash: keccak256 hash of the name of the interface as a string, for example web3.utils.keccak256('ERC777TokensRecipient') for the ERC777TokensRecipient interface. _implementer: Contract implementing _interfaceHash for _addr.

Retrieving an interface implementer for an address

Anyone can use the ERC820 registry to discover which interfaces an address implements through which contracts. This is done using the getInterfaceImplementer function.

javascript
function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) public view returns (address)

The function takes the address being queried and the interface hash as inputs and returns the address of the contract implementing the specified interface on behalf of the queried address.

If the last 28 bytes of the interface hash are 0, it is recognized as an ERC165 interface identifier. In that case, the registry queries the contract at the specified address to determine whether it implements the ERC165 interface. The results of ERC165 queries can also be cached to reduce gas consumption. This cache can be updated through the erc165UpdateCache function as named in the original explanation.

If the queried address (_addr) is 0, the caller (msg.sender) is used as the target. This design simplifies interactions in workflows such as multisignature signing.

For example, compute the keccak256 hash of an interface name such as ERC777Token, and supply the hash and the address being queried to the function. The function returns the address of the contract implementing the specified interface for that address, or 0x0 if no implementer is registered.

identifier: aabbb8ca parameters _addr: Address being queried for the implementer of an interface. (If _addr == 0 them msg.sender is assumed.) _interfaceHash: keccak256 hash of the name of the interface as a string. E.g. web3.utils.keccak256('ERC777Token') returns: The address of the contract which implements the interface _interfaceHash for _addr or 0x0 if _addr did not register an implementer for this interface.

Interface implementation (ERC820ImplementerInterface)

javascript
interface ERC820ImplementerInterface {
    /// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `addr`.
    /// @param addr Address for which the contract will implement the interface
    /// @param interfaceHash keccak256 hash of the name of the interface
    /// @return ERC820_ACCEPT_MAGIC only if the contract implements `ìnterfaceHash` for the address `addr`.
    function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) public view returns(bytes32);
}

ERC820ImplementerInterface provides a way to determine whether a contract agrees to implement a particular interface on behalf of a given address. A contract implementing this interface must provide the following function for the specified address and interface.

javascript
function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) public view returns(bytes32);

The function indicates whether the contract implements a particular interface (interfaceHash) for a particular address (addr). Here, interfaceHash is the keccak256 hash of the interface name.

identifier: f0083250 parameters interfaceHash: Hash of the interface which is implemented addr: Address for which the interface is implemented returns: ERC820_ACCEPT_MAGIC only if the contract implements ìnterfaceHash for the address addr.

If the contract implements the interface on behalf of the address, the function returns a special value, ERC820_ACCEPT_MAGIC. This value is defined as the keccak256 hash of the string "ERC820_ACCEPT_MAGIC". If the contract does not implement the interface, it returns a different value.

javascript
bytes32 constant ERC820_ACCEPT_MAGIC = keccak256("ERC820_ACCEPT_MAGIC");

Using ERC820_ACCEPT_MAGIC instead of a Boolean prevents a contract from being incorrectly recognized as an implementer when canImplementInterfaceForAddress is absent and a fallback function executes without reverting.

To establish whether a contract implements a particular interface for an address, use ERC820ImplementerInterface and check that ERC820_ACCEPT_MAGIC is returned under the appropriate conditions.

The reason to return ERC820_ACCEPT_MAGIC instead of a boolean is to prevent cases where a contract fails to implement the canImplementInterfaceForAddress but implements a fallback function which does not throw. In this case, since canImplementInterfaceForAddress does not exist, the fallback function is called instead, executed without throwing and returns 1. Thus making it appear as if canImplementInterfaceForAddress returned true.

Returning ERC820_ACCEPT_MAGIC instead of a Boolean prevents a false positive if a contract does not implement canImplementInterfaceForAddress but has a fallback function that does not throw. In that case, the absent function would cause the fallback to be called instead; a returned value of 1 could otherwise appear to indicate that canImplementInterfaceForAddress returned true.

Managers

Only the manager of an address (an individual account or a contract) can register the implementer of a particular interface for that address. By default, each address is its own manager.

setManager

javascript
function setManager(address _addr, address _newManager) public

The setManager function transfers management authority for an address to another address. The new manager can then register interface implementers on behalf of that address through setInterfaceImplementer. Setting the new manager to 0x0 (the zero address) resets the manager to the original address itself.

identifier: 5df8122f parameters _addr: Address for which to set the new manager. _newManager: The address of the new manager for _addr. (Pass 0x0 to reset the manager to _addr.)

getManager

javascript
function getManager(address _addr) public view returns(address)

The getManager function also allows callers to determine the current manager of an address. This is useful for looking up managers and determining whether management has changed.

identifier: 3d584063 parameters _addr: Address for which to return the manager. returns: Address of the manager for a given address.

Using these functions correctly enables management of addresses and efficient registration and discovery of their interface implementers.

Rationale

The standard provides a way for any type of address, including externally owned accounts and contracts, to support interfaces, potentially delegating interface implementation to a proxy contract. Delegation to a proxy contract is necessary for externally owned accounts and is useful for avoiding redeployment of existing contracts such as multisignature contracts and DAOs.

The registry also serves as an ERC165 cache, saving gas when checking whether a contract implements a particular ERC165 interface. The cache is deliberately kept simple, without automatic invalidation or refresh. Anyone can call updateERC165Cache to update the cache for any interface and contract in a straightforward and safe manner.

The registry uses keyless deployment based on a one-time deployment address, intended to ensure that nobody controls the deployment account and to provide a trust-minimizing deployment.

Backwards compatibility

This standard is backwards-compatible with ERC165, and the two can be implemented without conflict.

Tests

See the following repository for the test code.

Reference implementation

See the following repository for the implementation code.

References

Jordi Baylina jordi@baylina.cat, Jacques Dafflon jacques@dafflon.tech, "ERC-820: Pseudo-introspection Registry Contract," Ethereum Improvement Proposals, no. 820, January 2018. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-820.

Conclusion

This article examined ERC820, a standard proposing a way to discover whether an address supports a particular interface and which contract implements it. I hope it was useful.