本篇是這個系列的第一篇:創(chuàng)建一個 NFT 合約并實現(xiàn)交易。
注:這里主要聚焦在 The Graph 的使用,自己實現(xiàn) NFT 項目是為了方便解析事件,不關注 NFT 合約的安全等
創(chuàng)建合約
1、實現(xiàn)一個標準的 ERC721 合約,通過這個合約發(fā)行 NFT,用 The Graph 解析 Transfer 事件。
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";contract ERC721Token is ERC721 { string public baseURI; constructor() ERC721(unicode"小貓", "LCAT") { } function _baseURI(2、實現(xiàn)一個標準的 ERC20 代幣,用來買賣我們上面發(fā)行的 NFT。
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";contract ERC20Token is ERC20 { address public immutable owner; constructor() ERC20(unicode"貓幣", "CAT") { owner = msg.sender; _mint(owner, 100000 * 10 ** decimals()); } function mint(address account, uint256 amount) public { require(msg.sender == owner, "mint: only owner"); _mint(account, amount); }}3、實現(xiàn)一個 Market 合約,買賣 NFT
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";import "@openzeppelin/contracts/token/ERC721/IERC721.sol";contract Market { IERC20 public immutable TOKEN20; IERC721 public immutable TOKEN721; mapping(uint256 => uint256) public priceOf; mapping(uint256 => address) public sellerOf; constructor(address token20, address token721) { TOKEN20 = IERC20(token20); TOKEN721 = IERC721(token721); } event BuyEvent(address user, uint256 tokenId, uint256 amount); event SellEvent(address user, uint256 tokenId, uint256 price); function buy(uint256 tokenId, uint256 amount) external { uint256 price = priceOf[tokenId]; require(price > 0 && price <= amount, "buy: error price or amount"); require(sellerOf[tokenId] != address(0), "buy: seller address zero"); TOKEN20.transferFrom(msg.sender, sellerOf[tokenId], price); TOKEN721.transferFrom(address(this), msg.sender, tokenId); priceOf[tokenId] = 0; sellerOf[tokenId] = address(0); emit BuyEvent(msg.sender, tokenId, price); } function sell(uint256 tokenId, uint256 price) external { TOKEN721.transferFrom(msg.sender, address(this), tokenId); sellerOf[tokenId] = msg.sender; priceOf[tokenId] = price; emit SellEvent(msg.sender, tokenId, price); }}4、請使用你熟悉的工具(Remix/truffle/hardhat/foundry) 部署并驗證合約
使用 hardhat 部署合約,這里部署到 mumbai 網(wǎng)絡,也可部署到 bsc 測試網(wǎng)等
申請 apikey(驗證合約需要)
重點:apikey 需要去 測試網(wǎng) 對應的 主網(wǎng)區(qū)塊鏈瀏覽器 申請,需要注冊登錄
配置 hardhat.config.js
至此,本篇文章就結束了。如果有問題可以留言,我看到后會回復留言。
歡迎光臨 WDlinux官方論壇 (http://www.fsowen.com/bbs/) | Powered by Discuz! 7.2 |