You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ERC1155的mintBatch函数为每个NFT集合设置自定义URI

ERC1155 按批次设置统一URI的实现方案

要实现每次调用mintBatch时为整组NFT设置统一URI,核心思路是重写ERC1155的uri函数,并维护一个tokenId到批次URI的映射,在铸造时为每个新生成的tokenId绑定指定的URI。以下是具体实现方案:

核心实现代码

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

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

contract BatchURIERC1155 is ERC1155, Ownable {
    // 存储每个tokenId对应的批次URI
    mapping(uint256 => string) public tokenUri;
    // 自动递增的tokenId计数器
    uint256 public nextTokenId;

    // 构造函数无需传入默认URI,因为我们重写了uri逻辑
    constructor() ERC1155("") {}

    /**
     * 自定义批量铸造函数,支持传入批次统一URI
     * @param to 接收NFT的地址
     * @param amounts 每个tokenId的铸造数量数组(长度对应NFT个数)
     * @param batchUri 该批次所有NFT共用的URI
     * @param data 附加数据(可留空)
     */
    function mintBatchWithURI(
        address to,
        uint256[] memory amounts,
        string calldata batchUri,
        bytes memory data
    ) public onlyOwner {
        uint256[] memory tokenIds = new uint256[](amounts.length);
        
        // 为每个NFT生成唯一tokenId,并绑定批次URI
        for (uint256 i = 0; i < amounts.length; i++) {
            tokenIds[i] = nextTokenId++;
            tokenUri[tokenIds[i]] = batchUri;
        }

        // 调用ERC1155原生批量铸造逻辑
        _mintBatch(to, tokenIds, amounts, data);
    }

    /**
     * 重写ERC1155的uri函数,返回对应tokenId的批次URI
     */
    function uri(uint256 tokenId) public view override returns (string memory) {
        return tokenUri[tokenId];
    }

    /**
     * 可选:修改已有tokenId的URI(仅所有者可调用)
     */
    function setTokenUri(uint256 tokenId, string calldata newUri) public onlyOwner {
        tokenUri[tokenId] = newUri;
    }
}

场景适配说明

场景1:单个collection是同一tokenId的多份实例

如果你的collection1是10个相同tokenId的NFT实例,可以简化函数为单个tokenId的批量铸造:

function mintSingleTokenBatchWithURI(
    address to,
    uint256 amount,
    string calldata batchUri,
    bytes memory data
) public onlyOwner {
    uint256 tokenId = nextTokenId++;
    tokenUri[tokenId] = batchUri;
    _mint(to, tokenId, amount, data);
}

调用时传入amount=10和对应URI,即可让该tokenId的所有实例共用同一URI。

场景2:单个collection是多个不同tokenId的NFT

使用核心代码中的mintBatchWithURI函数,传入amounts数组为[1,1,...](共10个1)和对应URI,即可生成10个不同tokenId,且全部使用该批次URI。

关键注意事项

  • 权限控制:示例中用Ownable限制仅合约所有者可铸造,可根据需求替换为自定义权限逻辑(如白名单)。
  • URI有效性:可在mintBatchWithURI中添加对batchUri非空的校验,避免出现空URI。
  • 链上存储:URI本身存在链下,合约仅存储URI字符串,需确保URI指向的元数据符合ERC1155规范。

内容的提问来源于stack exchange,提问作者Yahya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:45:31