ERC1155 是由 Enjin 的 CTO Witek Radomski 提出。以下是主要合约代码
interface ERC1155 {
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _value, uint256 indexed _id);
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external;
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
function setApprovalForAll(address _operator, bool _approved) external;
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
从上边合约代码可以看到 ERC1155 与 ERC721 的主要却别在于 TransferSingle
和 TransferBatch
(包括其他 Batch 字段)。1155 会有这样区别的原因主要因为:
我们可以将 ERC721 想象成一副扑克牌,52 张牌每一张都不一样。而 ERC1155 则类似于一副麻将牌,虽然有不同的「条」「饼」「万」,但会有 4 张一样的「一万」和「九筒」。不同的「条」「饼」「万」之间是非同质性的,而 4 张一样的「一万」则是同质性的。
和 ERC721 一样,ERC1155 也规范了 transfer 的 _to
指向合约地址,需要支持的接口
interface ERC1155TokenReceiver {
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4);
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4);
}
ERC1155 MetaData 接口
interface ERC1155Metadata_URI {
function uri(uint256 _id) external view returns (string memory);
}
Metadata 指向 JSON 文件格式,关于 Metadata 我们在 ERC721 标准里有介绍
{
"title": "Token Metadata",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Identifies the asset to which this token represents"
},
"decimals": {
"type": "integer",
"description": "The number of decimal places that the token amount should display - e.g. 18, means to divide the token amount by 1000000000000000000 to get its user representation."
},
"description": {
"type": "string",
"description": "Describes the asset to which this token represents"
},
"image": {
"type": "string",
"description": "A URI pointing to a resource with mime type image/* representing the asset to which this token represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive."
},
"properties": {
"type": "object",
"description": "Arbitrary properties. Values may be strings, numbers, object or arrays."
}
}
}
ERC1155 的应用场景有很多,比如我们玩儿《魔兽争霸》游戏,游戏中的每个英雄人物需要设计成 ERC721,而士兵,木材资源等,则是同质化的类型。如果每个人物、事物都用 ERC721 来设计,那么成本将非常高。