Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article covers ERC1155.

Before learning about ERC1155, I recommend understanding ERC20 and ERC721. The following articles explain ERC20 and ERC721.

[ERC20] A Beginner's Guide to ERC20

[ERC721] A Beginner's Guide to ERC721

What is ERC1155?

ERC1155 is a token standard that combines the characteristics of ERC20 with the non-fungibility of ERC721.

Characteristics of ERC1155

ERC1155 is often associated with semi-fungible tokens. Simply put, it can manage multiple units of a token with a particular tokenId. Let's examine its characteristics one by one.

With ERC721, each tokenId corresponds to one token. With ERC1155, however, multiple token units can share one tokenId, as with ERC20 balances. This makes it possible to transfer multiple units associated with the same tokenId together.

Example

Suppose you want to sell several in-game items, such as swords, shields, and armor, on a marketplace. Under the ERC721 standard, you need to manage each item individually. For example, tokenId values 1–100 could represent swords, while values 101–200 could represent shields. With ERC1155, you can manage them by item type, using tokenId=1 for swords and tokenId=2 for shields.

EIP1155

What is an EIP?

So far, we have referred to ERC1155, but what is EIP1155?

EIP stands for Ethereum Improvement Proposals. These proposals specify standards for new Ethereum features and processes. A detailed explanation of EIPs is available here.

In simple terms:

EIP stands for Ethereum Improvement Proposals, which are proposals discussed to improve Ethereum. Because Ethereum is not controlled by any single party, anyone around the world can contribute to its development by submitting an EIP.

The number 1155 identifies the proposal.

The following page contains EIP1155. Explaining everything would make this article quite long, so this section focuses on the required functionality.

Required EIP1155 functions

Let's examine the required EIP1155 functions.

safeTransferFrom()
js
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;

Transfers the quantity specified by _value of the token identified by _id from the address specified by _from to the address specified by _to.

Requirements

  • _to must not be the zero address.
  • The caller must be _from or an operator approved to transfer the tokens identified by _id on its behalf.
  • The address specified by _from must hold at least _value units of the token identified by _id.
  • If _to is a contract address, the recipient contract must implement IERC1155Receiver's onERC1155Received() function for a single-token transfer.
safeBatchTransferFrom()
js
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external;

Transfers multiple tokens efficiently.

For each token in _ids, transfers the quantity at the corresponding index in _values from the address specified by _from to the address specified by _to.

Example

js
_ids = [5, 8, 13]
_values = [100, 20, 50]

The example above results in the following transfers.

  • Transfer 100 units of token ID 5 from _from to _to.
  • Transfer 20 units of token ID 8 from _from to _to.
  • Transfer 50 units of token ID 13 from _from to _to.

Requirements

  • The _ids and _values arrays must have the same length.
  • If _to is a contract address, the recipient must support the appropriate IERC1155Receiver callback, normally onERC1155BatchReceived() for batch transfers.
balanceOf()
js
function balanceOf(address _owner, uint256 _id) external view returns (uint256);

Returns the quantity of the token identified by _id held by the address specified by _owner.

Requirements

  • _owner must not be the zero address.
balanceOfBatch()
js
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);

Returns the balances held by each address in _owners for the corresponding token ID at the same index in _ids.

Example

js
_owners = [0x123..., 0xabc..., 0xXYZ...]
_ids = [5, 8, 13]

The example above returns an array containing the following values.

  • Balance of token ID 5 held by 0x123....
  • Balance of token ID 8 held by 0xabc....
  • Balance of token ID 13 held by 0xXYZ....

Requirements

  • The _owners and _ids arrays must have the same length.
setApprovalForAll()
js
function setApprovalForAll(address _operator, bool _approved) external;

Grants or revokes permission for the address specified by _operator to transfer ERC1155 tokens held by the caller of setApprovalForAll().

If _approved is true, permission is granted; if it is false, permission is revoked.

Requirements

  • In the implementation discussed here, the _operator address must differ from the caller of setApprovalForAll().
isApprovedForAll()
js
function isApprovedForAll(address _owner, address _operator) external view returns (bool);

Checks whether the address specified by _operator has permission to transfer ERC1155 tokens held by the address specified by _owner.

Returns true if permission has been granted, or false otherwise.

EIP1155 events

Next, let's examine the EIP1155 events.

TransferSingle
js
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);

Emitted when an ERC1155 token is transferred.

TransferBatch
js
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);

Emitted when multiple ERC1155 tokens are transferred in a batch.

ApprovalForAll
js
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);

Emitted when the address specified by _operator is granted or loses permission to transfer ERC1155 tokens held by _owner.

URI
js
event URI(string _value, uint256 indexed _id);

Emitted when the URI of the ERC1155 token identified by _id changes to the value specified by _value.

The value emitted in this event matches the value returned by the uri() function of IERC1155MetadataURI for that token ID.

ERC1155TokenReceiver

Next, let's examine ERC1155TokenReceiver.

onERC1155Received()
js
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4);

A callback used to check whether a safeTransferFrom() transfer is accepted.

If the recipient is a contract that does not support ERC1155, transferred tokens could become permanently inaccessible without a receiver check. To prevent this, the token contract checks whether the recipient contract supports receiving ERC1155 tokens.

Requirements

  • _operator must identify the EOA or contract authorized to perform the transfer.
  • _from must identify the owner of the ERC1155 tokens being transferred, except when minting.
  • When minting ERC1155 tokens, _from must be the zero address.
  • The token identified by _id must be the ERC1155 token being transferred.
  • The balance held by _from must decrease by _value, and the recipient's ERC1155 balance must increase accordingly, subject to minting rules.
  • The value passed in _data must be the unchanged data supplied for the transfer.
  • If the recipient contract returns bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")), the transfer must be accepted.
  • If the recipient contract calls revert to reject the ERC1155 transfer, the transaction must revert.
  • If a value other than bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) is returned, the transaction must revert.
  • onERC1155Received() may be called multiple times in a transaction if the following conditions are met.
    • Each call must be mutually exclusive.
    • ERC1155 token balance changes made during the transaction must be represented in transfer order.
  • When transferring ERC1155 tokens to the token contract itself, the onERC1155Received() callback may be skipped.
onERC1155BatchReceived()
js
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4);

A callback used to check whether a safeBatchTransferFrom() transfer is accepted.

Requirements

  • _operator must identify the EOA or contract authorized to perform the transfer.
  • _from must identify the owner of the ERC1155 tokens being transferred, except when minting.
  • When minting ERC1155 tokens, _from must be the zero address.
  • Each ID in _ids must identify an ERC1155 token being transferred.
  • For each value in _values, the corresponding ERC1155 balance of _from must decrease, and the recipient's balance must increase accordingly, subject to minting rules.
  • The value passed in _data must be the unchanged data supplied for the transfer.
  • If the recipient contract returns bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")), the batch transfer must be accepted.
  • If the recipient contract calls revert to reject the ERC1155 transfer, the transaction must revert.
  • If a value other than bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) is returned, the transaction must revert.
  • onERC1155BatchReceived() may be called multiple times in a transaction if the following conditions are met.
    • Each call must be mutually exclusive.
    • ERC1155 token balance changes made during the transaction must be represented in transfer order.
  • When transferring ERC1155 tokens to the token contract itself, the onERC1155BatchReceived() callback may be skipped.

ERC1155Metadata_URI

Finally, although it is not mandatory functionality, let's examine ERC1155Metadata_URI.

uri()
js
function uri(uint256 _id) external view returns (string memory);

Returns the metadata URI of the ERC1155 token identified by _id.

Metadata contains information about a token, including its name, description, and image.

Requirements

  • If a URI event has not been emitted, the function should be called to obtain the metadata URI.
  • If a URI event has been emitted for _id, the function must return the same value as the event.
  • The function must not be used to determine whether the token identified by _id exists.
    • This is because it can return a value even when the token does not exist.

Metadata

Before examining the ERC1155 code, let's look at metadata. As explained in the previous section, metadata contains information such as a token's name, description, and image.

IDs

If the metadata URI contains the string {id}, it must be replaced with the token ID in hexadecimal.

Keep the following requirements in mind.

Requirements

  • The hexadecimal ID must use lowercase alphanumeric characters without a leading 0x.
  • The hexadecimal ID must be padded with leading zeros.

The substituted value is 256 bits long.

The actual values look like this.

Example IDs

text
0000000000000000000000000000000100000000000000000000000000000000
1000000000000000000000000000000100000000000000000000000000000003
1000000000000000000000000000000100000000000000000000000000000007
1000000000000000000000000000000200000000000000000000000000000001

These are not particularly easy to read. Let's examine them individually.

First, split the value into two groups of 32 characters (128 bits) each. The first value can be split into 00000000000000000000000000000001 and 00000000000000000000000000000000.

The first half, 00000000000000000000000000000001, represents the token type ID in this example. The token ID is 1, padded with leading zeros as described above. In this example of a split-bit ID scheme, the leading bit is 0 for fungible tokens and 1 for NFTs.

The second half, 00000000000000000000000000000000, represents the token index. This identifies the ERC1155 token at index 0.

Let's examine the other three values.

  • 1000000000000000000000000000000100000000000000000000000000000003 represents an NFT with token type ID 1 and index 3.
  • 1000000000000000000000000000000100000000000000000000000000000007 represents an NFT with token type ID 1 and index 7.
  • 1000000000000000000000000000000200000000000000000000000000000001 represents an NFT with token type ID 2 and index 1.

Suppose we have the following URI.

text
https://token-domain/{id}.json

Substituting the token ID produces the following URI.

text
https://token-domain/1000000000000000000000000000000200000000000000000000000000000001.json

We have discussed URIs, but the split-bit ID scheme shown above is not a mandatory implementation requirement. Treat it as one possible example.

Metadata

Metadata is defined in JSON format.

The JSON schema for ERC1155 is based on the following ERC721 Metadata JSON Schema.

json
{
    "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."
        }
    }
}

An ERC1155 metadata JSON file looks like this.

json
{
    "name": "Asset Name",
    "description": "Lorem ipsum...",
    "image": "https://s3.amazonaws.com/your-bucket/images/{id}.png",
    "properties": {
        "simple_property": "example value",
        "rich_property": {
            "name": "Name",
            "value": "123",
            "display_value": "123 Example Value",
            "class": "emphasis",
            "css": {
                "color": "#ffffff",
                "font-weight": "bold",
                "text-decoration": "underline"
            }
        },
        "array_property": {
            "name": "Name",
            "value": [1,2,3,4],
            "class": "emphasis"
        }
    }
}

Localization should also be standardized to improve consistency across languages. For this purpose, a localization value can be included as shown below.

json
{
    "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."
        },
        "localization": {
            "type": "object",
            "required": ["uri", "default", "locales"],
            "properties": {
                "uri": {
                    "type": "string",
                    "description": "The URI pattern to fetch localized data from. This URI should contain the substring `{locale}` which will be replaced with the appropriate locale value before sending the request."
                },
                "default": {
                    "type": "string",
                    "description": "The locale of the default data within the base JSON"
                },
                "locales": {
                    "type": "array",
                    "description": "The list of locales for which data is available. These locales should conform to those defined in the Unicode Common Locale Data Repository (http://cldr.unicode.org/)."
                }
            }
        }
    }
}

Using the above in practice looks like this.

json
{
  "name": "Advertising Space",
  "description": "Each token represents a unique Ad space in the city.",
  "localization": {
    "uri": "ipfs://QmWS1VAdMD353A6SDk9wNyvkT14kyCiZrNDYAad4w1tKqT/{locale}.json",
    "default": "en",
    "locales": ["en", "es", "fr", "ja"]
  }
}

es.json

json
{
  "name": "Espacio Publicitario",
  "description": "Cada token representa un espacio publicitario único en la ciudad."
}

fr.json

json
{
  "name": "Espace Publicitaire",
  "description": "Chaque jeton représente un espace publicitaire unique dans la ville."
}

ja.json

json
{
  "name": "Espace Publicitaire",
  "description": "それぞれのトークンは、街で唯一の広告スペースを表しています。"
}

Examining the ERC1155 code

In the previous section, we examined metadata. By now, you should have a much better understanding of ERC1155. In this section, we'll examine the ERC1155 implementation code function by function.

Implementation note: The examples below use an older OpenZeppelin ERC1155 implementation with transfer hooks. The current upstream implementation may use different internal functions. The code excerpts have been preserved from the original article.

IERC1155.sol

The functions required by EIP1155 are defined here. Here is the code.

js
// 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";

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] calldata accounts,
        uint256[] calldata ids
    ) external view returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}

The required functions defined in IERC1155.sol are listed below.

Functions

  • balanceOf()
  • balanceOfBatch()
  • setApprovalForAll()
  • isApprovedForAll()
  • safeTransferFrom()
  • safeBatchTransferFrom()

These functions were covered in the EIP1155 section, so we will not explain them again here.

Interface

Looking at the code, you will see the keyword interface. What does it mean?

An interface resembles a contract, but it cannot be deployed as a concrete executable implementation. An interface defines function names, arguments, and signatures, but does not define their implementations. A contract inheriting the interface must therefore implement the required functions.

"Do we really need interfaces?"

Some readers may be wondering about this.

One benefit of using an interface is that it clearly identifies the functions required by an implementation. Because the interface defines the required functions, developers and contract users can easily identify the functionality available.

Interfaces are also widely used in major projects, so understanding them now will be useful later.

Here is the official documentation.

IERC1155Receiver.sol

The functions required by IERC1155Receiver are defined here. Here is the code.

js
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev _Available since v3.1._
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

The functions defined in IERC1155Receiver.sol are listed below.

Functions

  • onERC1155Received()
  • onERC1155BatchReceived()

These were also explained in the EIP1155 section, so we will not repeat the explanations.

ERC1155.sol

Now let's look at the main implementation, ERC1155.sol.

The code is too long to include in full here. You can find the complete code at the following link.

The defined functions are listed below.

List of functions

  • supportsInterface(bytes4 interfaceId)
  • uri(uint256)
  • balanceOf(address account, uint256 id)
  • balanceOfBatch(address[] memory accounts, uint256[] memory ids)
  • setApprovalForAll(address operator, bool approved)
  • isApprovedForAll(address account, address operator)
  • safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data)
  • safeBatchTransferFrom(address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data)
  • _safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data)
  • _safeBatchTransferFrom(address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data)
  • _setURI(string memory newuri)
  • _mint(address to, uint256 id, uint256 amount, bytes memory data)
  • _mintBatch(address to, uint256[] memory ids, uint256[] amounts, bytes memory data)
  • _burn(address from, uint256 id, uint256 amount)
  • _burnBatch(address from, uint256[] memory ids, uint256[] memory amounts)
  • _setApprovalForAll(address owner, address operator, bool approved)
  • _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data)
  • _afterTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data)
  • _doSafeTransferAcceptanceCheck(address operator, address from, address to, uint256 id, uint256 amount, bytes memory data)
  • _doSafeBatchTransferAcceptanceCheck(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data)
  • _asSingletonArray(uint256 element)

That's quite a long list. Let's examine them one by one.

Note: explanations of the functions defined in IERC1155 were covered in the EIP1155 section.

Variables

js
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;

// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;

// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;

First, let's examine the variables.

_balances

A mapping that records how many units of each token ID a particular address holds.

_operatorApprovals

A mapping that records whether a specified operator has permission to transfer all ERC1155 tokens held by a particular address.

_uri

A private variable that stores the URI.

Constructor
js
constructor(string memory uri_) {
    _setURI(uri_);
}

Sets the URI to the string specified by uri_.

The constructor executes once when the contract is deployed.

_setURI()
js
function _setURI(string memory newuri) internal virtual {
    _uri = newuri;
}

Stores the string specified by newuri in the _uri variable.

supportsInterface()
js
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
    return
        interfaceId == type(IERC1155).interfaceId ||
        interfaceId == type(IERC1155MetadataURI).interfaceId ||
        super.supportsInterface(interfaceId);
}

Checks whether the contract implements the interface specified by interfaceId.

It checks whether interfaceId corresponds to IERC1155, IERC1155MetadataURI, or an interface supported by a parent contract.

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

Returns the _uri variable.

balanceOf()
js
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
    require(account != address(0), "ERC1155: address zero is not a valid owner");
    return _balances[id][account];
}

Returns the quantity of the ERC1155 token identified by id held by the address specified by account.

balanceOfBatch()
js
function balanceOfBatch(
    address[] memory accounts,
    uint256[] memory ids
) public view virtual override returns (uint256[] memory) {
    require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");

    uint256[] memory batchBalances = new uint256[](accounts.length);

    for (uint256 i = 0; i < accounts.length; ++i) {
        batchBalances[i] = balanceOf(accounts[i], ids[i]);
    }

    return batchBalances;
}

For each ID in ids, returns the balance held by the address at the corresponding index in accounts.

_setApprovalForAll()
js
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
    require(owner != operator, "ERC1155: setting approval status for self");
    _operatorApprovals[owner][operator] = approved;
    emit ApprovalForAll(owner, operator, approved);
}

Grants or revokes permission for the address specified by operator to transfer ERC1155 tokens held by the address specified by owner.

Emits the ApprovalForAll event.

setApprovalForAll()
js
function setApprovalForAll(address operator, bool approved) public virtual override {
    _setApprovalForAll(_msgSender(), operator, approved);
}

Calls _setApprovalForAll(), passing the address of the user who called setApprovalForAll().

_msgSender()
js
function _msgSender() internal view virtual returns (address) {
    return msg.sender;
}

Returns msg.sender.

isApprovedForAll()
js
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
    return _operatorApprovals[account][operator];
}

Checks whether the address specified by operator is authorized to transfer ERC1155 tokens held by the address specified by account.

_beforeTokenTransfer()
js
function _beforeTokenTransfer(
    address operator,
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) internal virtual {}

A hook called before a token transfer.

Override this hook to add optional custom logic.

_afterTokenTransfer()
js
function _afterTokenTransfer(
    address operator,
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) internal virtual {}

A hook called after a token transfer.

Override this hook to add optional custom logic.

_asSingletonArray()
js
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
    uint256[] memory array = new uint256[](1);
    array[0] = element;

    return array;
}

Creates a single-element array and stores the value passed in element.

When transferring one type of ERC1155 token, this allows _beforeTokenTransfer() and _afterTokenTransfer() to be called with the same array-based arguments used for safeBatchTransferFrom().

_doSafeTransferAcceptanceCheck()
js
function _doSafeTransferAcceptanceCheck(
    address operator,
    address from,
    address to,
    uint256 id,
    uint256 amount,
    bytes memory data
) private {
    if (to.isContract()) {
        try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
            if (response != IERC1155Receiver.onERC1155Received.selector) {
                revert("ERC1155: ERC1155Receiver rejected tokens");
            }
        } catch Error(string memory reason) {
            revert(reason);
        } catch {
            revert("ERC1155: transfer to non-ERC1155Receiver implementer");
        }
    }
}

If the recipient is a contract, checks whether it supports receiving ERC1155 tokens.

It performs the check by calling ERC1155Receiver's onERC1155Received() function.

As explained at the start of this article, transferring ERC1155 tokens to a contract that does not support them could make the tokens permanently inaccessible without such a check.

_safeTransferFrom()
js
function _safeTransferFrom(
    address from,
    address to,
    uint256 id,
    uint256 amount,
    bytes memory data
) internal virtual {
    require(to != address(0), "ERC1155: transfer to the zero address");

    address operator = _msgSender();
    uint256[] memory ids = _asSingletonArray(id);
    uint256[] memory amounts = _asSingletonArray(amount);

    _beforeTokenTransfer(operator, from, to, ids, amounts, data);

    uint256 fromBalance = _balances[id][from];
    require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
    unchecked {
        _balances[id][from] = fromBalance - amount;
    }
    _balances[id][to] += amount;

    emit TransferSingle(operator, from, to, id, amount);

    _afterTokenTransfer(operator, from, to, ids, amounts, data);

    _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}

Updates _balances, calls _doSafeTransferAcceptanceCheck(), and transfers amount units of the ERC1155 token identified by id from from to to.

safeTransferFrom()
js
function safeTransferFrom(
    address from,
    address to,
    uint256 id,
    uint256 amount,
    bytes memory data
) public virtual override {
    require(
        from == _msgSender() || isApprovedForAll(from, _msgSender()),
        "ERC1155: caller is not token owner or approved"
    );
    _safeTransferFrom(from, to, id, amount, data);
}

Checks that the caller is from or has permission to transfer the tokens on its behalf, then calls _safeTransferFrom().

_doSafeBatchTransferAcceptanceCheck()
js
function _doSafeBatchTransferAcceptanceCheck(
    address operator,
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) private {
    if (to.isContract()) {
        try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
            bytes4 response
        ) {
            if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
                revert("ERC1155: ERC1155Receiver rejected tokens");
            }
        } catch Error(string memory reason) {
            revert(reason);
        } catch {
            revert("ERC1155: transfer to non-ERC1155Receiver implementer");
        }
    }
}

If the recipient is a contract, checks whether it supports receiving ERC1155 tokens.

It performs the check by calling ERC1155Receiver's onERC1155BatchReceived() function.

As explained at the start of this article, transferring ERC1155 tokens to a contract that does not support them could make the tokens permanently inaccessible without such a check.

_safeBatchTransferFrom()
js
function _safeBatchTransferFrom(
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) internal virtual {
    require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
    require(to != address(0), "ERC1155: transfer to the zero address");

    address operator = _msgSender();

    _beforeTokenTransfer(operator, from, to, ids, amounts, data);

    for (uint256 i = 0; i < ids.length; ++i) {
        uint256 id = ids[i];
        uint256 amount = amounts[i];

        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
        unchecked {
            _balances[id][from] = fromBalance - amount;
        }
        _balances[id][to] += amount;
    }

    emit TransferBatch(operator, from, to, ids, amounts);

    _afterTokenTransfer(operator, from, to, ids, amounts, data);

    _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}

Updates _balances for the corresponding entries in ids and amounts, transfers the specified quantities from from to to, and calls _doSafeBatchTransferAcceptanceCheck().

safeBatchTransferFrom()
js
function safeBatchTransferFrom(
    address from,
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) public virtual override {
    require(
        from == _msgSender() || isApprovedForAll(from, _msgSender()),
        "ERC1155: caller is not token owner or approved"
    );
    _safeBatchTransferFrom(from, to, ids, amounts, data);
}

Checks that the caller is from or has permission to transfer the tokens on its behalf, then calls _safeBatchTransferFrom().

_mint()
js
function _mint(address to, uint256 id, uint256 amount, bytes memory data) internal virtual {
    require(to != address(0), "ERC1155: mint to the zero address");

    address operator = _msgSender();
    uint256[] memory ids = _asSingletonArray(id);
    uint256[] memory amounts = _asSingletonArray(amount);

    _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);

    _balances[id][to] += amount;
    emit TransferSingle(operator, address(0), to, id, amount);

    _afterTokenTransfer(operator, address(0), to, ids, amounts, data);

    _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}

Mints new ERC1155 tokens.

Requirements

  • to must not be the zero address.
  • If the recipient is a contract, it must implement IERC1155Receiver's onERC1155Received() callback for a single-token mint.
js
require(to != address(0), "ERC1155: mint to the zero address");

Checks that the recipient is not the zero address.

js
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);

Retrieves the address of the caller of _mint(), converts id and amount into single-element arrays, and stores them in ids and amounts respectively.

js
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);

_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);

_afterTokenTransfer(operator, address(0), to, ids, amounts, data);

Updates _balances and executes the _beforeTokenTransfer() and _afterTokenTransfer() hooks.

js
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);

Calls _doSafeTransferAcceptanceCheck() to ensure that the recipient specified by to accepts amount units of the ERC1155 token identified by id.

_mintBatch()
js
function _mintBatch(
    address to,
    uint256[] memory ids,
    uint256[] memory amounts,
    bytes memory data
) internal virtual {
    require(to != address(0), "ERC1155: mint to the zero address");
    require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");

    address operator = _msgSender();

    _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);

    for (uint256 i = 0; i < ids.length; i++) {
        _balances[ids[i]][to] += amounts[i];
    }

    emit TransferBatch(operator, address(0), to, ids, amounts);

    _afterTokenTransfer(operator, address(0), to, ids, amounts, data);

    _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}

Mints multiple ERC1155 tokens in a batch.

The balance updates follow the same principle as _mint(), repeated for the corresponding elements of ids and amounts.

Requirements

  • The ids and amounts arrays must have the same length.
  • If the recipient is a contract, it must implement IERC1155Receiver's onERC1155BatchReceived() callback for a batch mint.
_burn()
js
function _burn(address from, uint256 id, uint256 amount) internal virtual {
    require(from != address(0), "ERC1155: burn from the zero address");

    address operator = _msgSender();
    uint256[] memory ids = _asSingletonArray(id);
    uint256[] memory amounts = _asSingletonArray(amount);

    _beforeTokenTransfer(operator, from, address(0), ids, amounts, "");

    uint256 fromBalance = _balances[id][from];
    require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
    unchecked {
        _balances[id][from] = fromBalance - amount;
    }

    emit TransferSingle(operator, from, address(0), id, amount);

    _afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}

Burns ERC1155 tokens held by the address specified by from.

Updating _balances by reducing the holder's balance and emitting a transfer to the zero address constitutes the burn in this implementation. The _afterTokenTransfer() hook can be overridden to add custom burn-related logic; it is not required for the basic burn itself.

Requirements

  • from must not be the zero address.
  • The address specified by from must hold at least amount units of the ERC1155 token identified by id.
_burnBatch()
js
function _burnBatch(address from, uint256[] memory ids, uint256[] memory amounts) internal virtual {
    require(from != address(0), "ERC1155: burn from the zero address");
    require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");

    address operator = _msgSender();

    _beforeTokenTransfer(operator, from, address(0), ids, amounts, "");

    for (uint256 i = 0; i < ids.length; i++) {
        uint256 id = ids[i];
        uint256 amount = amounts[i];

        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
        unchecked {
            _balances[id][from] = fromBalance - amount;
        }
    }

    emit TransferBatch(operator, from, address(0), ids, amounts);

    _afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}

Burns the ERC1155 tokens held by from for the corresponding entries in ids and amounts.

Reducing the balances in _balances and emitting a batch transfer to the zero address constitutes the batch burn in this implementation. The _afterTokenTransfer() hook can be overridden to add custom burn-related logic; it is not required for the basic batch burn itself.

Requirements

  • The ids and amounts arrays must have the same length.

Implementing ERC1155

Now let's implement ERC1155. Here is the implementation.

js
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

import "@openzeppelin/contracts@4.8.0/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts@4.8.0/access/Ownable.sol";

contract CardeneToken is ERC1155, Ownable {

    constructor() ERC1155("https://cardene.net/erc1115/{id}.json") {
        _mint(msg.sender, 0, 10000, "");
        _mint(msg.sender, 1, 1, "");
        _mint(msg.sender, 2, 10**9, "");
    }
}

"Wait, that's all?"

Many readers may have had this reaction.

At first glance, the functions explained so far seem to be missing. However, the contract declaration on line 7 inherits ERC1155.sol. This makes the functions described above available through inheritance.

This is enough for a minimal implementation, so feel free to customize it.

Running ERC1155

Now that we have examined the ERC1155 implementation, let's try running it. We will use Remix IDE, an editor available in the browser.

You can also easily generate an ERC1155 implementation using the following OpenZeppelin website. Try it if you have time.

Let's write the code.

Creating a file

Create a file in the Remix editor. Once the file is created, paste the following code into it.

js
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

import "@openzeppelin/contracts@4.8.0/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts@4.8.0/access/Ownable.sol";

contract CardeneToken is ERC1155, Ownable {

    constructor() ERC1155("https://cardene.net/erc1115/{id}.json") {
        _mint(msg.sender, 0, 10000, "");
        _mint(msg.sender, 1, 1, "");
        _mint(msg.sender, 2, 10**9, "");
    }
}

Running the contract

Now let's run it.

How did it go? Were you able to deploy it successfully? You should also have been able to verify that the functions in ERC1155.sol work.

Deploying to the Goerli testnet

As of November 2025, Goerli has been discontinued. Use a testnet such as Sepolia instead.

Finally, let's deploy to the Goerli testnet and create ERC1155 tokens. For new deployments, use the alternative testnet mentioned above.

Deploying ERC1155 to a testnet

How did it go? You should now be able to verify that the contract was successfully deployed to the testnet.

Conclusion

This article covered ERC1155.

References