Mastering the ERC-1155 Multi-Token Standard
What ERC-1155 is and how it differs from ERC-20 and ERC-721, then build, deploy and mint an OpenZeppelin 5 contract and read its balances and transfers.
On this page
ERC-1155 is the Ethereum multi-token standard: one smart contract that holds any number of token types, each identified by a numeric ID, where each ID can be fungible (like an ERC-20 currency), non-fungible (like an ERC-721 NFT) or anything in between. Balances are kept per owner and per ID, transfers can move several IDs in one transaction, and every transfer emits TransferSingle or TransferBatch. This guide explains how the standard works, builds and deploys an ERC-1155 contract with OpenZeppelin 5 and Foundry, and then reads its balances, owners and transfers with an NFT API.
What is ERC-1155?
EIP-1155 was proposed in June 2018 by Witek Radomski and co-authors, from the team behind Enjin, and is a Final Ethereum standard. It was written for games, where one title needs a currency, stackable consumables and one-of-a-kind items. Under ERC-20 and ERC-721 that means a separate contract for each fungible token and each collection, and a separate approval and transfer call for each.
ERC-1155 puts all of them in one contract. The contract stores a balance for every pair of owner and token ID:
- ID 0, "Gold", minted 1,000,000 times behaves like a fungible token: every unit is interchangeable.
- ID 1, "Sword", minted once behaves like an NFT: one holder, supply of one.
- ID 2, "Season ticket", minted 500 times is semi-fungible: identical copies of one item, like an edition or a ticket tier.
The standard doesn't label an ID as fungible or not. That follows from how many units the contract mints, and the contract's own code decides whether more can be minted later.
ERC-1155 vs ERC-20 vs ERC-721
| ERC-20 | ERC-721 | ERC-1155 | |
|---|---|---|---|
| Token types per contract | One | One collection, one token per ID | Any number of IDs, any supply per ID |
| Balance lookup | balanceOf(owner) |
balanceOf(owner) and ownerOf(id) |
balanceOf(owner, id), no ownerOf |
| Batch balance and transfer | No | No | balanceOfBatch, safeBatchTransferFrom |
| Approvals | Per spender, per amount | Per token or for all | For all IDs only (setApprovalForAll) |
| Transfer to a contract | Not checked | Checked only with safeTransferFrom |
Always checked |
| Metadata | name, symbol, decimals |
tokenURI(id) per token |
One uri(id) template with {id} |
| Interface ID (ERC-165) | None required | 0x80ac58cd |
0xd9b67a26 |
Choose ERC-1155 when one project issues many token types, when users move several at once, or when items come in editions. Choose ERC-721 when every token is unique and marketplaces and wallets should treat it as a standalone collectible. Choose ERC-20 for a single currency or governance token that DeFi protocols must accept.
How ERC-1155 works
Token IDs and balances
Every ERC-1155 call names a token ID. balanceOf(owner, id) returns how many units of id an address holds, and balanceOfBatch(owners, ids) takes two arrays of the same length and returns one balance per pair, so balanceOfBatch([alice, alice, bob], [0, 1, 1]) answers three questions in one call. Because many addresses can hold the same ID, there is no ownerOf.
The contract doesn't keep a list of its IDs or of who holds them. To list holders you replay the transfer events, which is what an indexer does (see Read ERC-1155 data with GoldRush).
Functions and events
The required interface is small:
safeTransferFrom(from, to, id, amount, data)movesamountunits of one ID and emitsTransferSingle.safeBatchTransferFrom(from, to, ids, amounts, data)moves several IDs in one call and emitsTransferBatch.balanceOf(owner, id)andbalanceOfBatch(owners, ids)read balances.setApprovalForAll(operator, approved)lets an operator, such as a marketplace, move all of the caller's tokens in the contract, and emitsApprovalForAll.isApprovedForAll(owner, operator)reads it. There is no approval for one ID or one amount.
Four events record every change:
| Event | When | Topic 0 |
|---|---|---|
TransferSingle(operator, from, to, id, value) |
One ID moves, is minted or is burned | 0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62 |
TransferBatch(operator, from, to, ids, values) |
Several IDs move in one call | 0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb |
ApprovalForAll(owner, operator, approved) |
An operator is approved or revoked | |
URI(value, id) |
The metadata URI for an ID changes |
A mint is a transfer from the zero address and a burn is a transfer to it, so the transfer events alone are enough to rebuild every balance.
Safe transfers and receiver hooks
ERC-1155 has no unchecked transfer. When the recipient is a contract, the token contract calls the recipient's onERC1155Received (or onERC1155BatchReceived for a batch) after updating balances, and reverts the whole transfer unless it gets back the function's selector: 0xf23a6e61 for a single transfer, 0xbc197c81 for a batch. A contract that doesn't implement the hook can't receive ERC-1155 tokens at all, which stops tokens being stranded in contracts that couldn't move them again. Externally owned accounts aren't called.
To let your own contract hold ERC-1155 tokens, inherit OpenZeppelin's ERC1155Holder, which implements both hooks.
Metadata and the {id} URI
Instead of one URI per token, an ERC-1155 contract usually returns one template from uri(id), such as ipfs://<CID>/{id}.json. Clients replace {id} with the token ID as lowercase hexadecimal, with no 0x prefix, left-padded with zeros to 64 characters. Token ID 1 becomes:
ipfs://<CID>/0000000000000000000000000000000000000000000000000000000000000001.jsonName the metadata files to match. Each file follows the ERC-1155 metadata JSON schema: name, description, image, an optional decimals for how wallets should display amounts, and free-form properties:
{ "name": "Sword", "description": "A one-of-a-kind blade. Only one will ever exist.", "image": "ipfs://<IMAGE_CID>/sword.png", "decimals": 0, "properties": { "rarity": "legendary", "damage": 42 }}The standard has no name(), symbol() or decimals() functions. Many contracts add name and symbol anyway so explorers can label them.
Detecting an ERC-1155 contract
ERC-1155 contracts must implement ERC-165: supportsInterface(0xd9b67a26) returns true. Check it before you treat an unknown contract as ERC-1155, since some contracts implement both ERC-721 and ERC-1155 functions.
Where ERC-1155 is used
- Games. Currencies, consumables, crafting materials and unique items live in one contract and move in one transaction. Aavegotchi's wearables are ERC-1155 tokens, for example.
- Editions and open editions. An artist mints 100 copies of a print as one ID instead of 100 ERC-721 tokens.
- Tickets and passes. Each tier is an ID with a fixed supply, and a ticket can be burned at the door.
- Bundles. A pack of items can be sent with one
safeBatchTransferFrom. - Semi-fungible receipts. Protocols issue claim or position tokens where many units share one ID.
Build an ERC-1155 contract with OpenZeppelin 5
This tutorial builds GameItems: a fungible GOLD ID and a one-of-one SWORD ID, owner-only minting, an updatable metadata URI and a total supply per ID. You'll deploy it to the Sepolia testnet, verify it on Etherscan and call it from the command line.
You need Foundry installed, some Sepolia ETH from a faucet in a wallet you can sign with, an Etherscan API key for verification, and a Sepolia RPC URL.
Step 1: Create the project
forge init erc1155-game-itemscd erc1155-game-itemsforge install OpenZeppelin/openzeppelin-contracts@v5.1.0echo '@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/' > remappings.txtImport a deployer key into Foundry's encrypted keystore rather than pasting it on the command line:
cast wallet import deployer --interactiveStep 2: Write the contract
Delete the sample src/Counter.sol, test/Counter.t.sol and script/Counter.s.sol, and create src/GameItems.sol:
// SPDX-License-Identifier: MITpragma solidity ^0.8.24; import {ERC1155} from "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";import {ERC1155Supply} from "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; contract GameItems is ERC1155Supply, Ownable { // Two token IDs in one contract: a fungible currency and a limited item. uint256 public constant GOLD = 0; uint256 public constant SWORD = 1; // uri_ is a template such as "ipfs://<CID>/{id}.json". Wallets swap {id} for the // token ID as 64 lowercase hex characters. constructor(string memory uri_) ERC1155(uri_) Ownable(msg.sender) {} function setURI(string memory newuri) external onlyOwner { _setURI(newuri); } function mint(address to, uint256 id, uint256 amount, bytes memory data) external onlyOwner { _mint(to, id, amount, data); } function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) external onlyOwner { _mintBatch(to, ids, amounts, data); }}What each part does:
ERC1155Supplyextends OpenZeppelin'sERC1155withtotalSupply(id),totalSupply()andexists(id). Inheriting the extension brings in the base contract, so there's no hook to override.Ownable(msg.sender)makes the deployer the owner. In OpenZeppelin 5 the initial owner is a constructor argument, andonlyOwnercalls from anyone else revert withOwnableUnauthorizedAccount.- The constructor stores the
{id}URI template.uri(id)returns it unchanged for every ID; clients do the substitution. setURIlets the owner point the metadata somewhere else, for example after moving it to a new IPFS folder.mintandmintBatchcall the internal_mintand_mintBatch, which emitTransferSingleandTransferBatchfrom the zero address and call the receiver hook whentois a contract.datais passed to that hook; send0xwhen you have nothing to pass.
If you're porting an OpenZeppelin 4 contract: v5 replaced the _beforeTokenTransfer and _afterTokenTransfer hooks with a single _update(from, to, ids, values) function. Override _update instead, and only when you add your own logic. Use ERC1155URIStorage if each ID needs its own URI rather than a template.
Step 3: Prepare the metadata
Write one JSON file per ID, named by the padded hex ID (0000…0000.json for GOLD, 0000…0001.json for SWORD), upload the folder to IPFS or any HTTPS host, and note the folder's base URI. You can deploy with a placeholder and call setURI once the files are up.
Step 4: Compile
forge buildFix any errors before deploying. forge build writes the ABI to out/GameItems.sol/GameItems.json, which is what a front end or script needs to call the contract.
Step 5: Deploy and verify on Sepolia
export SEPOLIA_RPC_URL=https://ethereum-sepolia-rpc.publicnode.comexport ETHERSCAN_API_KEY=your-etherscan-key forge create src/GameItems.sol:GameItems \ --rpc-url $SEPOLIA_RPC_URL \ --account deployer \ --broadcast \ --verify \ --constructor-args "ipfs://<CID>/{id}.json"--broadcast sends the transaction (without it forge create only simulates), and --verify submits the source to Etherscan once the contract is deployed. The output prints Deployed to: and Transaction hash:. Export both, and the deployment block, which the log reader at the end of this guide starts from; the later commands read them from your shell:
export TOKEN=the-deployed-to-address-forge-printedexport DEPLOY_TX=the-transaction-hash-forge-printedexport DEPLOY_BLOCK=$(cast receipt $DEPLOY_TX blockNumber --rpc-url $SEPOLIA_RPC_URL)If verification fails, for example because Etherscan hadn't indexed the contract yet, verify it on its own:
forge verify-contract $TOKEN src/GameItems.sol:GameItems \ --chain sepolia \ --constructor-args $(cast abi-encode "constructor(string)" "ipfs://<CID>/{id}.json") \ --watchA verified contract shows its source on Etherscan, and its Read Contract and Write Contract tabs let you call it from the browser.
Step 6: Mint, transfer and read balances
Mint 1,000 GOLD to yourself, then 500 more GOLD and the one SWORD in a batch:
export ME=$(cast wallet address --account deployer) cast send $TOKEN "mint(address,uint256,uint256,bytes)" $ME 0 1000 0x \ --rpc-url $SEPOLIA_RPC_URL --account deployer cast send $TOKEN "mintBatch(address,uint256[],uint256[],bytes)" $ME "[0,1]" "[500,1]" 0x \ --rpc-url $SEPOLIA_RPC_URL --account deployerRead balances one at a time or in a batch, and the metadata template:
cast call $TOKEN "balanceOf(address,uint256)(uint256)" $ME 0 --rpc-url $SEPOLIA_RPC_URL# expected: 1500 (1,000 minted, then 500 in the batch) cast call $TOKEN "balanceOfBatch(address[],uint256[])(uint256[])" "[$ME,$ME]" "[0,1]" \ --rpc-url $SEPOLIA_RPC_URL# expected: [1500, 1] cast call $TOKEN "uri(uint256)(string)" 1 --rpc-url $SEPOLIA_RPC_URLSend the sword to another wallet, and approve an operator such as a marketplace to move your tokens. Set both addresses first:
export FRIEND=a-second-wallet-addressexport OPERATOR=the-operator-contract-address cast send $TOKEN "safeTransferFrom(address,address,uint256,uint256,bytes)" $ME $FRIEND 1 1 0x \ --rpc-url $SEPOLIA_RPC_URL --account deployer cast send $TOKEN "setApprovalForAll(address,bool)" $OPERATOR true \ --rpc-url $SEPOLIA_RPC_URL --account deployerThree failures you'll meet while testing, all reverts with an OpenZeppelin 5 custom error:
OwnableUnauthorizedAccount: a wallet other than the owner calledmint,mintBatchorsetURI.ERC1155MissingApprovalForAll: someone tried to move another wallet's tokens withoutsetApprovalForAll.ERC1155InvalidReceiver: the recipient is a contract withoutonERC1155Received.
Read ERC-1155 data with GoldRush
A contract answers balance questions for an address and ID you already know. It can't tell you which IDs a wallet holds, which wallets hold an ID, or what moved when. That takes an indexer. The GoldRush endpoints below take ERC-1155 and ERC-721 contracts alike.
You need a GoldRush API key: sign up for the 14-day free trial, which includes 25,000 credits. Set it as GOLDRUSH_API_KEY; the code sends it as a Bearer token. The examples were run on Node.js 22 and use top-level await, so put them in one ES module, erc1155-data.mjs: this helper first, then each example below it in order (they all call get), and run node erc1155-data.mjs. The last example also uses viem:
npm install viem@2.58.4The examples share this helper:
const API = "https://api.covalenthq.com/v1";const headers = { Authorization: `Bearer ${process.env.GOLDRUSH_API_KEY}` }; async function get(path, params = {}) { const qs = new URLSearchParams(params); const res = await fetch(`${API}${path}?${qs}`, { headers }); if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); return (await res.json()).data;}Check ownership in a collection
Check ownership in an NFT collection returns the collection's token IDs a wallet holds and the balance of each, which for ERC-1155 can be more than one. It is billed in credits, 1 per call, and works on 6 chains: Ethereum, Polygon, Base, Optimism, BNB Smart Chain (BSC), and Gnosis. Sepolia isn't one of them, so run it against the collection once it's on a mainnet, here the ENS Name Wrapper, an ERC-1155 contract on Ethereum:
// Token IDs this wallet holds in one ERC-1155 collection, and how many of each.async function balancesInCollection(chain, wallet, collection) { const data = await get(`/${chain}/address/${wallet}/collection/${collection}/`); return data.items .map((item) => ({ tokenId: item.token_id, balance: BigInt(item.balance ?? 0) })) .filter((item) => item.balance > 0n);} const NAME_WRAPPER = "0xd4416b13d2b3a9abae7acd5d6c2bbdbe25686401";console.log(await balancesInCollection("eth-mainnet", "vitalik.eth", NAME_WRAPPER));The wallet field also takes ENS names. For token gating, signing and the pitfalls around staked and delegated tokens, see how to verify NFT ownership in a collection.
List a wallet's ERC-1155 tokens
NFTs for an address returns every NFT collection a wallet holds, ERC-721 and ERC-1155, with each token's ID and metadata, billed in credits at 1 per call. Keep the ERC-1155 collections by their supports_erc list:
// Every ERC-1155 collection a wallet holds, with the token IDs in it.async function erc1155Holdings(chain, wallet) { const data = await get(`/${chain}/address/${wallet}/balances_nft/`, { "no-spam": "true" }); return data.items .filter((c) => (c.supports_erc ?? []).some((erc) => erc.toLowerCase() === "erc1155")) .map((c) => ({ collection: c.contract_address, name: c.contract_name, tokenIds: (c.nft_data ?? []).map((nft) => nft.token_id), }));} console.log(await erc1155Holdings("eth-mainnet", "vitalik.eth"));Rebuild holders from TransferSingle and TransferBatch logs
To list every holder of every ID, or to follow your own contract on Sepolia, read its event logs with Get log events by contract address, which works on every GoldRush chain, including eth-sepolia, and is billed in credits at 0.01 per item returned. Each item carries raw_log_topics and raw_log_data; decode the two transfer events with viem and add up the movements per ID:
import { decodeEventLog, parseAbi } from "viem"; const ERC1155_TRANSFERS = parseAbi([ "event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value)", "event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values)",]); // Every log the contract emitted from startBlock on, page by page.async function contractLogs(chain, contract, startBlock) { const logs = []; for (let page = 0; ; page++) { const data = await get(`/${chain}/events/address/${contract}/`, { "starting-block": String(startBlock), "ending-block": "latest", "page-number": String(page), }); logs.push(...data.items); if (!data.pagination?.has_more) return logs; }} // One { from, to, id, value } per token ID moved; other events (ApprovalForAll, URI) give none.function transfers(log) { let event; try { event = decodeEventLog({ abi: ERC1155_TRANSFERS, topics: log.raw_log_topics, data: log.raw_log_data }); } catch { return []; } const { from, to } = event.args; if (event.eventName === "TransferSingle") return [{ from, to, id: event.args.id, value: event.args.value }]; return event.args.ids.map((id, i) => ({ from, to, id, value: event.args.values[i] }));} const ZERO = "0x0000000000000000000000000000000000000000"; // Map of token ID → Map of holder → balance, from the mint onwards.async function holdersById(chain, contract, startBlock) { const holders = new Map(); const add = (id, who, delta) => { if (who === ZERO) return; // mints come from, and burns go to, the zero address const ofId = holders.get(id) ?? new Map(); const balance = (ofId.get(who) ?? 0n) + delta; if (balance === 0n) ofId.delete(who); else ofId.set(who, balance); holders.set(id, ofId); }; for (const log of await contractLogs(chain, contract, startBlock)) { for (const t of transfers(log)) { add(t.id, t.from.toLowerCase(), -t.value); add(t.id, t.to.toLowerCase(), t.value); } } return holders;} // Your GameItems contract on Sepolia, from its deployment blockconst holders = await holdersById("eth-sepolia", process.env.TOKEN, Number(process.env.DEPLOY_BLOCK));for (const [id, ofId] of holders) console.log(`ID ${id}:`, Object.fromEntries(ofId));Start from the contract's deployment block (DEPLOY_BLOCK from Step 5), not from block 0, so you don't page through empty ranges. For a busy contract, store the result and fetch only newer blocks next time. The token_holders_v2 endpoint is documented for ERC-20 and ERC-721 contracts, which is why ERC-1155 holders are rebuilt from logs here.
Handle errors from the GoldRush API
get throws on any non-2xx status with the body in the message. A failed call returns the same envelope as a successful one, with data set to null, error set to true and the reason in error_message; error_code is a JSON number equal to the HTTP status. The docs show this body for a chain name the API doesn't recognize:
{ "data": null, "error": true, "error_message": "Chain nosuchchain-mainnet not supported.", "error_code": 501 }A 501 means the request was well formed but the chain or endpoint can't serve it, so retrying it unchanged won't help. The docs list an endpoint called on a chain it isn't served on among the 501 cases, which is what to expect if you point the ownership check at eth-sepolia: read your test contract with the log endpoint instead. A 401 means the key is missing or wrong; with no Authorization header at all, the edge proxy returns an HTML 401 page rather than JSON, which res.text() still reads. Failed requests cost no credits. Every code is listed in the error handling docs.
Common ERC-1155 mistakes
- Sending to a contract that can't receive. Every ERC-1155 transfer to a contract calls its receiver hook. Multisigs and vaults that should hold ERC-1155 tokens need
onERC1155ReceivedandonERC1155BatchReceived, for example throughERC1155Holder. - Reentrancy through the hook. The receiver hook runs after balances change but before your mint or transfer function returns. Don't update other state after
_mintor a transfer, or guard the function withReentrancyGuard. - Putting
0xor decimal IDs in metadata file names. Clients substitute{id}as 64 lowercase hex characters. A file named1.jsononly works if your contract returns a full per-ID URI instead of the template. - Approving an operator you don't trust.
setApprovalForAllcovers every ID and every unit in the contract, now and later. Revoke it withsetApprovalForAll(operator, false)when you're done. - Expecting a fixed supply. Nothing in the standard stops more units of an ID being minted. If an ID must stay one-of-one, enforce it in your mint function, for example with
require(totalSupply(id) == 0). - Reading only
TransferSingle. Indexers and analytics that skipTransferBatchmiss every batch mint and transfer.
Frequently asked questions
What is an ERC-1155 token?
ERC-1155 is the Ethereum multi-token standard, EIP-1155. One contract manages many token types, each with a numeric ID, and each ID can be fungible, non-fungible or semi-fungible depending on how many units are minted. It adds batch balance reads and batch transfers, and every transfer to a contract is checked with a receiver hook.
What is the difference between ERC-721 and ERC-1155?
An ERC-721 contract is one collection where every token ID has exactly one owner, read with ownerOf. An ERC-1155 contract holds any number of IDs, each with a balance per owner, so one ID can have many holders and there is no ownerOf. ERC-1155 also supports batch transfers and only has all-or-nothing operator approvals.
Can an ERC-1155 token be an NFT?
Yes. An ID minted once, to one owner, is non-fungible. The standard doesn't enforce that the supply stays at one, so the contract's mint logic has to.
Why did my ERC-1155 transfer to a contract revert?
When the recipient is a contract, the token calls its onERC1155Received (or onERC1155BatchReceived) and reverts unless the hook returns its selector. A contract without the hook can't receive ERC-1155 tokens. In OpenZeppelin 5 the revert is ERC1155InvalidReceiver.
How do I check if a contract is ERC-1155?
Call supportsInterface(0xd9b67a26) on it. ERC-1155 contracts must implement ERC-165 and return true for that interface ID. ERC-721 contracts return true for 0x80ac58cd instead.
How do I find every holder of an ERC-1155 token?
The contract doesn't store a holder list. Replay its TransferSingle and TransferBatch events from deployment, adding each transfer's value to the recipient and subtracting it from the sender, per token ID. GoldRush's contract event logs endpoint returns those logs, page by page.
Does OpenZeppelin 5 still have _beforeTokenTransfer for ERC-1155?
No. OpenZeppelin 5 replaced _beforeTokenTransfer and _afterTokenTransfer with one _update(from, to, ids, values) function. Inheriting ERC1155Supply alone needs no override.
Next steps
- NFT API: the GoldRush NFT endpoints, with credit costs.
- How to verify NFT ownership in a collection: ERC-721 and ERC-1155 ownership checks and token gating.
- Check ownership in an NFT collection reference: every parameter and response field.
- EIP-2981 NFT royalties: add on-chain royalty info to an ERC-1155 or ERC-721 contract.
- What is an NFT API?: what NFT APIs return and how to choose one.