行业知识
OpenZeppelin——ERC721
ERC721���一个代币标准,ERC721官方简要解释是Non-Fungible Tokens,简写为NFT,多翻译为非同质化代币。
那怎么理解非同质化代币呢?
非同质化代表独一无二,以卡牌游戏为例,盲盒开出的英雄属性是随机生成,尽管职业相同,但每个英雄不一样,一个英雄对应一个TokenId,就是一个NFT,英雄之间是不能置换的,因为价值不同。这种独特性使得某些稀有英雄具有收藏价值,也因此受到追捧。
ERC20代币是同质化代币,是可置换的,且可细分为N份(1 = 10 * 0.1), 而ERC721的Token最小的单位为1,无法再分割。
如果同一个集合的两个物品具有不同的特征,这两个物品是非同质化的,而同质化是某个部分或数量可以被另一个同等部分或数量所代替。
非同质性其实广泛存在于我们的生活中,如每一片树叶,宠物商店的每一只宠物,歌手所演唱的歌曲,花店里不同的花等等。
OpenZeppelin合约库为NFT的开发提供了一套完整的接口和实现标准(即ERC721系列),我们在智能合约中通过实现这些协议来满足安全、开放、透明等要求,同时该协议也帮助我们实现了基本的转账、铸造、销毁、查询等业务功能,无需我们重复造轮子,我们只需要继承标准库即可。接下来将对一般场景下用到的接口和函数展开介绍,末尾也会提供一个我认为标准的实现案例供各位参考。
一、ERC721相关
在介绍ERC721之前,我们先了解一下IERC721。IERC721是以太坊社区的共识和标准(EIP721),定义了一组函数,但是没有函数体,是对业务的抽象,需要合约来实现它,而官方提供的标准实现就是ERC721。通常发布一个NFT合约的一般做法是继承ERC721,而不会自己来实现IERC721,一是减少重复造轮子,二是用官方的更加安全,除非我们的业务比较特殊,官方实现无法满足业务需求,针对这种情况我们可以对函数进行重写或新增函数。合约通过实现IERC721来对外申明它满足EIP721标准,可以提供基本的交易、mint、查询等服务。同时,外部合约可以通过接口调用的方式与合约进行数据交互,如查询用户账户的NFT数量:
IERC721(address nft).balanceOf(address owner);
所有实现了IERC721接口的合约,与它交互的方式都可以通过以上方式进行,而无需关注具体的函数代码实现。类似的标准有IERC721Metadata、IERC721Enumerable、IERC721Receiver等等。ERC721 的合约主要使用了 4 个接口合约:IERC721.sol, IERC721Receiver.sol, IERC721Metadata.sol,和间接引用的 ERC165 的 IERC165.sol。我们将逐个介绍这 4 个接口合约。
二、ERC721/ERC721Upgradeable
ERC721Upgradeable与ERC721的区别在于合约初始化方式,以及命名方式上增加了“Upgradeable”后缀,它们在函数实现(功能)上并没有本质区别。Upgradeable合约的优势在于合约的可升级。通常来讲,区块链最让人耳熟能详的就是不可窜改性,任何合约上链后就不可以更改,这也赋予了区块链最强大的特性,但谁也不能保证自己写的合约能一直满足业务发展需求,这也不符合软件产业迅速迭代的特质。可升级合约就是为解决此问题而设计。
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)pragma solidity ^0.8.20;import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";import {ERC165Upgradeable} from "../../utils/introspection/ERC165Upgradeable.sol";import {IERC721Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";import {Initializable} from "../../proxy/utils/Initializable.sol";/** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */abstract contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721, IERC721Metadata, IERC721Errors { using Strings for uint256; /// @custom:storage-location erc7201:openzeppelin.storage.ERC721 struct ERC721Storage { // Token name string _name; // Token symbol string _symbol; mapping(uint256 tokenId => address) _owners; mapping(address owner => uint256) _balances; mapping(uint256 tokenId => address) _tokenApprovals; mapping(address owner => mapping(address operator => bool)) _operatorApprovals; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC721")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant ERC721StorageLocation = 0x80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab0079300; function _getERC721Storage() private pure returns (ERC721Storage storage $) { assembly { $.slot := ERC721StorageLocation } } /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { ERC721Storage storage $ = _getERC721Storage(); $._name = name_; $._symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual returns (uint256) { ERC721Storage storage $ = _getERC721Storage(); if (owner == address(0)) { revert ERC721InvalidOwner(address(0)); } return $._balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual returns (address) { return _requireOwned(tokenId); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual returns (string memory) { ERC721Storage storage $ = _getERC721Storage(); return $._name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual returns (string memory) { ERC721Storage storage $ = _getERC721Storage(); return $._symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual returns (string memory) { _requireOwned(tokenId); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual { _approve(to, tokenId, _msgSender()); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual returns (address) { _requireOwned(tokenId); return _getApproved(tokenId); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual returns (bool) { ERC721Storage storage $ = _getERC721Storage(); return $._operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual { if (to == address(0)) { revert ERC721InvalidReceiver(address(0)); } // Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here. address previousOwner = _update(to, tokenId, _msgSender()); if (previousOwner != from) { revert ERC721IncorrectOwner(from, tokenId, previousOwner); } } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual { transferFrom(from, to, tokenId); _checkOnERC721Received(from, to, tokenId, data); } /** * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist * * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the * core ERC721 logic MUST be matched with the use of {_increaseBalance} to keep balances * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`. */ function _ownerOf(uint256 tokenId) internal view virtual returns (address) { ERC721Storage storage $ = _getERC721Storage(); return $._owners[tokenId]; } /** * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted. */ function _getApproved(uint256 tokenId) internal view virtual returns (address) { ERC721Storage storage $ = _getERC721Storage(); return $._tokenApprovals[tokenId]; } /** * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in * particular (ignoring whether it is owned by `owner`). * * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this * assumption. */ function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) { return spender != address(0) && (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender); } /** * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner. * Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets * the `spender` for the specific `tokenId`. * * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this * assumption. */ function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual { if (!_isAuthorized(owner, spender, tokenId)) { if (owner == address(0)) { revert ERC721NonexistentToken(tokenId); } else { revert ERC721InsufficientApproval(spender, tokenId); } } } /** * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override. * * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that * a uint256 would ever overflow from increments when these increments are bounded to uint128 values. * * WARNING: Increasing an account's balance using this function tends to be paired with an override of the * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership * remain consistent with one another. */ function _increaseBalance(address account, uint128 value) internal virtual { ERC721Storage storage $ = _getERC721Storage(); unchecked { $._balances[account] += value; } } /** * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update. * * The `auth` argument is optional. If the value passed is non 0, then this function will check that * `auth` is either the owner of the token, or approved to operate on the token (by the owner). * * Emits a {Transfer} event. * * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}. */ function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) { ERC721Storage storage $ = _getERC721Storage(); address from = _ownerOf(tokenId); // Perform (optional) operator check if (auth != address(0)) { _checkAuthorized(from, auth, tokenId); } // Execute the update if (from != address(0)) { // Clear approval. No need to re-authorize or emit the Approval event _approve(address(0), tokenId, address(0), false); unchecked { $._balances[from] -= 1; } } if (to != address(0)) { unchecked { $._balances[to] += 1; } } $._owners[tokenId] = to; emit Transfer(from, to, tokenId); return from; } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal { if (to == address(0)) { revert ERC721InvalidReceiver(address(0)); } address previousOwner = _update(to, tokenId, address(0)); if (previousOwner != address(0)) { revert ERC721InvalidSender(address(0)); } } /** * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual { _mint(to, tokenId); _checkOnERC721Received(address(0), to, tokenId, data); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * This is an internal function that does not check if the sender is authorized to operate on the token. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal { address previousOwner = _update(address(0), tokenId, address(0)); if (previousOwner == address(0)) { revert ERC721NonexistentToken(tokenId); } } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal { if (to == address(0)) { revert ERC721InvalidReceiver(address(0)); } address previousOwner = _update(to, tokenId, address(0)); if (previousOwner == address(0)) { revert ERC721NonexistentToken(tokenId); } else if (previousOwner != from) { revert ERC721IncorrectOwner(from, tokenId, previousOwner); } } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients * are aware of the ERC721 standard to prevent tokens from being forever locked. * * `data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is like {safeTransferFrom} in the sense that it invokes * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `tokenId` token must exist and be owned by `from`. * - `to` cannot be the zero address. * - `from` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId) internal { _safeTransfer(from, to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual { _transfer(from, to, tokenId); _checkOnERC721Received(from, to, tokenId, data); } /** * @dev Approve `to` to operate on `tokenId` * * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is * either the owner of the token, or approved to operate on all tokens held by this owner. * * Emits an {Approval} event. * * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. */ function _approve(address to, uint256 tokenId, address auth) internal { _approve(to, tokenId, auth, true); } /** * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not * emitted in the context of transfers. */ function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual { ERC721Storage storage $ = _getERC721Storage(); // Avoid reading the owner unless necessary if (emitEvent || auth != address(0)) { address owner = _requireOwned(tokenId); // We do not use _isAuthorized because single-token approvals should not be able to call approve if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) { revert ERC721InvalidApprover(auth); } if (emitEvent) { emit Approval(owner, to, tokenId); } } $._tokenApprovals[tokenId] = to; } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Requirements: * - operator can't be the address zero. * * Emits an {ApprovalForAll} event. */ function _setApprovalForAll(address owner, address operator, bool approved) internal virtual { ERC721Storage storage $ = _getERC721Storage(); if (operator == address(0)) { revert ERC721InvalidOperator(operator); } $._operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned). * Returns the owner. * * Overrides to ownership logic should be done to {_ownerOf}. */ function _requireOwned(uint256 tokenId) internal view returns (address) { address owner = _ownerOf(tokenId); if (owner == address(0)) { revert ERC721NonexistentToken(tokenId); } return owner; } /** * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the * recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param data bytes optional data to send along with the call */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) private { if (to.code.length > 0) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) { if (retval != IERC721Receiver.onERC721Received.selector) { revert ERC721InvalidReceiver(to); } } catch (bytes memory reason) { if (reason.length == 0) { revert ERC721InvalidReceiver(to); } else { /// @solidity memory-safe-assembly assembly { revert(add(32, reason), mload(reason)) } } } } }} 函数说明:
- balanceOf(address owner): 查询特定账户余额,返回持有的令牌(tokenIds)数量。
- ownerOf(uint256 tokenId):查询特定令牌(tokenId)持有者账户地址。
- safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data):将令牌从`from`账户安全转移至`to`账户,安全性体现在函数逻辑中会判断`to`地址是否是合约地址,如果是合约地址(代码大小 > 0),验证其是否有实现IERC721Receiver接口中的onERC721Received函数,防止令牌卡在合约中(`to`地址无法将令牌转移出去)。同时,当前操作者必须有令牌的操作权限(即操作者是令牌拥有者或者得到拥有者的授权)。一般由第三方进行调用,将令牌从`from`账户转移至`to`账户。
- approve(address to, uint256 tokenId):批准某个地址操作指定令牌(必须存在)的权限,该函数会检查是否当前操作账户是否是令牌的持有者或有操作权限。
- setApprovalForAll(address operator, bool approved):工作方式与之前的approve函数类似,但该函数不是批准单个令牌的地址,而是批准和处理特定地址拥有的所有令牌,且包括撤销操作权限。当approved为true代表授权,为false代表撤销操作权限。
- getApproved(uint256 tokenId):类似于ERC-20接口中的allowance函数。返回指定令牌的批准address 。
- isApprovedForAll(address owner, address operator):类似于上面的函数。它查询一个address是否是另一个address的授权operator 。
三、ERC165/ERC165Upgradeable
EIP165(以太坊改进建议第 165 条),它的目的是创建一个标准方法来发布和检测智能合约实现的接口。讲一个真实事件,PeopleDAO 有个朋友错转了 4000w 枚 PEOPLE 到 Token 合约。但合约没有实现转出 Token 的功能,只能进不能出,这些 Token 直接锁***在里面销毁了。试想一下,如果在转账的时候自动判断接收方合约是否实现了相应的接口,没实现的话就 revert 交易,很多错转 Token 的悲剧都不会发生。EIP165 就是干这个的,而 ERC165 就是 EIP165 的实现。
IERC165 是 ERC165 的接口合约,只有一个supportsInterface()函数,输入想查询的接口的 interfaceId,返回一个 bool 告诉你合约是否实现了该接口。
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)pragma solidity ^0.8.20;import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";import {Initializable} from "../../proxy/utils/Initializable.sol";/** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` */abstract contract ERC165Upgradeable is Initializable, IERC165 { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC165).interfaceId; }}获取接口ID的核心代码:
type(IERC165).interfaceId
除上述获取interfaceID方式外,计算方式有两种,如:
bytes4(keccak256('supportsInterface(bytes4)'));
ERC165.supportsInterface.selector;
当接口中有多个函数时,它的接口ID为函数选择器的异或值,如:
bytes4(keccak256('supportsInterface1(bytes4)')) ^ bytes4(keccak256('supportsInterface(bytes4)'));
ERC165.supportsInterface1.selector ^ ERC165.supportsInterface2.selector;
下面我们来看一个测试案例:
// SPDX-License-Identifier: MITpragma solidity ^0.8.19;import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";import {ERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";contract EIP165 is ERC721Upgradeable{ function ierc165() external view returns (bool){ bytes4 interfaceId = type(IERC165).interfaceId; return IERC165(address(this)).supportsInterface(interfaceId); } function ierc721() external view returns (bool){ bytes4 interfaceId = type(IERC721).interfaceId; return IERC165(address(this)).supportsInterface(interfaceId); }}函数说明:
- ierc165() external view returns (bool):判断当前合约是否有实现IERC165接口,返回true则表示已经实现。
- ierc721() external view returns (bool):判断当前合约是否有实现IERC721接口,返回true则表示已经实现。
运行结果:
可能有的同学会说,案例中的EIP165合约并没有实现supportsInterface()函数,是因为继承了它的父类ERC721Upgradeable中的supportsInterface()函数。
四、ERC721Holder/ERC721HolderUpgradeable
ERC721Holder实现的接口是IERC721Receiver,这个接口只包含一个函数,那就是onERC721Received。当我们在合约中继承ERC721Holder合约,意味着对外申明该合约可以接受令牌。否则,在调用ERC721-safeTransferFrom、ERC721-_safeMint、ERC721-_safeTransfer函数时会发生错误,导致交易被撤回,以ERC721-safeTransferFrom函数实现为例,观察其细节部分:
/** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual { transferFrom(from, to, tokenId); _checkOnERC721Received(from, to, tokenId, data); }/** * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the * recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param data bytes optional data to send along with the call */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) private { if (to.code.length > 0) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) { if (retval != IERC721Receiver.onERC721Received.selector) { revert ERC721InvalidReceiver(to); } } catch (bytes memory reason) { if (reason.length == 0) { revert ERC721InvalidReceiver(to); } else { /// @solidity memory-safe-assembly assembly { revert(add(32, reason), mload(reason)) } } } } }当然,onERC721Received()函数并不能保证接收方合约中有取出令牌的功能,因为它只是检查接收方是否有实现该函数。那么它的意义何在?这个方法可以告诉我们,接收方合约的开发者至少知道这个方法,这意味着他们必须进一步实现将令牌转出合约的功能。
五、IERC721Metadata
IERC721Metadata 是 IERC721 的拓展接口,申明了三个查询 metadata 的常用函数:
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)pragma solidity ^0.8.20;import {IERC721} from "../IERC721.sol";/** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory);}函数说明:
- name():返回令牌名称;
- symbol():返回令牌代号;
- tokenURI():通过 tokenId 查询 metadata 所在 url。
以上三个函数在ERC721中都有被实现,我们只需进行拿来主义即可。
六、ERC721实例
// SPDX-License-Identifier: MITpragma solidity ^0.8.19;import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";import "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";contract MyNFT is ERC721EnumerableUpgradeable, AccessControlUpgradeable, ERC721HolderUpgradeable{ //bytes4 public constant IERC165_INTERFACE_ID = type(IERC165).interfaceId; uint256 private _nextTokenId; function initialize(string memory _name,string memory _symbol) public initializer { __ERC721_init(_name, _symbol); __AccessControl_init(); __ERC721Holder_init(); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); } function mint() external returns(uint256 tokenId) { tokenId = _nextTokenId++; _safeMint(msg.sender, tokenId); } function getTokenIdCounter() external view returns (uint256) { return _nextTokenId; } function supportsInterface(bytes4 interfaceId) public view override(ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); }}合约继承了ERC721EnumerableUpgradeable, AccessControlUpgradeable, ERC721HolderUpgradeable,其中:
- ERC721EnumerableUpgradeable:提供令牌的基本操作,如查询、授权、转账、铸造等功能;
- AccessControlUpgradeable:对函数操作权限进行管理,角色对应权限,合约对调用初始化函数的调用者赋予DEFAULT_ADMIN_ROLE(最高权限),其它权限由此用户进行赋予。
- ERC721HolderUpgradeable:继承其onERC721Received()函数,申明合约可以接受令牌。
函数说明:
- initialize(string memory _name,string memory _symbol):可升级合约的初始化函数,只能调用一次,包含令牌、权限、接受令牌、角色授权的初始化;
- mint():向调用者账户转移一枚令牌,同时总供应量+1,tokenId+1;
- getTokenIdCounter():查询当前已铸造的令牌数量;
- supportsInterface(bytes4 interfaceId):查询检测合约是否实现某个接口。
部署结果:
下一篇:英雄联盟服务器哪里买号?