< All Blog
November 04, 2022
EIP-721 is a specification on how Non-Fungible Token (NFT) should be implemented on Ethereum. You can use Solidity to build your own NFT that can be minted.
OpenZeppelin offers a simpler way to build your own NFT using their libraries.
In the following source code, you're creating a new NFT, whose name is MyNFT
and its unit is NFT
.
This NFT does not come with Ownable
OpenZeppelin libraly, meaning anyone can call mintNFT()
RPC.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
contract MyNFT is ERC721URIStorage {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
constructor() ERC721("MyNFT", "NFT") {}
function mintNFT(address recipient, string memory tokenURI)
public payable
returns (uint256)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(recipient, newItemId);
_setTokenURI(newItemId, tokenURI);
return newItemId;
}
}
What if you'd like to set prices on this NFT? If your NFTs are on any NFT marketplaces, they may offer pricing features. But how to implement the price guard on Solidity?
This is fairly simple actually. Add a new require
clause asserting that the passed msg.value
is larger than the price.
function mintNFT(address recipient, string memory tokenURI)
public payable
returns (uint256)
{
+ require(msg.value >= 0.0001 ether, "Not enough ETH sent");