pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract MyNFT is ERC721URIStorage {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
constructor() ERC721("MyNFT", "MNFT") {}
function mintNFT(address recipient, string memory tokenURI) public returns (uint256) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(recipient, newItemId);
_setTokenURI(newItemId, tokenURI);
return newItemId;
}
}
在上述示例中,我们使用了OpenZeppelin的ERC721URIStorage合约,该合约允许我们将NFT的元数据URI存储在链上。此外,我们还使用了OpenZeppelin的Counters库来生成唯一的NFT ID。
在合约中,我们定义了一个mintNFT函数,该函数接受一个接收者地址和一个元数据URI,然后铸造出一个新的NFT。
现在我们可以使用Solidity编译器来编译我们的合约。我们可以使用Remix等在线Solidity IDE或使用本地Solidity编译器。
编译合约时,我们需要指定Solidity编译器的版本号。在示例合约中,我们使用^0.8.0版本,因此我们需要确保我们的Solidity编译器是该版本或更高版本。
如果编译没有错误,则会生成一个编译后的合约文件(通常为.sol文件)。
现在我们可以使用web3.js或其他以太坊编程库部署我们的合约到测试链或主网上。