ERC-2309 · Final(最终) · ERC · 2019-10-08
ERC-2309: ERC-721 Consecutive Transfer Extension
一个可选的 ERC-721 事件 ConsecutiveTransfer,用一条日志报告整段 token ID 的铸造、转移或销毁,使超大规模的 NFT 批量操作不必为每个代币发出一个 Transfer 事件。
它解决什么问题?
ERC-721 规定,任何 NFT 的所有权发生变化时都必须发出 Transfer 事件。索引器、市场和区块浏览器都依赖这些事件来判断谁拥有什么。
这条规则让大批量操作变得昂贵。合约可以借助巧妙的数据结构在一笔交易中铸造一百万个代币,但在循环中发出一百万个 Transfer 事件会耗尽 gas。ERC-2309 为这类合约提供了一个标准事件,一次性描述一整段连续的 token ID。
它如何运作
ERC-2309 只定义了一个事件,别无其他。它不规定如何实现批量铸造或转移,只规定如何对外宣告:
event ConsecutiveTransfer(
uint256 indexed fromTokenId,
uint256 toTokenId,
address indexed fromAddress,
address indexed toAddress
);
规则:
fromTokenId到toTokenId必须是一段连续的 ID。- 铸造使用
fromAddress == address(0);销毁使用toAddress == address(0)。 fromTokenId、fromAddress和toAddress是 indexed;toTokenId不是,它位于日志数据中。- 调用者必须拥有该范围内的每个代币,或者是获批的操作者。
- 为一组代币发出
ConsecutiveTransfer时,不得再为它们发出Transfer。合约仍可对普通的单个代币转移使用Transfer。
该事件也适用于单个代币:ConsecutiveTransfer(1, 1, address(0), alice) 铸造代币 1。
示例代码
批量铸造时发出该事件(为便于说明,簿记逻辑做了简化):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract BatchNFT {
event ConsecutiveTransfer(
uint256 indexed fromTokenId,
uint256 toTokenId,
address indexed fromAddress,
address indexed toAddress
);
uint256 public nextId = 1;
// A real contract stores ownership compactly, e.g. one entry per batch.
mapping(uint256 => address) internal batchOwner; // keyed by first id of batch
function mintBatch(address to, uint256 quantity) external {
require(quantity > 0, "qty");
uint256 first = nextId;
uint256 last = first + quantity - 1;
batchOwner[first] = to;
nextId = last + 1;
emit ConsecutiveTransfer(first, last, address(0), to); // one log for the whole range
}
}
在索引器中监听(ethers v6):
import { Contract, JsonRpcProvider } from "ethers";
const provider = new JsonRpcProvider(process.env.RPC_URL);
const nft = new Contract(nftAddress, [
"event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress)",
], provider);
nft.on("ConsecutiveTransfer", (fromId, toId, from, to) => {
console.log(`tokens ${fromId}..${toId}: ${from} -> ${to}`);
});