0Pricing
Blockchain Smart Contracts with Solidity · Leçon

Standard multi-jetons ERC-1155

Découvrez le standard multi-jetons ERC-1155, qui permet à un seul contrat de gérer simultanément des jetons fongibles, semi-fongibles et non fongibles pour des opérations groupées économes en gas.

Standard multi-jetons ERC-1155 est une leçon Blockchain Smart Contracts with Solidity gratuite sur CoddyKit. Ceci est la leçon 4 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Blockchain Smart Contracts with Solidity, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Blockchain Smart Contracts with Solidity comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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.

Questions Fréquemment Posées

La leçon « Standard multi-jetons ERC-1155 » est-elle gratuite ?

Oui — le texte complet de « Standard multi-jetons ERC-1155 » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Blockchain Smart Contracts with Solidity, passe à CoddyKit PRO. Le cours Blockchain Smart Contracts with Solidity comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Standard multi-jetons ERC-1155 » ?

Découvrez le standard multi-jetons ERC-1155, qui permet à un seul contrat de gérer simultanément des jetons fongibles, semi-fongibles et non fongibles pour des opérations groupées économes en gas. Tu pratiques Blockchain Smart Contracts with Solidity avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Blockchain Smart Contracts with Solidity ?

Aucune expérience préalable n'est requise. Blockchain Smart Contracts with Solidity sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 4 sur 4.

Combien de temps prend la leçon « Standard multi-jetons ERC-1155 » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Blockchain Smart Contracts with Solidity ?

Oui. Chaque leçon Blockchain Smart Contracts with Solidity inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Standard de jetons fongibles ERC-20
  2. Mise en œuvre d’un jeton ERC-20
  3. Jetons non fongibles ERC-721 (NFT)
  4. Standard multi-jetons ERC-1155
← Retour à Blockchain Smart Contracts with Solidity