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

如何在TON NFT合约中创建链上元数据的attributes字段

TON NFT合约链上Attributes元数据实现示例

你的当前代码把attributes存成了单个JSON对象,但标准NFT元数据中attributes是数组类型,下面是符合规范的合约内实现方案:

1. 固定属性的基础实现

如果你的NFT属性是固定的(比如所有NFT都有相同的几个属性),可以直接构建完整的JSON数组cell:

// 构建attributes的JSON数组cell
cell attributes = begin_cell()
    .store_int(0, 8)  // 字符串前缀(0表示UTF-8编码)
    .store_slice("[{'trait_type':'背景','value':'蓝色'},{'trait_type':'等级','value':'1'}]")
    .end_cell();

// 将attributes存入元数据字典
metadata_dict~udict_set_ref(256, "attributes"H, attributes);

2. 动态生成属性(根据Token ID)

如果需要根据每个NFT的token_id生成不同属性,可以通过条件判断拼接字符串:

slice build_attributes(int token_id) {
    // 根据token_id生成不同属性值
    string rarity = "";
    if (token_id % 3 == 0) {
        rarity = "稀有";
    } elif (token_id % 3 == 1) {
        rarity = "普通";
    } else {
        rarity = "罕见";
    }

    // 拼接JSON数组字符串
    string attributes_str = "[{'trait_type':'稀有度','value':'" + rarity + "'},{'trait_type':'编号','value':'" + token_id + "'}]";
    return attributes_str;
}

// 在铸造逻辑中调用生成并存储
cell attributes_cell = begin_cell()
    .store_int(0, 8)
    .store_slice(build_attributes(token_id))
    .end_cell();

metadata_dict~udict_set_ref(256, "attributes"H, attributes_cell);

关键注意点

  • 必须严格遵循NFT元数据规范:attributes是包含多个trait_type和value键值对对象的JSON数组,不能用单个对象格式。
  • 存储字符串时,开头的store_int(0,8)是TON标准的UTF-8字符串标识,不可省略。
  • 如果属性数量较多,建议用字符串拼接的方式动态构建,避免硬编码冗余。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:32:36