How to create an ERC721 Solidity smart contract

Sep 7, 2021

How to create an ERC721 Solidity smart contract


In this blog, well explain the way to create an ERC721 Solidity smart contract. First, well review the differences between an ERC20 and ERC721. Then well create two ERC721 NFT contracts.


There are many differences between an ERC20 and an ERC721 Ethereum token contract. ERC20 contracts create identical tokens that dont have characteristics to make them unique. Tokens from an ERC20 contract are fungible and are exchanged one for one. It doesnt matter which one you purchase or sell because theyre all equivalent. An ERC721 contract is employed to make unique tokens or NFTs (non-fungible tokens). Tokens from an equivalent ERC721 contract are unique and may not be duplicated because each token features a unique id. This suggests each token from an equivalent contract can have a special value or characteristic thanks to its age, rarity or another attribute.


What does one understand by ERC-721?

The full sort of ERC is EthereumRequest for Comment, and 721 in “ERC-721” is the numeric proposal identifier. ERC is that the application-level guideline within the Ethereum network wants to define smart contract specifications for the tokens like ERC-20. Its the responsibility of the author of an ERC to determine consensus within the Ethereum community, and once the community has finalized the proposal, it becomes typical. ERC-721 was intended to facilitate the tracking and transfer of non-fiduciary tokens within smart contracts.


ERC-721 is an open standard that defines the way to create Non-Fungible Tokens on EVM (Ethereum Virtual Machine) compliant blockchains; it also is a typical interface for Non-Fungible Tokens and it includes a group of rules that make working with NFTs simple. Non-fungible tokens (NFTs) arent limited to the ERC-721 standard; they will even be ERC-1155 tokens.


ERC-721 defines several functions that are compliant with ERC-20. It simplifies the method of existing wallets displaying basic token information added to the list of the subsequent salient features.


  • High compliance.

  • Unique ID.

  • Multiple Product Management.

  • Admin tools.

  • Subscriptions and Newsletters for immediate upgrades.

  • Embedded Web3 checkout button with metamask support.

  • Easy transfers.

  • ERC721 token wallet apps for web, android, and ios.

  • Roles-based permission.

  • High-end security systems.

What are the functions of ERC-721? 

Functions almost like that of ERC-20

Name

This field is employed to specify the token’s name, which other contracts and applications can use to spot it.

Symbol

Used to define the shorthand name or symbol for the token.

totalSupply

This function is employed to specify the entire supply of tokens on the blockchain; the availability doesnt need to be persistent.

balanceOf

Returns the amount of NFTs that an address owns.

Ownership Responsibilities

ownerOf

This function returns the owner of a token’s address. Because ERC-721 tokens are non-fungible and unique, theyre represented on the blockchain by an ID. This ID is often employed by other users, contracts, and applications to work out who owns the token.

Approve

This function allows or approves another entity the authority to transfer tokens on behalf of the owner.

takeOwnership

It is an optional function that functions similarly to a withdraw function therein; it is often called by an external party to withdraw tokens from another user’s account. As such, takeOwnership is often used when a user has been approved to have a specified amount of tokens and needs to withdraw those tokens from the balance of another user.

transfer

It is another transfer function; it enables the token owner to transfer it to a different user, almost like how other digital tokens/coins work.

tokenOfOwnerByIndex

It is a recommended but optional function. Each owner may own multiple NFTs concurrently. However, each NFT is identified by a singular ID, and it can become difficult to stay track of IDs over time. As a result, the contract stores these IDs in an array, and therefore the tokenOfOwnerByIndex function allows us to retrieve them.

The function of Metadata

tokenMetadata

This optional feature provides an interface for locating the metadata or linking to the info related to a token.


Events


Transfer

This event is triggered when the token’s ownership changes from one individual to a different one. It emits information about the account that transferred the token, the account that received the token, and therefore the transferred token (by ID).


Approve

This event is fired whenever a user grants another user ownership of the token, i.e., whenever the approve function is executed. It emits information about which account currently owns the token, which account has been granted permission to accumulate ownership of the token within the future, and which token (by ID) has been granted permission to transfer ownership.

What are the steps to make and deploy ERC-721 tokens? 

Now that we are conversant in the concept of ERC-721 let’s move ahead and understand the steps involved in creating and deploying the ERC-721 token.


Step1: Getting test ETH

We will use the Ropsten testnet to deploy our contract. To start with this process, youll need a browser extension named Metamask from the Ropsten faucet to make some test ETH and an ETH wallet. Next, select the choice of Ropsten test network available on Metamask wallet, copy the wallet address to the subsequent specified field, then press the choice for receiving the test Ether.

Step2: Adding Files to IPFS

The next step is to feature the files to the IPFS. well get to host our art for the NFT and make a metadata file before writing the NFTcontract; well use the Peer-to-Peer File Storing, and Sharing distributed system (IPFS). Start with downloading IPFS then install it as per the OS.


Follow the below-mentioned steps to host a picture and a metadata file:


Start with the IPFS repo creation by typing the below-mentioned code during a cmd/terminal window,

$ ipfs init

Then begin with the IPFS daemon by separately opening the cmd/terminal window then enter the code,

$ ipfs daemon

Then add a picture to the IPFS by getting to the primary terminal window as per the code mentioned below,

$ ipfs add art.png

Then copy hash ranging from Qm and fasten the prefix “https://ipfs.io/ipfs/.”


Next, youve got to feature a JSON file to IPFS. Begin by creating a JSON file and saving it on an equivalent directory within the image form.

Check out the file format of JSON mentioned below,


name: NFT Art

description: This image shows accurate nature of NFT

image: https://ipfs.io/ipfs/QmZzBdKF7sQX1Q49CQGmreuZHxt9sVB3hTc3TTXYcVZ7jC

The next step is to feature JSON file as,

$ ipfs add nft.json

Then copy hash ranging from Qm and fasten the prefix “https://ipfs.io/ipfs/.” The output will appear as if this,


https://ipfs.io/ipfs/QmUFbUjAifv9GwJo7ufTB5sccnrNqELhDMafoEmZdPPng7

We will save this URL because it becomes useful while minting the tokens later.


Step3: Creating Token

We will be using the ERC-721 contract for a smooth NFT creation process. well not write on the entire ERC-721 interface as we are using the Ethereum ERC-721. We also use the functions of the library contract by importing them. Move towards the Ethereum IDE then create a solidity file. Then start importing the below-mentioned code into your newly created script of solidity.


// SPDX-License-Identifier: MIT

pragma solidity 0.8.0;

import https://github.com/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-metadata.sol,

import https://github.com/0xcert/ethereum-erc721/src/contracts/ownership/ownable.sol,

contract newNFT is NFTokenMetadata, Ownable {

constructor() {

nftName = Synth NFT;

nftSymbol = SYN;

}

function mint(address _to, uint256 _tokenId, string calldata _uri) external onlyOwner {

super._mint(_to, _tokenId);

super._setTokenUri(_tokenId, _uri);

}

}

The code mentioned above is known as,


Line 1 specifies the sort of SPDX license. These licenses will help in solving the problems of copyright.

Line 2 declares the version of solidity.

Line 4 and 5 of the command explains importing of Ethereum ERC-721 contracts.

Line 7 command states about beginning the Contract named newNFT and specifically mentioning it’s extending Ownable contracts and NFT token metadata.

Line 9-12 states about initializing a logo for the token, constructor and setting a reputation .

Line 14 declares the function minted with the three arguments, variable _uri of type string, the method of storing the URI of the JSON file, variable _to of type address which can help in storing the address of the receiver of NFT token, variable _tokenId of uint256 type which can hold the token id.

Line 15 gives the command of token minting with the assistance of the token id and receiver’s address.

Line 16 states about fixing Token URI with the assistance of URI of JSON file and token id.

With the assistance of injected Web3, deploy the compiled smart contract then approve the transaction from the metamask.


After deploying the smart contract, expand it from the “Deployed Contracts” section in Remix. itll reflect tons of functions/methods. Then broaden the function of mint and fasten the below-mentioned details:


Ropsten address

Any big number value within the _tokenid field

Add URI of JSON enter the _uri field obtained previously.

Click and ensure transaction from metamask. youll then have a token on the Ropsten chain. youll also verify other credentials like name, symbol, owner, or token URI by inserting the token id.


What are the advantages of ERC-721 token development?

ERC-721 tokens cover numerous business verticals like healthcare, finance, retail, e-learning, tourism, media, and entertainment, with the foremost prominent following benefits.

Piracy free

The undeniable security and effective management make the token piracy-free.

Surveillance free

The web3 platform handles overall ownership-oriented matters. Hence, tokens are free from surveillance.

Limited licenses

The number of licenses imparted to the ERC721 token is extremely limited and scarce.

Transferable license 

Though the tokens are non-transferrable thanks to their non-fungibility, their licenses are transferrable or exchangeable.


The motive behind creating ERC-721 tokens is that the chance of token generation that too a singular token with solitary functions. Therefore, the individuality of the ERC-721 token works as a benefit. Therefore, people’s desire to urge it remains inversely proportional to the number of comparable tokens available. For better guidance, contact our team of developers.


ERC721 Contract

ERC721 tokens support many of the equivalent features as ERC20 tokens. Both of those token contracts support many equivalent sorts of functions (transfer, approve, get total supply, etc.). Additionally, a bit like an ERC20 contract, an ERC721 contract requires basic metadata as an example name and symbol are required when creating a contract.


ERC721 tokens have a couple of characteristics that arent found in an ERC20 token. Every ERC721 token minted from a contract can have a singular id. consider this unique id just like the number on a 1 out of 200 trading card. Every ERC721 token minted can include a URI (a link to something). A URI or Uniform Resource Locator is an identifier for a selected resource file for instance an image, book, or document. These URI’s are usually tips about IPFS. This contract is used for DeFi Development Companies like brugu. 

Example ERC721 NFT smart contracts with URI

The Solidity code below is an ERC721 smart contract. youll use this contract to mint NFT tokens. within the contract below once you call the create NFT function youll pass during a URI to associate it with the NFT that you simply mint. So if youve got a URI on IPFS that links to an image youll include it within the contract below. The contract is extendable and will contain additional functions. Read the code comments to urge a far better understanding of how the contract works.

Example ERC721 NFT smart contracts with characteristics

In programming, there are some ways to implement an answer so now let’s check out a special NFT smart contract implementation.


In the ERC721 smart contract below youll create an NFT which will have a trait or specific characteristic (for example; red, tall, fast, strong, anything). Maps store NTF traits. The map is checked whenever a replacement NFT is minted to stop duplicate tokens from being created. This prevents tokens from having equivalent traits or characteristics.


The best way to find out how NFT works is to experiment and make a sensible accept Remix. Take these contracts to a subsequent level and add your creativity. Extend these contracts to:

Allow for multiple traits

Implement a Chainlink oracle to get a very random number and have the amount represent a characteristic (value, strength, speed, etc)


  • Create an internet site so visitors can mint their own NFTs.

  • Combine the 2 contracts above so your NFT can have a URI and traits


ERC721 contracts support many various use cases from document ownership to issuing domain names.


This code is for learning and entertainment purposes only. The code has not been audited. Use at your own risk. Remember smart contracts are experimental and will contain bugs.




Articles authored by brugu softwaresolutions

Published: Aug 7, 2021

Published: Jul 27, 2021

Published: Jul 22, 2021

Published: Jul 13, 2021

Published: Jul 1, 2021

Published: May 26, 2021

Published: May 24, 2021

Published: May 19, 2021