Visão Geral

Esta página fornece exemplos abrangentes e reais de implementação do CreateKit em vários cenários. Cada exemplo inclui código completo, tratamento de erros e melhores práticas.

Coleção Básica de NFT

Uma simples coleção de arte com cunhagem gratuita:
Coleção de Arte Básica
import { 
  CollectionManager, 
  BaseMintStorage, 
  b3Testnet 
} from '@b3dotfun/basemint'
import { createPublicClient, createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'

async function createBasicArtCollection() {
  // Configuração dos clientes
  const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`)
  const publicClient = createPublicClient({
    chain: b3Testnet,
    transport: http()
  })
  const walletClient = createWalletClient({
    chain: b3Testnet,
    transport: http(),
    account
  })

  // Inicialização dos serviços
  const collectionManager = new CollectionManager(publicClient)
  const storage = new BaseMintStorage({ baseUrl: 'https://api.basemint.fun' })

  // Definição da coleção
  const artCollection = {
    name: "Galeria de Arte Digital",
    symbol: "DAG", 
    creator: account.address,
    gameOwner: account.address,
    description: "Uma coleção curada de obras de arte digitais",
    image: "https://example.com/art-collection.png",
    maxSupply: 1000n,
    mintPrice: 0n, // Cunhagem gratuita
    maxPerWallet: 5n,
    tokenStandard: "ERC721" as const,
    chainId: 1993
  }

  try {
    console.log("🎨 Criando coleção de arte...")

    // Geração da assinatura do criador
    const creatorSignature = await collectionManager.generateCreatorSignature(
      walletClient,
      artCollection
    )

    // Previsão do endereço
    const predictedAddress = collectionManager.predictCollectionAddress(
      artCollection,
      creatorSignature
    )
    console.log(`📍 Endereço da coleção: ${predictedAddress}`)

    // Submissão ao armazenamento
    await storage.submitCollection(artCollection, creatorSignature)
    console.log("✅ Metadados da coleção armazenados")

    // Implantação e cunhagem do primeiro NFT
    const deployerSignature = await collectionManager.generateDeployerSignature(
      walletClient,
      predictedAddress
    )

    const collection = collectionManager.createCollection(predictedAddress, "ERC721")
    const mintTx = await collection.mint(
      walletClient,
      1n,
      undefined,
      0n,
      [],
      creatorSignature,
      deployerSignature
    )

    console.log(`🎉 Coleção implantada e primeiro NFT cunhado: ${mintTx}`)
    return { collection, predictedAddress, mintTx }

  } catch (error) {
    console.error("❌ Falha ao criar coleção de arte:", error)
    throw error
  }
}

// Uso
createBasicArtCollection()
  .then(result => console.log("Coleção criada com sucesso:", result))
  .catch(error => console.error("Criação falhou:", error))

Coleção de Jogos com Lista Branca

Uma coleção de jogos com acesso por lista branca em níveis:
import { 
  CollectionManager, 
  WhitelistManager,
  BaseMintStorage,
  RewardTracker,
  b3Testnet 
} from '@b3dotfun/basemint'
import { createPublicClient, createWalletClient, http, parseEther } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'

class GamingCollectionManager {
  private publicClient: any
  private walletClient: any
  private collectionManager: CollectionManager
  private storage: BaseMintStorage
  private rewardTracker: RewardTracker

  constructor(privateKey: string) {
    const account = privateKeyToAccount(privateKey as `0x${string}`)
    
    this.publicClient = createPublicClient({
      chain: b3Testnet,
      transport: http()
    })
    
    this.walletClient = createWalletClient({
      chain: b3Testnet,
      transport: http(),
      account
    })

    this.collectionManager = new CollectionManager(this.publicClient)
    this.storage = new BaseMintStorage({ baseUrl: 'https://api.basemint.fun' })
    this.rewardTracker = new RewardTracker(this.publicClient)
  }

  async createGamingCollection() {
    // Definição dos níveis de jogadores
    const playerTiers = {
      legendary: [
        "0x1111111111111111111111111111111111111111",
        "0x2222222222222222222222222222222222222222"
      ],
      epic: [
        "0x3333333333333333333333333333333333333333",
        "0x4444444444444444444444444444444444444444",
        "0x5555555555555555555555555555555555555555"
      ],
      rare: [
        "0x6666666666666666666666666666666666666666",
        "0x7777777777777777777777777777777777777777",
        "0x8888888888888888888888888888888888888888"
      ]
    }

    // Criação da lista branca combinada
    const allPlayers = [
      ...playerTiers.legendary.map(address => ({ address })),
      ...playerTiers.epic.map(address => ({ address })),
      ...playerTiers.rare.map(address => ({ address }))
    ]

    const whitelist = new WhitelistManager(allPlayers)
    const merkleRoot = whitelist.getRoot()

    // Definição da coleção
    const gamingCollection = {
      name: "Itens de Jogo Lendários",
      symbol: "LGI",
      creator: this.walletClient.account.address,
      gameOwner: "0x9999999999999999999999999999999999999999", // Plataforma de jogo
      description: "Itens exclusivos de jogo para os melhores jogadores",
      image: "https://example.com/gaming-collection.png",
      
      // Configuração da lista branca
      isWhitelistEnabled: true,
      whitelistMerkleRoot: merkleRoot,
      
      // Preços e limites
      maxSupply: 500n,
      mintPrice: parseEther("0.01"),
      maxPerWallet: 3n,
      
      // Temporização - fase da lista branca por 24 horas
      startTime: BigInt(Math.floor(Date.now() / 1000)),
      endTime: BigInt(Math.floor(Date.now() / 1000) + 86400 * 7),
      
      tokenStandard: "ERC1155" as const,
      chainId: 1993,
      
      // Metadados específicos do jogo
      attributes: [
        { trait_type: "Categoria", value: "Jogo" },
        { trait_type: "Raridade", value: "Lendário" },
        { trait_type: "Jogo", value: "RPG de Fantasia" }
      ]
    }

    try {
      console.log("🎮 Criando coleção de jogos...")

      // Geração das assinaturas
      const creatorSignature = await this.collectionManager.generateCreatorSignature(
        this.walletClient,
        gamingCollection
      )

      const predictedAddress = this.collectionManager.predictCollectionAddress(
        gamingCollection,
        creatorSignature
      )

      // Submissão ao armazenamento com referência de jogo
      await this.storage.submitCollection(
        gamingCollection,
        creatorSignature,
        "jogo-rpg-de-fantasia" // ID do referenciador
      )

      console.log(`✅ Coleção de jogos armazenada em: ${predictedAddress}`)

      return {
        collection: gamingCollection,
        predictedAddress,
        whitelist,
        playerTiers
      }

    } catch (error) {
      console.error("❌ Falha na criação da coleção de jogos:", error)
      throw error
    }
  }

  async mintForPlayer(
    collectionAddress: string,
    whitelist: WhitelistManager,
    playerAddress: string,
    quantity: bigint = 1n
  ) {
    try {
      // Verifica se a coleção está implantada
      const collection = this.collectionManager.createCollection(collectionAddress, "ERC1155")
      const isDeployed = await collection.isDeployed()

      if (!isDeployed) {
        // Primeira cunhagem - implantação da coleção
        const deployerSignature = await this.collectionManager.generateDeployerSignature(
          this.walletClient,
          collectionAddress
        )

        // Obtenção da prova da lista branca
        const proof = whitelist.getProof(playerAddress)
        const mintPrice = parseEther("0.01") * quantity

        const tx = await collection.mint(
          this.walletClient,
          quantity,
          "https://example.com/espada-lendaria.json", // Metadados do item específico
          mintPrice,
          proof,
          undefined, // assinatura do criador necessária para a implantação
          deployerSignature
        )

        console.log(`🚀 Coleção implantada e item cunhado: ${tx}`)
        return tx

      } else {
        // Cunhagem regular
        const proof = whitelist.getProof(playerAddress)
        const mintPrice = parseEther("0.01") * quantity

        const tx = await collection.mint(
          this.walletClient,
          quantity,
          "https://example.com/espada-lendaria.json",
          mintPrice,
          proof
        )

        console.log(`⚔️ Item de jogo cunhado: ${tx}`)
        return tx
      }

    } catch (error: any) {
      if (error.message.includes('Invalid merkle proof')) {
        console.error(`❌ Jogador ${playerAddress} não está na lista branca`)
      } else {
        console.error("❌ Cunhagem falhou:", error)
      }
      throw error
    }
  }

  async getPlayerRewards(collectionAddress: string, playerAddress: string) {
    const escrowAddress = this.collectionManager.getEscrowAddress()
    
    // Verifica se o jogador foi o primeiro a cunhar
    const firstMinterRewards = await this.rewardTracker.getRecipientRewards(
      escrowAddress,
      collectionAddress,
      "FIRST_MINTER",
      playerAddress
    )

    // Obtém estatísticas da coleção
    const collectionRewards = await this.rewardTracker.getCollectionRewards(
      escrowAddress,
      collectionAddress
    )

    return {
      firstMinterRewards: firstMinterRewards.toString(),
      collectionTotalRewards: collectionRewards.totalRewards.toString(),
      collectionMints: collectionRewards.totalMints.toString()
    }
  }
}

// Exemplo de uso
async function main() {
  const gameManager = new GamingCollectionManager(process.env.PRIVATE_KEY!)
  
  // Criação da coleção
  const { predictedAddress, whitelist, playerTiers } = await gameManager.createGamingCollection()
  
  // Simulação de cunhagem de jogador lendário
  const legendaryPlayer = playerTiers.legendary[0]
  await gameManager.mintForPlayer(predictedAddress, whitelist, legendaryPlayer, 2n)
  
  // Verificação de recompensas
  const rewards = await gameManager.getPlayerRewards(predictedAddress, legendaryPlayer)
  console.log("Recompensas do jogador:", rewards)
}

main().catch(console.error)

Plataforma Multi-Coleção

Uma plataforma gerenciando múltiplas coleções:
import { 
  CollectionManager, 
  BaseMintStorage,
  RewardTracker,
  b3Testnet 
} from '@b3dotfun/basemint'

class NFTPlatform {
  private collectionManager: CollectionManager
  private storage: BaseMintStorage
  private rewardTracker: RewardTracker
  private platformId: string

  constructor(
    publicClient: any,
    platformId: string
  ) {
    this.collectionManager = new CollectionManager(publicClient)
    this.storage = new BaseMintStorage({ baseUrl: 'https://api.basemint.fun' })
    this.rewardTracker = new RewardTracker(publicClient)
    this.platformId = platformId
  }

  async registerPlatform() {
    try {
      await this.storage.registerReferrer(this.platformId, {
        name: "Minha Plataforma NFT",
        website: "https://mynftplatform.com",
        description: "Uma plataforma para criar e gerenciar coleções de NFT"
      })
      console.log(`✅ Plataforma registrada: ${this.platformId}`)
    } catch (error: any) {
      if (error.message.includes('already exists')) {
        console.log(`ℹ️ Plataforma ${this.platformId} já registrada`)
      } else {
        throw error
      }
    }
  }

  async createCollection(
    creatorWalletClient: any,
    collectionData: {
      name: string
      symbol: string
      description: string
      image: string
      maxSupply: bigint
      mintPrice: bigint
      category: string
    }
  ) {
    const collection = {
      ...collectionData,
      creator: creatorWalletClient.account.address,
      gameOwner: creatorWalletClient.account.address, // A plataforma pode ser o proprietário do jogo
      tokenStandard: "ERC721" as const,
      chainId: 1993,
      attributes: [
        { trait_type: "Plataforma", value: "Minha Plataforma NFT" },
        { trait_type: "Categoria", value: collectionData.category }
      ]
    }

    // Geração da assinatura e armazenamento
    const creatorSignature = await this.collectionManager.generateCreatorSignature(
      creatorWalletClient,
      collection
    )

    const predictedAddress = this.collectionManager.predictCollectionAddress(
      collection,
      creatorSignature
    )

    await this.storage.submitCollection(
      collection,
      creatorSignature,
      this.platformId
    )

    return {
      collection,
      predictedAddress,
      creatorSignature
    }
  }

  async deployCollection(
    deployerWalletClient: any,
    collectionAddress: string,
    creatorSignature: string
  ) {
    const deployerSignature = await this.collectionManager.generateDeployerSignature(
      deployerWalletClient,
      collectionAddress
    )

    const collection = this.collectionManager.createCollection(collectionAddress, "ERC721")
    
    const tx = await collection.mint(
      deployerWalletClient,
      1n,
      undefined,
      0n, // O implantador recebe a primeira cunhagem gratuitamente
      [],
      creatorSignature,
      deployerSignature
    )

    return tx
  }

  async getPlatformStats() {
    const collections = await this.storage.queryCollections({
      referrer: this.platformId
    })

    const stats = {
      totalCollections: collections.total,
      deployed: 0,
      undeployed: 0,
      totalVolume: 0n,
      totalRewards: 0n
    }

    const escrowAddress = this.collectionManager.getEscrowAddress()

    for (const collection of collections.collections) {
      if (collection.isDeployed) {
        stats.deployed++
        
        // Obtém recompensas da coleção
        const rewards = await this.rewardTracker.getCollectionRewards(
          escrowAddress,
          collection.address
        )
        stats.totalRewards += rewards.totalRewards
      } else {
        stats.undeployed++
      }
    }

    return {
      ...stats,
      collections: collections.collections
    }
  }

  async getCreatorDashboard(creatorAddress: string) {
    const collections = await this.storage.queryCollections({
      creator: creatorAddress,
      referrer: this.platformId
    })

    const escrowAddress = this.collectionManager.getEscrowAddress()
    let totalCreatorRewards = 0n

    const collectionStats = await Promise.all(
      collections.collections.map(async (collection) => {
        if (collection.isDeployed) {
          const rewards = await this.rewardTracker.getRecipientRewards(
            escrowAddress,
            collection.address,
            "CREATOR",
            creatorAddress
          )
          totalCreatorRewards += rewards
          
          return {
            ...collection,
            creatorRewards: rewards.toString()
          }
        }
        return {
          ...collection,
          creatorRewards: "0"
        }
      })
    )

    return {
      totalCollections: collections.total,
      totalCreatorRewards: totalCreatorRewards.toString(),
      collections: collectionStats
    }
  }
}

// Uso
async function runPlatform() {
  const publicClient = createPublicClient({
    chain: b3Testnet,
    transport: http()
  })

  const platform = new NFTPlatform(publicClient, "minha-plataforma-nft")
  
  // Registro da plataforma
  await platform.registerPlatform()
  
  // Criador cria coleção
  const creatorAccount = privateKeyToAccount(process.env.CREATOR_PRIVATE_KEY as `0x${string}`)
  const creatorWalletClient = createWalletClient({
    chain: b3Testnet,
    transport: http(),
    account: creatorAccount
  })

  const { predictedAddress, creatorSignature } = await platform.createCollection(
    creatorWalletClient,
    {
      name: "Coleção Incrível de Arte",
      symbol: "AAC",
      description: "Obras de arte digitais incríveis",
      image: "https://example.com/awesome-art.png",
      maxSupply: 1000n,
      mintPrice: parseEther("0.005"),
      category: "Arte"
    }
  )

  // Implantação da coleção
  const deployerAccount = privateKeyToAccount(process.env.DEPLOYER_PRIVATE_KEY as `0x${string}`)
  const deployerWalletClient = createWalletClient({
    chain: b3Testnet,
    transport: http(),
    account: deployerAccount
  })

  const deployTx = await platform.deployCollection(
    deployerWalletClient,
    predictedAddress,
    creatorSignature
  )

  console.log(`🚀 Coleção implantada: ${deployTx}`)

  // Obtenção das estatísticas da plataforma
  const stats = await platform.getPlatformStats()
  console.log("Estatísticas da plataforma:", stats)

  // Obtenção do painel do criador
  const dashboard = await platform.getCreatorDashboard(creatorAccount.address)
  console.log("Painel do criador:", dashboard)
}