ERC1155多代币标准
ERC1155结合了ERC20和ERC721的能力,这是一个标准接口,支持开发同质化的、半同质化的、非同质化的代币和其他配置的通用智能合约。
IERC1155接口
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
// IERC1155接口同样继承了IERC165接口
interface IERC1155 is IERC165 {
TransferSingle事件
// 转移代币后触发事件,记录转移信息
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
TransferBatch事件
// 批量转移代币后触发事件,记录转移信息
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
ApprovalForAll事件
// 授权approve后触发事件,记录授权信息
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
URI事件
// URI的值改变时触发该事件,记录信息
event URI(string value, uint256 indexed id);
balanceOf函数
// 获取account账户对应代币id拥有的数量
function balanceOf(address account, uint256 id) external view returns (uint256);
balanceOfBatch函数
// 获取账户列表对用的token余额,相当于多次balanceOf
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
setApprovalForAll函数
// 设置给operate的授权
function setApprovalForAll(address operator, bool approved) external;
isApprovedForAll函数
// 判断operate是否有account账号的授权
function isApprovedForAll(address account, address operator) external view returns (bool);
safeTransferFrom函数
// 从from账户转移amount数量的代币id到to地址
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
safeBatchTransferFrom函数
// 批量转移token,相当于调用多次safeTransfer
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
ERC1155
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// 代币id与拥有者地址及其该代币余额的映射
mapping(uint256 => mapping(address => uint256)) private _balances;
// 地址之间的授权状态的映射
mapping(address => mapping(address => bool)) private _operatorApprovals;
// 相同类型的代币 _uri是一致的
string private _uri;
// 构造函数 初始化uri
constructor(string memory uri_) {
_setURI(uri_);
}