May 16, 2024 05:45 AM
(This post was last modified: May 16, 2024 07:29 AM by Hackers.)
![[Image: banner-1.gif]](https://i.ibb.co/J74v9LR/banner-1.gif)
Today you will learn how to create an ERC-721 smart contract. This is meant for Ethereum/EVM-based blockchain tokens, using Solidity as the core language. This is a basic example to help you get started, but does work as-is. You can deploy the contract and as the owner, you can mint NFTs to other addresses. The contract below (source code in spoiler at end of post) does not include IPFS or other onchain data, but instead acts as a mechanism to distribute tokens. You can use these tokens however you wish in external systems, such as using them for access, memberships, real-world representations, or other use cases. Feel free to add on features and extend this base contract however you wish to implement custom functions!
![[Image: divider.png]](https://i.ibb.co/9Zr9WzJ/divider.png)
Code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;Code
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";We use Ownable to enforce on-chain security for token ownership so people can't manage other people's tokens and to keep things secure.
Code
contract FallenExampleERC721 is ERC721, Ownable {Code
uint256 private _tokenIdCounter;Code
constructor() ERC721("FallenExampleERC721", "FE721") {}Code
function safeMint(address to) public onlyOwner {
uint256 tokenId = _tokenIdCounter;
_tokenIdCounter += 1;
_safeMint(to, tokenId);
}We set the token ID to the current token ID count, which is the newest #, starting from 1 on first mint, then 2, 3, and so on.
We then increment the token id counter before we mint , so that the count is already +1 for the next mint that occurs on the contract. This is a safeguard / best practice to update data related to mints before the mint. The same is true if you are deducting balances - deduct from contract balance before sending. This is due to a thing called reentrancy but I won't go deep into that here. Just know that you should follow this rule 100% of the time.
The _safeMint function corresponds to an openzeppelin method to mint the NFT to the destination address, for the new token ID.
![[Image: divider-gif.gif]](https://i.ibb.co/G2HzzXd/divider-gif.gif)
Full source code:
Spoiler (Click to View)
Looking for more? Check this out:
https://hackforums.net/showthread.php?tid=6271197







![[Image: vibesignature.gif]](https://i.ibb.co/8LvxwtYQ/vibesignature.gif)