ERC1155 - OpenZeppelin Docs (2024)

ERC1155 is a novel token standard that aims to take the best from previous standards to create a fungibility-agnostic and gas-efficient token contract.

ERC1155 draws ideas from all of ERC20, ERC721, and ERC777. If you’re unfamiliar with those standards, head to their guides before moving on.

Multi Token Standard

The distinctive feature of ERC1155 is that it uses a single smart contract to represent multiple tokens at once. This is why its balanceOf function differs from ERC20’s and ERC777’s: it has an additional id argument for the identifier of the token that you want to query the balance of.

This is similar to how ERC721 does things, but in that standard a token id has no concept of balance: each token is non-fungible and exists or doesn’t. The ERC721 balanceOf function refers to how many different tokens an account has, not how many of each. On the other hand, in ERC1155 accounts have a distinct balance for each token id, and non-fungible tokens are implemented by simply minting a single one of them.

This approach leads to massive gas savings for projects that require multiple tokens. Instead of deploying a new contract for each token type, a single ERC1155 token contract can hold the entire system state, reducing deployment costs and complexity.

Batch Operations

Because all state is held in a single contract, it is possible to operate over multiple tokens in a single transaction very efficiently. The standard provides two functions, balanceOfBatch and safeBatchTransferFrom, that make querying multiple balances and transferring multiple tokens simpler and less gas-intensive.

In the spirit of the standard, we’ve also included batch operations in the non-standard functions, such as _mintBatch.

Constructing an ERC1155 Token Contract

We’ll use ERC1155 to track multiple items in our game, which will each have their own unique attributes. We mint all items to the deployer of the contract, which we can later transfer to players. Players are free to keep their tokens or trade them with other people as they see fit, as they would any other asset on the blockchain!

For simplicity we will mint all items in the constructor but you could add minting functionality to the contract to mint on demand to players.

For an overview of minting mechanisms check out Creating ERC20 Supply.

Here’s what a contract for tokenized items might look like:

// contracts/GameItems.sol// SPDX-License-Identifier: MITpragma solidity ^0.6.0;import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";contract GameItems is ERC1155 { uint256 public constant GOLD = 0; uint256 public constant SILVER = 1; uint256 public constant THORS_HAMMER = 2; uint256 public constant SWORD = 3; uint256 public constant SHIELD = 4; constructor() public ERC1155("https://game.example/api/item/{id}.json") { _mint(msg.sender, GOLD, 10**18, ""); _mint(msg.sender, SILVER, 10**27, ""); _mint(msg.sender, THORS_HAMMER, 1, ""); _mint(msg.sender, SWORD, 10**9, ""); _mint(msg.sender, SHIELD, 10**9, ""); }}

Note that for our Game Items, Gold is a fungible token whilst Thor’s Hammer is a non-fungible token as we minted only one.

The ERC1155 contract includes the optional extension IERC1155MetadataURI. That’s where the uri function comes from: we use it to retrieve the metadata uri.

Also note that, unlike ERC20, ERC1155 lacks a decimals field, since each token is distinct and cannot be partitioned.

Once deployed, we will be able to query the deployer’s balance:

> gameItems.balanceOf(deployerAddress,3)1000000000

We can transfer items to player accounts:

> gameItems.safeTransferFrom(deployerAddress, playerAddress, 2, 1, "0x0")> gameItems.balanceOf(playerAddress, 2)1> gameItems.balanceOf(deployerAddress, 2)0

We can also batch transfer items to player accounts and get the balance of batches:

> gameItems.safeBatchTransferFrom(deployerAddress, playerAddress, [0,1,3,4], [50,100,1,1], "0x0")> gameItems.balanceOfBatch([playerAddress,playerAddress,playerAddress,playerAddress,playerAddress], [0,1,2,3,4])[50,100,1,1,1]

The metadata uri can be obtained:

> gameItems.uri(2)"https://game.example/api/item/{id}.json"

The uri can include the string {id} which clients must replace with the actual token ID, in lowercase hexadecimal (with no 0x prefix) and leading zero padded to 64 hex characters.

For token ID 2 and uri https://game.example/api/item/{id}.json clients would replace {id} with 0000000000000000000000000000000000000000000000000000000000000002 to retrieve JSON at https://game.example/api/item/0000000000000000000000000000000000000000000000000000000000000002.json.

The JSON document for token ID 2 might look something like:

{ "name": "Thor's hammer", "description": "Mjölnir, the legendary hammer of the Norse god of thunder.", "image": "https://game.example/item-id-8u5h2m.png", "strength": 20}

For more information about the metadata JSON Schema, check out the ERC-1155 Metadata URI JSON Schema.

you’ll notice that the item’s information is included in the metadata, but that information isn’t on-chain! So a game developer could change the underlying metadata, changing the rules of the game!

Sending Tokens to Contracts

A key difference when using safeTransferFrom is that token transfers to other contracts may revert with the following message:

ERC1155: transfer to non ERC1155Receiver implementer

This is a good thing! It means that the recipient contract has not registered itself as aware of the ERC1155 protocol, so transfers to it are disabled to prevent tokens from being locked forever. As an example, the Golem contract currently holds over 350k GNT tokens, worth multiple tens of thousands of dollars, and lacks methods to get them out of there. This has happened to virtually every ERC20-backed project, usually due to user error.

In order for our contract to receive ERC1155 tokens we can inherit from the convenience contract ERC1155Holder which handles the registering for us. Though we need to remember to implement functionality to allow tokens to be transferred out of our contract:

// contracts/MyContract.sol// SPDX-License-Identifier: MITpragma solidity ^0.6.0;import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol";contract MyContract is ERC1155Holder {}

We can also implement more complex scenarios using the onERC1155Received and onERC1155BatchReceived functions.

Preset ERC1155 contract

A preset ERC1155 is available, ERC1155PresetMinterPauser. It is preset to allow for token minting (create) - including batch minting, stop all token transfers (pause) and allow holders to burn (destroy) their tokens. The contract uses Access Control to control access to the minting and pausing functionality. The account that deploys the contract will be granted the minter and pauser roles, as well as the default admin role.

This contract is ready to deploy without having to write any Solidity code. It can be used as-is for quick prototyping and testing, but is also suitable for production environments.

← ERC777

Gas Station Network →

ERC1155 - OpenZeppelin Docs (2024)
Top Articles
SEC's Gary Gensler says he has never owned crypto
Conan Exiles Obelisk Locations - Must-Know Obelisk Info - Conan Fanatics
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Selly Medaline
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 6142

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.