I've been revisiting ethers.js recently to refresh my understanding of the details and to write a simple tutorial called "WTF Ethers" for beginners.
Twitter: @0xAA_Science
Community: Website wtf.academy | WTF Solidity | discord | WeChat Group Application
All the code and tutorials are open-sourced on GitHub: github.com/WTFAcademy/WTF-Ethers
In this tutorial, we will learn how to use ethers.js to identify if a contract is an ERC721 standard.
ERC721
ERC721 is a popular non-fungible token (NFT) standard on the Ethereum network. If you're unfamiliar with this standard, you can read about it in WTF Solidity 34: ERC721. When working on NFT-related projects, we need to identify contracts that comply with the ERC721 standard. For example, OpenSea automatically recognizes ERC721 contracts and collects their names, codes, metadata, and other data for display. To identify ERC721 contracts, we first need to understand ERC165.
ERC165
With the ERC165 standard, smart contracts can declare the interfaces they support for other contracts to check. Therefore, we can check if a smart contract supports the ERC721 interface using ERC165.
The IERC165 standard interface contract only declares a supportsInterface function. This function returns true if it implements that interface ID; otherwise, it returns false:
ERC721 contracts implement the supportsInterface function from the IERC165 interface contract and return true when queried with 0x80ac58cd (ERC721 interface ID):
Identifying ERC721 Contracts
- 
Create a providerto connect to the Ethereum mainnet.
- 
Create an instance of the ERC721contract. In theabiinterface, we declare thename(),symbol(), andsupportsInterface()functions to use. Here, we use the Bored Ape Yacht Club (BAYC) contract address.
- 
Read the on-chain information of the contract: name and symbol.  
- 
Use the supportsInterface()function ofERC165to identify whether the contract is anERC721standard. If it is, returntrue; otherwise, throw an error or returnfalse.Note that the selectorERC721constant in this code has been extracted into the main function. 
Summary
In this tutorial, we learned how to use ethers.js to identify if a contract follows the ERC721 standard. Since we utilized the ERC165 standard, contracts that support the ERC165 standard can be identified using this method, including ERC721, ERC1155, and others. However, for standards like ERC20 that do not support ERC165, different methods need to be used to identify them. Do you know how to check if a contract is an ERC20?