0Pricing
Blockchain Smart Contracts with Solidity · 课时

ERC-1155 多代币标准

学习 ERC-1155 多代币标准,了解单个合约如何同时管理同质化、半同质化和非同质化代币,以便高效执行批量操作。

ERC-1155 多代币标准 是 CoddyKit 上的免费 Blockchain Smart Contracts with Solidity 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Blockchain Smart Contracts with Solidity 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why ERC-1155 Exists

ERC-20 manages one fungible token; ERC-721 manages unique NFTs. But a game may need thousands of item types mixing both. Deploying a separate contract per type is wasteful.

ERC-1155 is a single contract that can manage many token IDs at once, each of which can be fungible or non-fungible.

Token IDs as Categories

In ERC-1155 each token is identified by a numeric id. The same id can have a balance greater than one (fungible) or a supply of exactly one (non-fungible).

  • id = 1 with balance 500 = a fungible gold coin
  • id = 2 with balance 1 = a unique sword NFT

Core Balance Mapping

The heart of an ERC-1155 contract is a nested mapping from id to owner to balance.

mapping(uint256 => mapping(address => uint256)) private _balances;

function balanceOf(address account, uint256 id) public view returns (uint256) {
    return _balances[id][account];
}

Batch Balance Queries

A signature feature is balanceOfBatch, which returns many balances in one call, saving round trips.

function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
    public view returns (uint256[] memory)
{
    require(accounts.length == ids.length, 'length mismatch');
    uint256[] memory batch = new uint256[](accounts.length);
    for (uint256 i = 0; i < accounts.length; i++) {
        batch[i] = _balances[ids[i]][accounts[i]];
    }
    return batch;
}

Batch Transfers

ERC-1155 lets you move several token types in a single transaction with safeBatchTransferFrom. This is far cheaper than many separate ERC-20/721 transfers.

function safeBatchTransferFrom(
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) public {
    require(ids.length == amounts.length, 'length mismatch');
    for (uint256 i = 0; i < ids.length; i++) {
        _balances[ids[i]][from] -= amounts[i];
        _balances[ids[i]][to] += amounts[i];
    }
}

Approval For All

Instead of per-token approvals, ERC-1155 uses a single operator approval: setApprovalForAll grants an address permission to move every token you own.

mapping(address => mapping(address => bool)) private _operatorApprovals;

function setApprovalForAll(address operator, bool approved) public {
    _operatorApprovals[msg.sender][operator] = approved;
}

function isApprovedForAll(address owner, address operator) public view returns (bool) {
    return _operatorApprovals[owner][operator];
}

The Shared Metadata URI

ERC-1155 uses one URI template for all tokens. The placeholder {id} is replaced by the hex token id by clients.

Example: https://game.example/api/{id}.json

string private _uri = 'https://game.example/api/{id}.json';

function uri(uint256) public view returns (string memory) {
    return _uri;
}

Minting Tokens

Minting increases a balance for an id. The same internal logic works for both fungible (amount > 1) and non-fungible (amount = 1) tokens.

function _mint(address to, uint256 id, uint256 amount) internal {
    require(to != address(0), 'mint to zero');
    _balances[id][to] += amount;
    emit TransferSingle(msg.sender, address(0), to, id, amount);
}

event TransferSingle(address operator, address from, address to, uint256 id, uint256 value);

Safe Transfer Receiver Check

Like ERC-721, ERC-1155 protects against tokens being locked in contracts. A receiving contract must implement onERC1155Received and return its magic value, or the transfer reverts.

interface IERC1155Receiver {
    function onERC1155Received(
        address operator, address from,
        uint256 id, uint256 value, bytes calldata data
    ) external returns (bytes4);
}

Using OpenZeppelin

In practice you inherit the audited OpenZeppelin implementation rather than writing it from scratch.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import '@openzeppelin/contracts/token/ERC1155/ERC1155.sol';

contract GameItems is ERC1155 {
    uint256 public constant GOLD = 0;
    uint256 public constant SWORD = 1;

    constructor() ERC1155('https://game.example/api/{id}.json') {
        _mint(msg.sender, GOLD, 1000, '');
        _mint(msg.sender, SWORD, 1, '');
    }
}

When To Choose ERC-1155

Pick ERC-1155 when you have many token types, need batch operations, or mix fungible and non-fungible assets. Stick with ERC-20/721 for a single, simple asset where the extra complexity is not justified.

Quick Check

Test your understanding of ERC-1155.

Recap

You learned that ERC-1155 is a multi-token standard managing many IDs in one contract. Key points:

  • Nested id => owner => balance mapping
  • Batch queries and transfers save gas
  • Single operator approval and shared {id} URI
  • Safe-transfer receiver checks protect against locked tokens

It is the standard of choice for games and marketplaces with many asset types.

常见问题解答

「ERC-1155 多代币标准」课时是免费的吗?

是的 — 「ERC-1155 多代币标准」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Blockchain Smart Contracts with Solidity 课程的其余内容,请升级到 CoddyKit PRO。 Blockchain Smart Contracts with Solidity 课程共包含 4 节课。

「ERC-1155 多代币标准」这节课中我会学到什么?

学习 ERC-1155 多代币标准,了解单个合约如何同时管理同质化、半同质化和非同质化代币,以便高效执行批量操作。 你通过在浏览器中直接运行的动手代码来练习 Blockchain Smart Contracts with Solidity,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Blockchain Smart Contracts with Solidity 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Blockchain Smart Contracts with Solidity 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「ERC-1155 多代币标准」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Blockchain Smart Contracts with Solidity 课中编写并运行代码吗?

能。每节 Blockchain Smart Contracts with Solidity 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. ERC-20 同质化代币标准
  2. 实施 ERC-20 代币
  3. ERC-721 非同质化代币(NFT)
  4. ERC-1155 多代币标准
← 返回 Blockchain Smart Contracts with Solidity