Solidity get interface id and ERC165

Nhan Cao
3 min readSep 15, 2021

To get interface id, use

type(ITest).interfaceId

Remember interfaceId = xor of all selectors (methods) name and param type, don't care to return type

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;
}
}
  • Return same id with difference param name
=> bytes4: 0xd48e638a// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITest {
function getCreator(uint name) external returns (uint);
}
contract Test is ITest {
bytes4 public constant IID_ITEST = type(ITest).interfaceId;

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

function getCreator(uint name2) external pure override returns (uint) {
return name2;
}
}
  • MockERC1155
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4…

--

--