ERC721 是一种用于创建非同质化代币(NFT)的以太坊标准。与 ERC20 标准不同,ERC721 代币是独特的,每个代币都有其独特的属性和价值。
不可互换/独特性:
元数据(Metadata):
所有权(Ownership):
pragma solidity ^0.8.0;
// IERC721 ERC721 标准要求实现 ERC165
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
interface IERC721Metadata {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
// 返回 给定资产的唯一统一资源标识符(URI),通常指向一个符合“ERC721元数据JSON模式”的JSON文件。
function tokenURI(uint256 _tokenId) external view returns (string);
}
ERC721元数据 JSON 参考模式:
{
"title": "Asset Metadata",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Identifies the asset to which this NFT represents"
},
"description": {
"type": "string",
"description": "Describes the asset to which this NFT represents"
},
"image": {
"type": "string",
"description": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive."
}
}
}
以下是一个基于 OpenZeppelin 代码实现的简单的 ERC721 代币合约示例:
// contracts/GameItem.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract GameItem is ERC721URIStorage {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
constructor() ERC721("GameItem", "ITM") {}
function awardItem(address player, string memory tokenURI) public returns (uint256) {
uint256 newItemId = _tokenIds.current();
_mint(player, newItemId);
_setTokenURI(newItemId, tokenURI);
_tokenIds.increment();
return newItemId;
}
}
ERC721 代币已经在许多领域得到了应用,特别是在数字艺术、游戏、DEFI 等领域。例如,CryptoKitties 是最早使用 ERC721 标准的知名项目之一,允许用户购买、繁殖和交易独特的数字猫。 Uniswap V3 通过 NFT 来表示用户提供的独一无二的流动性。
ERC721 标准为创建和管理独特的数字资产提供了一个强大的工具。