How to Create NFT Using Solidity: Simple Guide with Example
To create an NFT using
Solidity, write a smart contract that inherits from the ERC721 standard, which defines the NFT behavior. Use OpenZeppelin's library for secure and tested code, then deploy your contract to a blockchain to mint unique tokens.Syntax
An NFT contract in Solidity typically inherits from the ERC721 standard. You define the contract name, import the OpenZeppelin ERC721 library, and implement functions like _mint to create tokens.
- pragma solidity: Specifies Solidity version.
- import: Brings in OpenZeppelin's ERC721 code.
- contract: Defines your NFT contract.
- constructor: Sets the token name and symbol.
- _mint: Creates a new NFT with a unique ID.
solidity
pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract MyNFT is ERC721 { constructor() ERC721("MyNFT", "MNFT") {} function mintNFT(address to, uint256 tokenId) public { _mint(to, tokenId); } }
Example
This example shows a simple NFT contract using OpenZeppelin's ERC721. It lets anyone mint a unique token by calling mintNFT with their address and a token ID.
solidity
pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract SimpleNFT is ERC721 { constructor() ERC721("SimpleNFT", "SNFT") {} function mintNFT(address recipient, uint256 tokenId) public { _mint(recipient, tokenId); } }
Output
No direct output; the contract deploys and allows minting NFTs on the blockchain.
Common Pitfalls
Common mistakes when creating NFTs include:
- Not using a unique
tokenIdfor each NFT, causing minting to fail. - Not inheriting from
ERC721properly, missing essential NFT functions. - Not setting the token name and symbol in the constructor.
- Allowing anyone to mint without restrictions can lead to spam tokens.
Always test your contract on a test network before deploying live.
solidity
/* Wrong: minting same tokenId twice causes error */ function mintNFT(address to) public { uint256 tokenId = 1; _mint(to, tokenId); // works first time _mint(to, tokenId); // fails second time } /* Right: use unique tokenIds */ uint256 private currentId = 0; function mintNFT(address to) public { currentId++; _mint(to, currentId); }
Quick Reference
Key points to remember when creating NFTs with Solidity:
- Use OpenZeppelin's
ERC721for standard NFT features. - Each NFT must have a unique
tokenId. - Set token name and symbol in the constructor.
- Control who can mint tokens to avoid abuse.
- Test on testnets before mainnet deployment.
Key Takeaways
Use OpenZeppelin's ERC721 contract to create NFTs securely and easily.
Always assign a unique tokenId for each NFT minted.
Set the token name and symbol in the contract constructor.
Control minting permissions to prevent unwanted token creation.
Test your NFT contract on a test network before deploying to mainnet.