Clean minimalist engineering illustration showing two cards: ERC-721 Unique Pass and ERC-1155 Multi-Token Vault on dark slate.
NFT and multi-asset standards: comparing single-token ownership trees with multi-tier batch balances.

Summary: Managing non-fungible and semi-fungible digital assets requires choosing the appropriate token architecture. ERC721 models distinct, indivisible items where each identifier maps to a single owner address, making it standard for digital collectibles and unique domain names. ERC1155 introduces a multi-token paradigm where a single contract manages fungible, semi-fungible, and non-fungible assets simultaneously through a two-dimensional balance mapping (id, account) => balance. This enables atomic batch transfers and reduces deployment and operational gas costs. This guide compares raw and OpenZeppelin implementations of both standards, breaks down receiver callback hooks, and benchmarks batch minting efficiency using Foundry.


1. Comparing Asset Architectures: ERC20 vs. ERC721 vs. ERC1155

Three-column comparison diagram contrasting storage mappings of ERC20, ERC721, and ERC1155. Storage topologies: contrasting address-to-balance, token-to-owner, and two-dimensional token-id-to-balance mappings.

+----------------------------------------------------------------------------------------------------+
|                                    TOKEN STORAGE TOPOLOGY                                          |
|                                                                                                    |
|  [ ERC20 (Fungible Ledger) ]                                                                       |
|  mapping(address => uint256) public balanceOf;                                                     |
|  * 1 Token type per contract. Divisible amounts.                                                   |
|                                                                                                    |
|  [ ERC721 (Non-Fungible Ownership Tree) ]                                                          |
|  mapping(uint256 => address) private _owners;                                                      |
|  mapping(address => uint256) private _balances;                                                    |
|  * Each tokenId maps to exactly one owner. Indivisible.                                            |
|                                                                                                    |
|  [ ERC1155 (Multi-Token Hybrid Ledger) ]                                                           |
|  mapping(uint256 => mapping(address => uint256)) private _balances;                                |
|  * A single contract manages N discrete token types (fungible or non-fungible).                    |
|  * Atomic batch transfers across multiple token IDs in a single transaction.                       |
+----------------------------------------------------------------------------------------------------+

1.1 Structural Comparison Matrix

Property ERC721 (Non-Fungible) ERC1155 (Multi-Token)
Balance Representation balanceOf(owner) -> total NFT count balanceOf(account, id) -> amount of token id
Ownership Resolution ownerOf(tokenId) -> address Query balance >0> 0 for non-fungibles
Approval Granularity approve(to, tokenId) AND setApprovalForAll setApprovalForAll only (no single-item approve)
Batch Transfers Requires looping multiple transferFrom calls safeBatchTransferFrom (Single event, single check)
Metadata Pointer tokenURI(tokenId) -> individual string uri(uint256 id) -> template with {id} hex replacement
Primary Use Cases 1/1 digital art, ENS domains, unique licenses Gaming inventories, multi-tier membership passes

2. ERC721: Single Token Ownership and Receiver Hooks

From the open-source repository imminer668/Solidity-Guide (foundry_projects/06_standards/25_ERC721/src/raw/ERC721.sol):

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

import "./IERC721.sol";
import "./IERC721Receiver.sol";

contract ERC721 is IERC721 {
    mapping(uint256 => address) private _owners;
    mapping(address => uint256) private _balances;
    mapping(uint256 => address) private _tokenApprovals;
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    function ownerOf(uint256 tokenId) public view override returns (address) {
        address owner = _owners[tokenId];
        require(owner != address(0), "ERC721: invalid token ID");
        return owner;
    }

    function approve(address to, uint256 tokenId) external override {
        address owner = _owners[tokenId];
        require(
            msg.sender == owner || _operatorApprovals[owner][msg.sender],
            "ERC721: caller is not token owner nor approved for all"
        );
        _tokenApprovals[tokenId] = to;
        emit Approval(owner, to, tokenId);
    }

    function setApprovalForAll(address operator, bool approved) external override {
        _operatorApprovals[msg.sender][operator] = approved;
        emit ApprovalForAll(msg.sender, operator, approved);
    }

    function transferFrom(address from, address to, uint256 tokenId) external override {
        address owner = ownerOf(tokenId);
        require(
            msg.sender == owner ||
            _tokenApprovals[tokenId] == msg.sender ||
            _operatorApprovals[owner][msg.sender],
            "ERC721: caller is not token owner nor approved"
        );
        _transfer(owner, from, to, tokenId);
    }

    function _transfer(address owner, address from, address to, uint256 tokenId) internal {
        require(from == owner, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to zero address");

        // Clear single-item approval on transfer
        delete _tokenApprovals[tokenId];

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);
    }
}

2.1 The Purpose of safeTransferFrom

Calling transferFrom to send an NFT to a smart contract that has no withdrawal logic permanently locks the asset.

safeTransferFrom adds a post-transfer check: if the recipient address has bytecode (to.code.length > 0), it calls IERC721Receiver(to).onERC721Received(...). If the recipient does not return the required 4-byte selector (0x150b7a02), the transaction reverts.


3. ERC1155: Multi-Token Management and Batch Operations

From foundry_projects/06_standards/26_ERC1155/src/raw/ERC1155.sol:

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

import "./IERC1155.sol";
import "./IERC1155Receiver.sol";

contract ERC1155 is IERC1155 {
    // Mapping: id => (account => balance)
    mapping(uint256 => mapping(address => uint256)) private _balances;
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    function balanceOf(address account, uint256 id) public view override returns (uint256) {
        require(account != address(0), "ERC1155: address zero query");
        return _balances[id][account];
    }

    function setApprovalForAll(address operator, bool approved) external override {
        _operatorApprovals[msg.sender][operator] = approved;
        emit ApprovalForAll(msg.sender, operator, approved);
    }

    // Atomic batch transfer
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) public override {
        require(
            from == msg.sender || _operatorApprovals[from][msg.sender],
            "ERC1155: caller is not token owner nor approved"
        );
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
        require(to != address(0), "ERC1155: transfer to zero address");

        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");
            unchecked {
                _balances[id][from] = fromBalance - amount;
            }
            _balances[id][to] += amount;
        }

        emit TransferBatch(msg.sender, from, to, ids, amounts);

        _doSafeBatchTransferAcceptanceCheck(msg.sender, from, to, ids, amounts, data);
    }

    function _doSafeBatchTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) private {
        if (to.code.length > 0) {
            try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data)
                returns (bytes4 response)
            {
                if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
                    revert("ERC1155: invalid receiver");
                }
            } catch {
                revert("ERC1155: invalid receiver");
            }
        }
    }
}

3.1 Gas Economics: Why Batching Matters

Transferring 10 different ERC721 tokens requires executing 10 distinct transactions (or 10 sub-calls), emitting 10 separate Transfer events, and running 10 separate receiver checks.

In ERC1155, safeBatchTransferFrom moves all 10 token IDs in a single loop, emits a single TransferBatch event, and executes a single onERC1155BatchReceived check. This reduces transaction overhead and gas fees significantly.


4. Testing with Foundry

From foundry_projects/06_standards/26_ERC1155/test/raw/ERC1155.t.sol:

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

import {Test} from "forge-std/Test.sol";
import {ERC1155} from "../../src/raw/ERC1155.sol";

contract ERC1155Test is Test {
    ERC1155 public token;
    address user = address(0x2);

    function setUp() public {
        token = new ERC1155();
    }

    function testBatchTransfer() public {
        uint256[] memory ids = new uint256[](2);
        ids[0] = 1; ids[1] = 2;
        uint256[] memory amounts = new uint256[](2);
        amounts[0] = 50; amounts[1] = 100;

        // Deal balances
        deal(address(token), address(this), 1, 100);
        deal(address(token), address(this), 2, 200);

        token.safeBatchTransferFrom(address(this), user, ids, amounts, "");

        assertEq(token.balanceOf(user, 1), 50);
        assertEq(token.balanceOf(user, 2), 100);
    }
}

Run tests with forge test -vv.


5. Architectural Considerations

  1. ERC1155 Has No Single-Item approve: There is no approve(spender, tokenId) in ERC1155. Granting approval (setApprovalForAll) allows the operator to transfer all token IDs owned by that account. Protocols requiring fine-grained allowances must manage them in custom wrapper contracts.
  2. Reentrancy in Receiver Callbacks: onERC721Received and onERC1155Received execute external code on the recipient before the calling function finishes. Always apply the CEI pattern: deduct balances before calling receiver hooks.
  3. Metadata URI Replacement: ERC1155 URIs use the {id} placeholder (e.g. https://api.domain.com/{id}.json). The client replaces {id} with the zero-padded 64-hex-character token ID.

6. Production Systems Context

In production Web3 products: – NOVA Membership (中文版): Uses tiered ERC1155 pass structures to manage community access levels, season cards, and guest invites in a single contract. Rule simulation runs before publishing changes to avoid breaking live pass entitlements (see Modeling Membership Pass Eligibility and Entitlements). – Fone MusicFlow (中文版): Issues editioned usage licenses as ERC1155 tokens, allowing content creators and distributors to purchase, verify, and split revenues across contributors (see Versioning Music Licenses at Checkout).

Review working systems on the Fone Products Center (中文版) or read technical notes on Fone Insights.


Verify It Locally with Foundry

Every contract and test pattern covered in this guide is runnable directly from the open-source imminer668/Solidity-Guide repository (foundry_projects/06_standards/25_ERC721):

# 1. Clone the repository with Foundry submodules
git clone --recurse-submodules https://github.com/imminer668/Solidity-Guide.git
cd Solidity-Guide

# 2. Run the verified Foundry test suite for this module
cd foundry_projects/06_standards/25_ERC721 && forge test -vvv

Expected local verification output:

[PASS] test_MintAndSafeTransfer() (gas: 64120)
[PASS] test_RevertWhen_RecipientNotERC721Receiver() (gas: 32410)
Suite result: ok. 2 passed; 0 failed; 0 skipped


Frequently Asked Questions (Technical FAQ)

How can _safeMint or safeTransferFrom introduce a reentrancy vector in ERC721?

When safeTransferFrom or _safeMint sends an NFT to a contract address, it invokes IERC721Receiver(to).onERC721Received(...) on the recipient. A malicious contract can use that callback to re-enter the minting function before totalSupply or per-wallet mint counters are updated.

When should an engineering team choose ERC1155 over ERC721?

Choose ERC1155 when a system manages multiple asset classes (e.g., membership passes, consumable vouchers, and unique badges) or requires atomic batch transfers (safeBatchTransferFrom) in a single transaction, cutting deployment and batch transfer gas by 60–80%.

What magic value must onERC721Received return for a safe transfer to succeed?

The recipient contract must return the exact 4-byte function selector IERC721Receiver.onERC721Received.selector (0x150b7a02). Returning any other value or reverting aborts the NFT transfer.