Solidity get interface id and ERC165

To get interface id, use

type(ITest).interfaceId

Remember interfaceId = xor of all selectors (methods) name, don’t care to return type, just name

For example:

  • Return zero with empty interface
=> bytes4: 0x00000000

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface ITest {
}

contract Test is ITest {
    bytes4 public constant IID_ITEST = type(ITest).interfaceId;    
}
  • Return same id with difference return type
=> bytes4: 0x0ee2cb10

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface ITest {
    function getCreator() external;
}

contract Test is ITest {
    bytes4 public constant IID_ITEST = type(ITest).interfaceId;   
    
    function getCreator() external override { } 
}

===========
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface ITest {
    function getCreator() external returns (uint);
}

contract Test is ITest {
    bytes4 public constant IID_ITEST = type(ITest).interfaceId;   
    
    function getCreator() external pure override returns (uint) {
        return 0;
    }
}
  • Combine with ERC165
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/introspection/IERC165.sol";

interface ITest {
    function getCreator() external returns (uint);
}

contract Test is ITest, IERC165 {
    bytes4 public constant IID_ITEST = type(ITest).interfaceId;
    bytes4 public constant IID_IERC165 = type(IERC165).interfaceId;
    
    function getCreator() external pure override returns (uint) {
        return 0;
    }
    
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == IID_ITEST || interfaceId == IID_IERC165;
    }
}

Leave a Reply

Your email address will not be published.Required fields are marked *