Rust NFT运行时API库pallet-nfts-runtime-api的使用,实现Substrate区块链的NFT铸造、转移与管理功能

以下是关于pallet-nfts-runtime-api库的使用说明和完整示例:

库介绍

pallet-nfts-runtime-api是Substrate区块链框架中用于NFT功能的运行时API库,提供NFT铸造、转移和管理等功能。许可证为Apache-2.0。

安装方法

在项目目录中运行以下Cargo命令:

cargo add pallet-nfts-runtime-api

或在Cargo.toml中添加:

pallet-nfts-runtime-api = "27.0.0"

完整示例代码

use frame_support::traits::Currency;
use pallet_nfts_runtime_api::{NftsApi, CollectionId, ItemId};
use sp_api::ProvideRuntimeApi;
use sp_runtime::AccountId32;

// 创建NFT集合
fn create_collection(api: &impl NftsApi<Block>, owner: AccountId32) -> CollectionId {
    let collection_id = api.next_collection_id();
    api.create_collection(owner.clone(), collection_id, Default::default())
        .unwrap();
    collection_id
}

// 铸造NFT
fn mint_nft(
    api: &impl NftsApi<Block>,
    collection_id: CollectionId,
    owner: AccountId32,
    recipient: AccountId32,
) -> ItemId {
    let item_id = api.next_item_id(collection_id);
    api.mint(
        owner.clone(),
        collection_id,
        item_id,
        recipient.clone(),
        Default::default(),
    )
    .unwrap();
    item_id
}

// 转移NFT
fn transfer_nft(
    api: &impl NftsApi<Block>,
    collection_id: CollectionId,
    item_id: ItemId,
    sender: AccountId32,
    recipient: AccountId32,
) {
    api.transfer(sender, collection_id, item_id, recipient)
        .unwrap();
}

// 销毁NFT
fn burn_nft(
    api: &impl NftsApi<Block>,
    collection_id: CollectionId,
    item_id: ItemId,
    owner: AccountId32,
) {
    api.burn(owner, collection_id, item_id).unwrap();
}

fn main() {
    // 初始化运行时客户端
    let client = create_runtime_client();
    
    // 获取API实例
    let api = client.runtime_api();
    
    // 创建测试账户
    let owner = AccountId32::new([1; 32]);
    let recipient = AccountId32::new([2; 32]);
    
    // 执行NFT操作
    let collection_id = create_collection(&api, owner.clone());
    let item_id = mint_nft(&api, collection_id, owner.clone(), recipient.clone());
    transfer_nft(&api, collection_id, item_id, recipient.clone(), owner.clone());
    burn_nft(&api, collection_id, item_id, owner.clone());
}

主要功能说明

  1. create_collection - 创建新的NFT集合
  2. mint_nft - 在指定集合中铸造新的NFT
  3. transfer_nft - 转移NFT所有权
  4. burn_nft - 销毁NFT

注意:实际使用时需要根据具体区块链实现调整账户类型和区块类型参数。

更完整的示例代码

use frame_support::traits::Currency;
use pallet_nfts_runtime_api::{NftsApi, CollectionId, ItemId};
use sp_api::{ProvideRuntimeApi, BlockT};
use sp_runtime::{AccountId32, generic::Block};
use sp_core::sr25519;
use substrate_test_runtime_client::{
    runtime::TestAPI, 
    DefaultTestClientBuilderExt, 
    TestClientBuilder, 
    TestClientBuilderExt
};

// 自定义区块类型
type Block = substrate_test_runtime_client::runtime::Block;

// 创建运行时客户端
fn create_runtime_client() -> sp_blockchain::Client<Block> {
    TestClientBuilder::new()
        .build()
        .into()
}

// 创建NFT集合
fn create_collection(api: &impl NftsApi<Block>, owner: AccountId32) -> CollectionId {
    let collection_id = api.next_collection_id();
    api.create_collection(owner.clone(), collection_id, Default::default())
        .unwrap();
    collection_id
}

// 铸造NFT
fn mint_nft(
    api: &impl NftsApi<Block>,
    collection_id: CollectionId,
    owner: AccountId32,
    recipient: AccountId32,
) -> ItemId {
    let item_id = api.next_item_id(collection_id);
    api.mint(
        owner.clone(),
        collection_id,
        item_id,
        recipient.clone(),
        Default::default(),
    )
    .unwrap();
    item_id
}

// 转移NFT
fn transfer_nft(
    api: &impl NftsApi<Block>,
    collection_id: CollectionId,
    item_id: ItemId,
    sender: AccountId32,
    recipient: AccountId32,
) {
    api.transfer(sender, collection_id, item_id, recipient)
        .unwrap();
}

// 销毁NFT
fn burn_nft(
    api: &impl NftsApi<Block>,
    collection_id: CollectionId,
    item_id: ItemId,
    owner: AccountId32,
) {
    api.burn(owner, collection_id, item_id).unwrap();
}

fn main() {
    // 初始化运行时客户端
    let client = create_runtime_client();
    
    // 获取API实例
    let api = client.runtime_api();
    
    // 创建测试账户
    let owner = AccountId32::new([1; 32]);
    let recipient = AccountId32::new([2; 32]);
    
    // 执行NFT操作
    let collection_id = create_collection(&api, owner.clone());
    println!("Created collection with ID: {:?}", collection_id);
    
    let item_id = mint_nft(&api, collection_id, owner.clone(), recipient.clone());
    println!("Minted NFT with ID: {:?} in collection: {:?}", item_id, collection_id);
    
    transfer_nft(&api, collection_id, item_id, recipient.clone(), owner.clone());
    println!("Transferred NFT {:?} back to owner", item_id);
    
    burn_nft(&api, collection_id, item_id, owner.clone());
    println!("Burned NFT {:?}", item_id);
}

1 回复

以下是根据提供的内容整理的完整示例demo,先展示内容中提供的示例,然后给出一个整合的完整示例:

内容中提供的示例回顾

创建NFT集合

use pallet_nfts_runtime_api::NftsApi;

fn create_nft_collection(api: &impl NftsApi<Block>, owner: AccountId) -> Result<CollectionId, String> {
    let config = pallet_nfts::CollectionConfig {
        settings: pallet_nfts::CollectionSettings::all_enabled(),
        max_supply: None,
        mint_settings: pallet_nfts::MintSettings::default(),
    };
    
    api.create_collection(owner, config)
        .map_err(|e| format!("Failed to create collection: {:?}", e))
}

铸造NFT

fn mint_nft(
    api: &impl NftsApi<Block>,
    collection_id: CollectionId,
    item_id: ItemId,
    owner: AccountId,
) -> Result<(), String> {
    let config = pallet_nfts::ItemConfig {
        settings: pallet_nfts::ItemSettings::all_enabled(),
    };
    
    api.mint(collection_id, item_id, owner, config)
        .map_err(|e| format!("Failed to mint NFT: {:?}", e))
}

完整示例Demo

下面是一个整合了NFT创建、铸造、转移和元数据设置的完整示例:

use sp_runtime::traits::Block as BlockT;
use pallet_nfts_runtime_api::NftsApi;
use sp_core::crypto::AccountId32;
use sp_runtime::DispatchError;

// 定义类型别名
type Block = sp_runtime::generic::Block<(), ()>;
type CollectionId = u32;
type ItemId = u32;
type AccountId = AccountId32;

// NFT操作结构体
struct NftOperator<A: NftsApi<Block>> {
    api: A,
}

impl<A: NftsApi<Block>> NftOperator<A> {
    // 创建NFT集合
    fn create_collection(&self, owner: AccountId) -> Result<CollectionId, String> {
        let config = pallet_nfts::CollectionConfig {
            settings: pallet_nfts::CollectionSettings::all_enabled(),
            max_supply: None,
            mint_settings: pallet_nfts::MintSettings::default(),
        };
        
        self.api.create_collection(owner, config)
            .map_err(|e| format!("创建集合失败: {:?}", e))
    }

    // 铸造NFT
    fn mint_nft(
        &self,
        collection_id: CollectionId,
        item_id: ItemId,
        owner: AccountId,
    ) -> Result<(), String> {
        let config = pallet_nfts::ItemConfig {
            settings: pallet_nfts::ItemSettings::all_enabled(),
        };
        
        self.api.mint(collection_id, item_id, owner, config)
            .map_err(|e| format!("铸造NFT失败: {:?}", e))
    }

    // 转移NFT所有权
    fn transfer_nft(
        &self,
        collection_id: CollectionId,
        item_id: ItemId,
        new_owner: AccountId,
    ) -> Result<(), String> {
        self.api.transfer(collection_id, item_id, new_owner)
            .map_err(|e| format!("转移NFT失败: {:?}", e))
    }

    // 设置NFT元数据
    fn set_metadata(
        &self,
        collection_id: CollectionId,
        item_id: ItemId,
        metadata: Vec<u8>,
    ) -> Result<(), String> {
        self.api.set_metadata(collection_id, item_id, metadata)
            .map_err(|e| format!("设置元数据失败: {:?}", e))
    }

    // 批量铸造NFT
    fn batch_mint(
        &self,
        collection_id: CollectionId,
        items: Vec<(ItemId, AccountId)>,
    ) -> Result<(), String> {
        for (item_id, owner) in items {
            self.mint_nft(collection_id, item_id, owner)?;
        }
        Ok(())
    }
}

// 示例使用
fn example_usage(api: impl NftsApi<Block>) {
    let operator = NftOperator { api };
    
    // 创建集合
    let owner = AccountId32::new([1u8; 32]);
    let collection_id = operator.create_collection(owner.clone())
        .expect("创建集合失败");
    
    // 铸造NFT
    operator.mint_nft(collection_id, 1, owner.clone())
        .expect("铸造NFT失败");
    
    // 设置元数据
    let metadata = b"NFT Metadata".to_vec();
    operator.set_metadata(collection_id, 1, metadata)
        .expect("设置元数据失败");
    
    // 转移NFT
    let new_owner = AccountId32::new([2u8; 32]);
    operator.transfer_nft(collection_id, 1, new_owner)
        .expect("转移NFT失败");
    
    // 批量铸造
    let items = vec![(2, owner.clone()), (3, owner.clone())];
    operator.batch_mint(collection_id, items)
        .expect("批量铸造失败");
}

代码说明

  1. 类型定义:定义了常用的区块链类型别名
  2. NftOperator结构体:封装了NFT相关操作
  3. 核心方法
    • create_collection: 创建NFT集合
    • mint_nft: 铸造单个NFT
    • transfer_nft: 转移NFT所有权
    • set_metadata: 设置NFT元数据
    • batch_mint: 批量铸造NFT
  4. 错误处理:所有方法都返回Result,包含详细的错误信息
  5. 示例使用:展示了从创建集合到批量铸造的完整流程

这个示例整合了内容中提到的所有核心功能,并添加了更完整的错误处理和类型定义,可以直接用于实际开发中。

回到顶部