🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Building NFTs: ERC-721, ERC-1155, and On-Chain Metadata

NFTsđŸŸĸ Free Lesson
NFTs

The one-line mental model

An NFT is a unique identifier in a contract's bookkeeping paired with a metadata pointer that resolves to whatever humans want to look at, which is why the token can be permanent while the image it references may not be.

Prerequisites

  • !ERC-20 basics and the idea of contract-owned state
  • !What content addressing means at a high level

What You'll Learn

  • 1Mint ERC-721 tokens safely and explain why _safeMint exists
  • 2Choose between ERC-721 and ERC-1155 for a given collection design
  • 3Structure metadata JSON so marketplaces render it consistently
  • 4Implement ERC-2981 royalties and describe why marketplaces must honor them voluntarily

What the token actually stores

On-chain, an NFT occupies one entry in a mapping: token ID to owner address, plus any per-token state you choose to add, such as a level, a staking status, or a URI override. That is the entire permanent record. Everything visual — the image, the name, the trait list — lives off chain and is reached through a URI that the contract returns on request. Ethereum Improvement Proposal 721 defines two URI functions: one returning a base collection URI to which token IDs are appended, and one returning a fully custom URI per token, which generative collections use when each token's metadata is computed rather than stored.

Understanding that split resolves most confusion about NFTs. Burning a token deletes the on-chain record, and the marketplaces stop showing it, even if the image still exists on a public gateway. Conversely, a collection can be fully on-chain, with the metadata generated by contract code, in which case the art and the ownership record share the same permanence. That design choice is the real spectrum: from a JSON file on someone's server, through content-addressed storage, all the way to bytecode-computed artwork. The contract you deploy determines where on that spectrum a collection sits, and the choice is expensive to reverse, because a URI stored in contract state cannot be migrated to a new contract without moving every token.

ERC-721 by example

OpenZeppelin's implementation gives you the ownership bookkeeping, transfer rules, and safe-transfer receiver checks, so the custom code is mostly minting policy:

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

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract ArtCollection is ERC721, ERC721URIStorage, Ownable {
    uint256 private _nextId;
    uint256 public maxSupply = 1000;
    bool public mintingOpen;

    event Minted(address indexed to, uint256 indexed tokenId);

    constructor() ERC721("ChatWhole Art", "CWA") Ownable(msg.sender) {}

    function setMintingOpen(bool open) external onlyOwner {
        mintingOpen = open;
    }

    function mint(string calldata uri) external returns (uint256 tokenId) {
        require(mintingOpen, "minting closed");
        require(_nextId < maxSupply, "sold out");

        tokenId = _nextId++;
        _safeMint(msg.sender, tokenId);
        _setTokenURI(tokenId, uri);

        emit Minted(msg.sender, tokenId);
    }

    function tokenURI(uint256 tokenId)
        public
        view
        override(ERC721, ERC721URIStorage)
        returns (string memory)
    {
        return super.tokenURI(tokenId);
    }

    function supportsInterface(bytes4 id)
        public
        view
        override(ERC721, ERC721URIStorage)
        returns (bool)
    {
        return super.supportsInterface(id);
    }
}

Two overrides at the bottom are required precisely because this contract inherits the same functions from three places; the compiler needs to be told which implementation wins. _safeMint additionally calls the recipient's onERC721Received hook when the recipient is a contract, which prevents tokens from being locked forever inside contracts that cannot move them.

ERC-1155 when one contract holds many assets

A game rarely wants one contract per item type. ERC-1155 stores a balance per (token ID, address) pair in a single contract, so a hundred fungible potions and one legendary sword share one deployment and one batch transfer:

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

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";

contract GameItems is ERC1155 {
    uint256 public constant SWORD = 0;
    uint256 public constant SHIELD = 1;
    uint256 public constant POTION = 2;

    mapping(uint256 => uint256) public maxSupply;

    constructor() ERC1155("ipfs://QmCollection/{id}.json") {
        maxSupply[SWORD] = 100;
        maxSupply[SHIELD] = 250;
        maxSupply[POTION] = 100000;
    }

    function mintBatch(address to, uint256[] calldata ids, uint256[] calldata amounts)
        external
    {
        for (uint256 i = 0; i < ids.length; i++) {
            require(totalSupply(ids[i]) + amounts[i] <= maxSupply[ids[i]], "over cap");
        }
        _mintBatch(to, ids, amounts, "");
    }
}

The {id} placeholder in the base URI is replaced by callers with the zero-padded hexadecimal token ID, so one URI template serves the entire catalog. The trade-off against ERC-721 is flexibility: per-token metadata overrides are harder, and marketplaces must support the multi-token standard, which the major ones all do. Batching is the practical payoff — minting a hundred items in one transaction costs a small fraction of a hundred individual mints, which matters for game economies where items are created constantly and the gas bill would otherwise set the floor on how cheap an in-game action can be.

Metadata: the part users actually see

Marketplaces expect a specific JSON shape, and small formatting choices determine whether your collection renders as a gallery or as a wall of broken thumbnails:

{
  "name": "ChatWhole Study Token #042",
  "description": "A study badge earned by completing the blockchain module.",
  "image": "ipfs://QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG/042.png",
  "animation_url": "ipfs://QmAnimation/042.glb",
  "attributes": [
    { "trait_type": "Module", "value": "Blockchain" },
    { "trait_type": "Rarity", "value": "Rare" },
    { "trait_type": "Score", "display_type": "number", "value": 92 }
  ],
  "external_url": "https://chatwhole.com/learn/blockchain/06-nft/"
}
Metadata hostPermanenceCostTypical failure
Project HTTP serverNone; can change or vanishCheapImage 404s after domain lapses
IPFS with active pinningStrong while pinnedModerateUnpinned data eventually garbage-collected
Filecoin / Arweave storage dealContractual permanenceHigher, one-timeCost underestimated for large media
Fully on-chain SVG or generativeAs permanent as the chainExpensive writesStorage gas for large payloads

For a collection that claims scarcity, pin every asset to at least two independent pinning providers and store the base URI on chain so it cannot be silently repointed. A metadata URI you can change at will is a mutable asset no matter how permanent the token ID is, and buyers price that difference in — sometimes brutally.

Lazy minting and the gas problem it solves

Minting an NFT costs a storage write, and in busy periods that write can exceed the price a collector is willing to pay for a cheap item. Lazy minting defers it: the collection owner signs an order authorizing a specific token ID and URI for a specific price, off chain, and the marketplace submits the mint transaction only when a buyer appears. The buyer pays the gas, the seller pays nothing until sale, and the collection's supply remains unbounded until demand shows up.

Implementing lazy minting means storing an unsigned authorisation — signer, token ID, URI, price, expiry — that the mint function verifies with an ECDSA check before calling _safeMint to the buyer and paying the seller. The pattern has one sharp edge: replay. If the same signed order can be filled twice, a popular item sells repeatedly to different buyers, or the same buyer mints the same token twice if the ID is not consumed in state. Consume the order in storage the moment it is filled, bound it to a maximum quantity, and expire it by block number rather than by a timestamp a client can lie about.

Lazy minting also shifts a trust question. Collectors are buying into a signature that promises a future on-chain record, so the collection contract must be reputable enough that the promise is credible. That is a reasonable trade for established collections and a poor one for anonymous deployments, which is why marketplaces restrict lazy minting to verified creators and why the verification badge carries real economic weight.

Royalties without a payment rail

ERC-2981 gives collections a standard way to advertise a royalty percentage and receiver, but it is a convention that marketplaces must choose to honor:

import "@openzeppelin/contracts/token/common/ERC2981.sol";

contract RoyalArt is ERC721, ERC2981 {
    constructor() ERC721("Royal", "RYL") {
        _setDefaultRoyalty(msg.sender, 750); // 7.5%
    }

    function supportsInterface(bytes4 id)
        public
        view
        override(ERC721, ERC2981)
        returns (bool)
    {
        return super.supportsInterface(id);
    }
}

Secondary markets can ignore the signal entirely, which is why enforceable royalties — where the collection itself controls transfer or minting of wrapped derivatives — became a design axis of their own. Decide which model you are shipping and say so in the collection documentation, because the expectation gap here has produced more community disputes than almost any other technical detail.

âš ī¸Approvals are the real attack surface

An NFT that nobody can sell is safe; an NFT with an open marketplace approval is one malicious signature away from being transferred. Prefer signing off-chain orders over granting blanket setApprovalForAll, and revoke stale approvals regularly on the chain's approval explorer.

Common Mistakes

Hosting metadata on a server you control and calling the collection immutable

Fix: Pin assets to IPFS from day one, keep at least two pinning providers, and treat the server URL as a fallback rather than the source of truth

Letting anyone mint unlimited tokens with no cap or phase control

Fix: Enforce a supply cap in the contract, gate public phases behind a flag or merkle proof, and test the sold-out path

Forgetting the supportsInterface overrides when inheriting multiple ERC-721 extensions

Fix: Override supportsInterface and tokenURI explicitly, delegating to super, or marketplaces will mis-detect the collection's capabilities

Assuming ERC-2981 royalties are enforced on every marketplace

Fix: Document the royalty as advisory, or implement an on-chain enforcement model if the collection's economics depend on it

Best Practices

  • Use _safeMint rather than _mint so contracts that cannot receive tokens are rejected at mint time
  • Store a base URI on chain and derive per-token paths, so a migration is one storage write
  • Separate the minting contract from the token contract if you expect to iterate on minting rules
  • Verify the deployed source on the explorer; collectors check before they buy, and so do auditors

Interview Questions

Q1: Why does _safeMint exist alongside _mint?

_safeMint checks whether the recipient is a contract and, if so, calls onERC721Received on it. That prevents minting into a contract that has no way to move the token, which would otherwise lock it permanently.

Q2: What is the practical difference between ERC-721 and ERC-1155?

ERC-721 gives each token its own ID space and separate URI, suited to unique items. ERC-1155 stores balances per ID in one contract and supports batch transfers, which is cheaper for collections mixing fungibles and semi-fungibles.

Q3: If metadata can change, is the NFT still unique?

Uniqueness of the token ID and permanence of the presentation are independent properties. The ID is fixed on chain, but what a marketplace displays depends on the URI, so immutability claims must specify which layer they refer to.

Key Takeaways

  • An NFT combines on-chain ownership state with an off-chain metadata pointer that resolves to the artwork
  • ERC-721 suits unique items; ERC-1155 batches many IDs into one contract for cheaper operations
  • Metadata quality is determined by the host, the pinning strategy, and the JSON shape marketplaces expect
  • ERC-2981 advertises royalties but cannot enforce them without marketplace cooperation or transfer controls
  • Approval transactions, not minting, are where most NFT thefts actually happen
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement