本篇是這個系列的第一篇:創(chuàng)建一個 NFT 合約并實(shí)現(xiàn)交易。 注:這里主要聚焦在 The Graph 的使用,自己實(shí)現(xiàn) NFT 項(xiàng)目是為了方便解析事件,不關(guān)注 NFT 合約的安全等
創(chuàng)建合約 1、實(shí)現(xiàn)一個標(biāo)準(zhǔ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(
) internal view override returns (string memory) { return baseURI; } function setBaseURI(string calldata uri) external { baseURI = uri; } function safeMint(address to, uint256 tokenId) external { _safeMint(to, tokenId); }}
2、實(shí)現(xiàn)一個標(biāo)準(zhǔ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、實(shí)現(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) 部署并驗(yàn)證合約 至此,本篇文章就結(jié)束了。如果有問題可以留言,我看到后會回復(fù)留言。 |