NFT Mastery: Understanding ERC-721 on Ethereum for Starters

Rosario Borgesi
Coinmonks
10 min readJan 20, 2024

--

NFTs have become a mainstream topic in the blockchain world. In this article, our goal is to delve into the NFT sphere, gaining insights into what defines them, what sets them apart from other tokens, and the benefits they offer. Furthermore, we will take a closer look at the ERC-721 standard on Ethereum, aimed at standardizing the creation of NFTs, shaping the landscape of digital ownership.

Table of Contents

· Table of Contents
· Tokens
· Non-Fungible Tokens (NFTs)
· Examples of NFTs
· Benefits of Non-Fungible Tokens
Market Efficiency
Investing
Security
Defense against Counterfeiting
Protect Value and Ownership
· ERC-721 Standard
Methods
Events
· OpenZeppelin’s ERC-721 Contracts
· Hands-on Demonstration
· Further NFT Exploration
· Conclusions
· Resources

Tokens

A token is a digital asset built on top of a blockchain and can represent virtually anything like:

  • Loyalty Points in a Customer Rewards Program
  • Experience Points for a Player in a Role-Playing Game
  • Event Tickets for Concerts or Sports Games
  • Equity Stake in a Start-up Company
  • Real Estate Properties
  • Academic Credentials and Degrees
  • and so on…

However, from a financial perspective, we can distinguish between two kinds of tokens:

  • Fungible tokens: are interchangeable and hold equal value. For instance, the value of one bitcoin is consistently the same as another, much like how every U.S. dollar bill is always equal to another dollar bill. (More on fungible tokens here)
  • Non-fungible tokens (NFTs): are unique and non-interchangeable, each possessing distinct attributes that differentiate them from one another. Consider two well-known masterpieces, such as Leonardo da Vinci’s “Mona Lisa” and Vincent Van Gogh’s “The Starry Night” — each possesses its own distinctiveness and cannot be exchanged for the other.

Non-Fungible Tokens (NFTs)

Non-fungible tokens serve as representations of assets, with the tokens residing on the blockchain while the actual assets are stored in other places.

NFTs can be traded and exchanged for money, cryptocurrencies, or other NFTs, and their value is determined by both the market and individual owners. For example, consider taking a picture of the ocean and tokenizing it on a blockchain. The individual holding the private keys to that token gains ownership of the designated rights associated with it.

NFTs existed well before gaining widespread popularity. Allegedly, the initial NFT to be sold was “Quantum,” crafted and tokenized by Kevin McKoy in 2014 on Namecoin blockchain, later minted on Ethereum, and eventually sold in 2021.

NFTs are created through a process called minting, in which the asset’s information is encrypted and recorded on a blockchain. This process require creating and deploying smart contracts that handle the ownership assignment and manage the transfer of the NFTs.

Upon minting, tokens receive a distinct identifier directly tied to a blockchain address. Each token comes with an owner, and the ownership details — namely, the address where the minted token resides— are publicly accessible.

NFTs have revolutionized the crypto landscape by ensuring the uniqueness and irreplaceability of each token. This makes it impossible for any non-fungible token to be identical to another. Functioning as digital representations of assets, they’ve been compared to digital passports due to each token holding a distinct, non-transferable identity, setting it apart from others.

Examples of NFTs

The initial NFT market predominantly focused on digital art and collectibles, but it has expanded into diverse domains. In fact the most popular NFT marketplace OpenSea has several NFT categories:

  • Photography: Photographers can tokenize their work and offer total or partial ownership.
  • Sports: Collections of digital art based on celebrities and sports personalities.
  • Trading cards: Tokenized digital trading cards. Some are collectibles, while others can be traded in video games.
  • Utility: NFTs that can represent membership or unlock benefits.
  • Virtual worlds: Virtual world NFTs grant you ownership of anything from avatar wearables to digital property.
  • Art: A generalized category of NFTs that includes everything from pixel to abstract art
  • Collectibles: Bored Ape Yacht Club, Crypto Punks, and Pudgy Panda are some examples of NFTs in this category
  • Domain names: NFTs that represent ownership of domain names for your website(s)
  • Music: Artists can tokenize their music, granting buyers the rights the artist wants them to have

Benefits of Non-Fungible Tokens

Market Efficiency

One of the standout advantages of NFTs lies in market efficiency. The process of tokenizing a physical asset has the potential to simplify sales procedures and cut out intermediaries. In the case of NFTs representing digital or physical artwork on a blockchain, the necessity for agents can be eliminated, enabling sellers to directly engage with their intended audience

Investing

NFTs offer a streamlined approach to investing, extending beyond art and collectibles. Real estate, for instance, can be tokenized, dividing properties into unique sections represented by individual NFTs. This enables simplified trading with specific property features and associated metadata.

Additionally, NFTs can mirror stock ownership, providing an alternative to traditional stock ledgers. Leveraging blockchain technology, NFTs and smart contracts automate ownership transfers, offering a more efficient and secure method compared to conventional stock processes.

Furthermore, NFTs contribute to democratizing investing through fractionalized ownership of physical assets. Tokenization enables multiple individuals to purchase shares of assets such as paintings, allowing for the transfer of ownership fractions.

Security

Non-fungible tokens play a crucial role in enhancing identity security, as personal information stored on an immutable blockchain remains inaccessible and secure without the proper keys.

Defense against Counterfeiting

Each NFT possesses distinct attributes and a unique identifier, ensuring its individuality and distinguishing it from all other tokens. This unique identifier plays a crucial role in authenticating and verifying the provenance of the associated asset, confirming its originality and guarding against counterfeiting.

When applied to physical merchandise, NFTs function as digital certificates of authenticity. By linking an NFT to a specific product, manufacturers and creators establish an immutable record of the item’s origin, production process, and ownership history. This decentralized and transparent system creates a formidable barrier for counterfeiters, as the blockchain maintains an unalterable trail of the item’s journey from creation to sale.

Moreover, retailers and consumers can effortlessly authenticate a product by scanning its associated NFT. Prospective buyers, in fact, have the ability to confirm the authenticity and ownership of digital assets before completing a transaction, effectively minimizing the risk of falling victim to fraudulent schemes.

Protect Value and Ownership

NFTs extend their protective role beyond physical goods, providing a solution for preserving the value and ownership of digital assets. In the art domain, NFTs emerge as a revolutionary tool, empowering artists to both sell and secure their digital masterpieces. By minting artwork as NFTs, artists not only establish ownership and trace the lineage of each creation but also monetize their work while preventing unauthorized duplication and distribution. NFTs enable a direct and traceable connection between creators and their digital creations.

ERC-721 Standard

The ERC-721 (Ethereum Request for Comments 721), introduced by William Entriken, Dieter Shirley, Jacob Evans, and Nastassia Sachs in January 2018, serves as a Non-Fungible Token Standard with an API tailored for tokens within Smart Contracts.

This standard enables various functionalities, including the transfer of tokens between accounts, retrieving the current token balance of an account, identifying the owner of a specific token, and determining the total supply of tokens available on the network. Additionally, it includes features such as approving a third-party account to move a designated amount of tokens from another account.

A Smart Contract implementing these methods and events is recognized as an ERC-721 Non-Fungible Token Contract. Once deployed, it assumes the responsibility of tracking the created tokens on the Ethereum network.

Methods

  function balanceOf(address _owner) external view returns (uint256);
function ownerOf(uint256 _tokenId) external view returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
function approve(address _approved, uint256 _tokenId) external payable;
function setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
  • balanceOf: count all NFTs assigned to an owner
  • ownerOf: find the owner of an NFT
  • safeTransferFrom (without data): transfers safely the ownership of an NFT from one address to another. It also checks if the recipient is a smart contract and if it can accept the NFT. In fact the recevire of the NFT must implement a specific function (onERC721Received) to accept the transfer.
  • safeTransferFrom (with data): this function operates similarly to safeTransferFrom (without data), but includes an additional data parameter. This extra data can convey supplementary information during the transfer, particularly if the recipient is a smart contract.Furthermore, the function verifies whether the recipient is a smart contract and if it implements the onERC721Received function.
  • transferFrom: transfer ownership of an NFT. The caller is responsible to confirm that the _to address is capable of receiving NFTs or else the may be permanently lost. It is generally used when the sender has been approved to transfer the token.
  • approve: this function grants permission to a specific address for transferring a designated token. It enables delegated transfers, permitting an owner to authorize another party to transfer a token on their behalf.
  • setApprovalForAll: enable or disable approval for a third party (“operator”) to manage all of msg.sender’s assets. In other words, this function enables a token owner to grant or revoke approval for an operator to manage all of their tokens.
  • getApproved: this function retrieves the approved address for a specific NFT. If no address has been approved for the token, this function will return a null address.
  • isApprovedForAll: this function is utilized to verify whether an operator is approved to manage all NFTs belonging to an owner.

Events

  event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
  • Transfer: this emits when ownership of any NFT changes by any mechanism.
  • Approval: this emits when the approved address for an NFT is changed or reaffirmed.
  • ApprovalForAll: this emits when an operator is enabled or disabled for an owner. The operator can manage all NFTs of the owner.

OpenZeppelin’s ERC-721 Contracts

OpenZeppelin provides the contract implementations of the ERC-721 standard.

The ERC specifies four interfaces:

  • IERC721: Core functionality required in all compliant implementation.
  • IERC721Metadata: Optional extension that adds name, symbol, and token URI, almost always included.
  • IERC721Enumerable: Optional extension that allows enumerating the tokens on chain, often not included since it requires large gas overhead.
  • IERC721Receiver: An interface that must be implemented by contracts if they want to accept tokens through safeTransferFrom.

OpenZeppelin Contracts provides implementations of all four interfaces:

  • ERC721: The basic contract implementation contains the core functionality and metadata extensions, with a base URI mechanism.
  • ERC721Enumerable: The enumerable extension. Adds the enumerability of all token ids in the contract as well as token ids owned by each account
  • ERC721Holder: A bare bones implementation of the receiver interface.

There are also other custom extensions that provide additional features to the ERC721 contract:

  • ERC721Burnable: allows token holders to burn their own tokens.
  • ERC721Consecutive: allows to mint large batches of tokens, during contract construction only
  • ERC721Pausable: allows to pause token transfers, minting and burning
  • ERC721Royalty: introduces a standardized way to retrieve royalty payment informations.
  • ERC721URIStorage: adds a more flexible but more expensive way of storing metadata.
  • ERC721Votes: supports voting and delegation, where each individual NFT counts as 1 vote unit
  • ERC721Wrapper: wrapper to create an ERC-721 backed by another ERC-721, with deposit and withdraw methods. Useful in conjunction with {ERC721Votes}.

Hands-on Demonstration

In this example, we want to create a very basic ERC721 token to tokenize houses on the blockchain.

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

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract HouseToken is ERC721, Ownable {
uint256 private _nextTokenId;

constructor(address initialOwner)
ERC721("HouseToken", "HTK")
Ownable(initialOwner)
{}

function safeMint(address to) public onlyOwner {
uint256 tokenId = _nextTokenId++;
_safeMint(to, tokenId);
}
}

The contract, named HouseToken, inherits from both the ERC721 and Ownable contracts. The ERC721 token incorporates all the functions and events discussed in the ERC721 standard. In the ERC721 constructor, we provide the token name ‘HouseToken’ and its symbol ‘HTK’ as arguments. This contract allows us to mint new tokens by calling the safeMint function and specifying the address that should receive the newly minted token.

On the other hand, the Ownable contract enables the definition of an owner address for this contract. The owner address is the only one authorized to mint new tokens, as the safeMint function is equipped with the onlyOwner modifier. Additionally, with each new token minted, the contract automatically handles the incrementation of the tokenId.

Further NFT Exploration

For those eager to explore the technical side, I recommend diving into the following companion piece:

In this in-depth article, we dissect the smart contracts, delve into Solidity code, and explore the intricacies of minting, transferring, and managing NFTs. Whether you’re a developer, an artist, or simply curious about the magic behind NFTs, this deeper exploration awaits.

Conclusions

In conclusion, we’ve delved into the fascinating world of NFTs, unraveling their definition, benefits, and real-world applications. Our exploration extended to OpenZeppelin’s contracts, empowering creators to forge new NFTs. In the final leg, we walked through the creation of an ERC721 token. I trust this article has proven valuable. Should you have any questions, feel free to comment. If you enjoyed the read, consider subscribing for updates on future content. Thank you for reading my article!

Resources

--

--