0
0
Blockchain / Solidityprogramming~10 mins

ERC-721 implementation in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

ERC-721 is a standard for creating unique digital items called NFTs on the blockchain. It helps make sure these items can be owned, transferred, and tracked easily.

You want to create digital art that can be owned and sold individually.
You need to make unique game items that players can trade.
You want to represent ownership of collectibles like trading cards.
You want to build a system where each token is different and has its own value.
Syntax
Blockchain / Solidity
pragma solidity ^0.8.0;

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

contract MyNFT is ERC721 {
    constructor() ERC721("MyNFT", "MNFT") {}

    function mint(address to, uint256 tokenId) public {
        _mint(to, tokenId);
    }
}

The contract inherits from OpenZeppelin's ERC721 implementation to save time and avoid errors.

The mint function creates a new unique token and assigns it to an owner.

Examples
This example shows a basic NFT contract with a mint function.
Blockchain / Solidity
pragma solidity ^0.8.0;

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

contract SimpleNFT is ERC721 {
    constructor() ERC721("SimpleNFT", "SNFT") {}

    function mintToken(address to, uint256 tokenId) public {
        _mint(to, tokenId);
    }
}
This example adds metadata support by storing a URI for each token.
Blockchain / Solidity
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";

contract MetadataNFT is ERC721URIStorage {
    constructor() ERC721("MetadataNFT", "MNFT") {}

    function mintToken(address to, uint256 tokenId, string memory uri) public {
        _mint(to, tokenId);
        _setTokenURI(tokenId, uri);
    }
}
Sample Program

This contract lets anyone mint a new unique NFT. Each token has a unique ID starting from 0 and increasing by 1.

Blockchain / Solidity
pragma solidity ^0.8.0;

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

contract MyNFT is ERC721 {
    uint256 public nextTokenId;

    constructor() ERC721("MyNFT", "MNFT") {}

    function mint() public {
        _mint(msg.sender, nextTokenId);
        nextTokenId++;
    }
}
OutputSuccess
Important Notes

Always use a well-tested library like OpenZeppelin to avoid security issues.

Each token ID must be unique to represent a unique item.

Minting functions can be restricted to certain users for control.

Summary

ERC-721 lets you create unique tokens called NFTs.

Use OpenZeppelin's ERC721 contract to simplify your code.

Minting creates new tokens with unique IDs assigned to owners.