Create Your ERC721 Contract
Install Dependencies
We will build your ERC721 contract based on the Openzeppelin contracts. Let's install Openzeppelin contracts for our foundry project:
forge install openzeppelin/openzeppelin-contracts Foundry installs all dependencies as git submodules under the directory of "lib". And to make it easier to import the dependencies, let's create a remappings.txt file with the following contents:
openzeppelin-contracts=lib/openzeppelin-contractsWith the remappings.txt file above, we can import the ERC721 contract from Openzeppelin by the following import statement :
import "openzeppelin-contracts/contracts/token/ERC721/ERC721.sol";The ERC721 Contract
Create a new file named "MyNFT.sol" under the directory of "src". The content in the file is as follows:
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import "openzeppelin-contracts/contracts/token/ERC721/ERC721.sol";
import "openzeppelin-contracts/contracts/access/Ownable.sol";
contract MyNFT is ERC721, Ownable{
string private _URIBase;
constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {
_transferOwnership(msg.sender);
}
function mint(address to, uint256 tokenId) public onlyOwner {
_safeMint(to, tokenId);
}
function setBaseURI(string memory baseURI_) public onlyOwner {
_URIBase = baseURI_;
}
function _baseURI() internal view override returns (string memory) {
return _URIBase;
}
}Deploy Your ERC721 Contract
If everything goes well, forge will print out the address of the deployed contract and the transaction hash for the deployment.
Mint An NFT
We can use cast from foundry to interact with our ERC721 contract. Let's mint an NFT with cast:
We can also verify the owner of this newly minted NFT by using cast again:
Last updated