SupportsInterface.behavior.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const { makeInterfaceId } = require('@openzeppelin/test-helpers');
  2. const { expect } = require('chai');
  3. const INTERFACES = {
  4. ERC165: [
  5. 'supportsInterface(bytes4)',
  6. ],
  7. ERC721: [
  8. 'balanceOf(address)',
  9. 'ownerOf(uint256)',
  10. 'approve(address,uint256)',
  11. 'getApproved(uint256)',
  12. 'setApprovalForAll(address,bool)',
  13. 'isApprovedForAll(address,address)',
  14. 'transferFrom(address,address,uint256)',
  15. 'safeTransferFrom(address,address,uint256)',
  16. 'safeTransferFrom(address,address,uint256,bytes)',
  17. ],
  18. ERC721Enumerable: [
  19. 'totalSupply()',
  20. 'tokenOfOwnerByIndex(address,uint256)',
  21. 'tokenByIndex(uint256)',
  22. ],
  23. ERC721Metadata: [
  24. 'name()',
  25. 'symbol()',
  26. 'tokenURI(uint256)',
  27. ],
  28. };
  29. const INTERFACE_IDS = {};
  30. const FN_SIGNATURES = {};
  31. for (const k of Object.getOwnPropertyNames(INTERFACES)) {
  32. INTERFACE_IDS[k] = makeInterfaceId.ERC165(INTERFACES[k]);
  33. for (const fnName of INTERFACES[k]) {
  34. // the interface id of a single function is equivalent to its function signature
  35. FN_SIGNATURES[fnName] = makeInterfaceId.ERC165([fnName]);
  36. }
  37. }
  38. function shouldSupportInterfaces (interfaces = []) {
  39. describe('Contract interface', function () {
  40. beforeEach(function () {
  41. this.contractUnderTest = this.mock || this.token;
  42. });
  43. for (const k of interfaces) {
  44. const interfaceId = INTERFACE_IDS[k];
  45. describe(k, function () {
  46. describe('ERC165\'s supportsInterface(bytes4)', function () {
  47. it('should use less than 30k gas', async function () {
  48. expect(await this.contractUnderTest.supportsInterface.estimateGas(interfaceId)).to.be.lte(30000);
  49. });
  50. it('should claim support', async function () {
  51. expect(await this.contractUnderTest.supportsInterface(interfaceId)).to.equal(true);
  52. });
  53. });
  54. for (const fnName of INTERFACES[k]) {
  55. const fnSig = FN_SIGNATURES[fnName];
  56. describe(fnName, function () {
  57. it('should be implemented', function () {
  58. expect(this.contractUnderTest.abi.filter(fn => fn.signature === fnSig).length).to.equal(1);
  59. });
  60. });
  61. }
  62. });
  63. }
  64. });
  65. }
  66. module.exports = {
  67. shouldSupportInterfaces,
  68. };