Overview

This page provides comprehensive, real-world examples of implementing CreateKit in various scenarios. Each example includes complete code, error handling, and best practices.

Basic NFT Collection

A simple art collection with free minting:
Basic Art Collection
import { 
  CollectionManager, 
  BaseMintStorage, 
  b3Testnet 
} from '@b3dotfun/basemint'
import { createPublicClient, createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'

async function createBasicArtCollection() {
  // Setup clients
  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
  })

  // Initialize services
  const collectionManager = new CollectionManager(publicClient)
  const storage = new BaseMintStorage({ baseUrl: 'https://api.basemint.fun' })

  // Define collection
  const artCollection = {
    name: "Digital Art Gallery",
    symbol: "DAG", 
    creator: account.address,
    gameOwner: account.address,
    description: "A curated collection of digital artworks",
    image: "https://example.com/art-collection.png",
    maxSupply: 1000n,
    mintPrice: 0n, // Free minting
    maxPerWallet: 5n,
    tokenStandard: "ERC721" as const,
    chainId: 1993
  }

  try {
    console.log("🎨 Creating art collection...")

    // Generate creator signature
    const creatorSignature = await collectionManager.generateCreatorSignature(
      walletClient,
      artCollection
    )

    // Predict address
    const predictedAddress = collectionManager.predictCollectionAddress(
      artCollection,
      creatorSignature
    )
    console.log(`📍 Collection address: ${predictedAddress}`)

    // Submit to storage
    await storage.submitCollection(artCollection, creatorSignature)
    console.log("✅ Collection metadata stored")

    // Deploy and mint first 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(`🎉 Collection deployed and first NFT minted: ${mintTx}`)
    return { collection, predictedAddress, mintTx }

  } catch (error) {
    console.error("❌ Failed to create art collection:", error)
    throw error
  }
}

// Usage
createBasicArtCollection()
  .then(result => console.log("Collection created successfully:", result))
  .catch(error => console.error("Creation failed:", error))

Gaming Collection with Whitelist

A gaming collection with tiered whitelist access:

Multi-Collection Platform

A platform managing multiple collections:

Marketplace Integration

Integrating CreateKit with a marketplace:
Marketplace Integration
import { 
  CollectionManager,
  BaseMintStorage,
  RewardTracker 
} from '@b3dotfun/basemint'

class NFTMarketplace {
  private storage: BaseMintStorage
  private collectionManager: CollectionManager
  private rewardTracker: RewardTracker

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

  // Discover collections for marketplace display
  async discoverCollections(filters?: {
    category?: string
    minSupply?: number
    maxPrice?: string
    deployed?: boolean
  }) {
    const queryFilters: any = {}
    
    if (filters?.deployed !== undefined) {
      queryFilters.deployed = filters.deployed
    }

    const collections = await this.storage.queryCollections({
      ...queryFilters,
      limit: 50,
      sortBy: "createdAt",
      sortOrder: "desc"
    })

    // Enrich with on-chain data for deployed collections
    const enrichedCollections = await Promise.all(
      collections.collections.map(async (collection) => {
        if (collection.isDeployed) {
          const contract = this.collectionManager.createCollection(
            collection.address,
            collection.tokenStandard
          )

          const [totalSupply, mintPrice, maxSupply] = await Promise.all([
            contract.totalSupply(),
            contract.mintPrice(),
            contract.maxSupply()
          ])

          return {
            ...collection,
            onChainData: {
              totalSupply: totalSupply.toString(),
              mintPrice: mintPrice.toString(),
              maxSupply: maxSupply.toString(),
              remainingSupply: (maxSupply - totalSupply).toString()
            }
          }
        }

        return collection
      })
    )

    // Apply additional filters
    let filtered = enrichedCollections

    if (filters?.category) {
      filtered = filtered.filter(c => 
        c.attributes?.some(attr => 
          attr.trait_type === "Category" && 
          attr.value.toLowerCase().includes(filters.category!.toLowerCase())
        )
      )
    }

    if (filters?.minSupply) {
      filtered = filtered.filter(c => 
        !c.onChainData || 
        parseInt(c.onChainData.totalSupply) >= filters.minSupply!
      )
    }

    return filtered
  }

  // Get trending collections
  async getTrendingCollections(timeframe: '24h' | '7d' | '30d' = '24h') {
    const collections = await this.storage.queryCollections({
      deployed: true,
      limit: 100
    })

    const escrowAddress = this.collectionManager.getEscrowAddress()

    // Get reward data to determine trending status
    const collectionsWithMetrics = await Promise.all(
      collections.collections.map(async (collection) => {
        const rewards = await this.rewardTracker.getCollectionRewards(
          escrowAddress,
          collection.address
        )

        return {
          ...collection,
          metrics: {
            totalMints: parseInt(rewards.totalMints.toString()),
            totalRewards: rewards.totalRewards.toString(),
            // Calculate trend score based on mints and rewards
            trendScore: parseInt(rewards.totalMints.toString()) * 
                       parseInt(rewards.totalRewards.toString())
          }
        }
      })
    )

    // Sort by trend score
    return collectionsWithMetrics
      .sort((a, b) => b.metrics.trendScore - a.metrics.trendScore)
      .slice(0, 10)
  }

  // Get collection details for marketplace display
  async getCollectionDetails(address: string) {
    try {
      // Get metadata from storage
      const collection = await this.storage.getCollection(address)
      
      if (!collection.isDeployed) {
        return {
          ...collection,
          status: 'pending-deployment',
          onChainData: null
        }
      }

      // Get on-chain data
      const contract = this.collectionManager.createCollection(
        address,
        collection.tokenStandard
      )

      const [info, isActive] = await Promise.all([
        contract.getCollectionInfo(),
        contract.isMintingActive()
      ])

      // Get reward metrics
      const escrowAddress = this.collectionManager.getEscrowAddress()
      const rewards = await this.rewardTracker.getCollectionRewards(
        escrowAddress,
        address
      )

      return {
        ...collection,
        status: 'deployed',
        onChainData: {
          name: info.name,
          symbol: info.symbol,
          totalSupply: info.totalSupply.toString(),
          maxSupply: info.maxSupply.toString(),
          mintPrice: info.mintPrice.toString(),
          maxPerWallet: info.maxPerWallet.toString(),
          isMintingActive: isActive,
          remainingSupply: (info.maxSupply - info.totalSupply).toString()
        },
        metrics: {
          totalMints: parseInt(rewards.totalMints.toString()),
          totalRewards: rewards.totalRewards.toString(),
          averageRewardPerMint: rewards.totalMints > 0n 
            ? (rewards.totalRewards / rewards.totalMints).toString()
            : "0"
        }
      }

    } catch (error) {
      console.error(`Failed to get collection details for ${address}:`, error)
      throw error
    }
  }

  // Search collections
  async searchCollections(query: string) {
    const searchResults = await this.storage.searchCollections({
      query,
      limit: 20
    })

    return searchResults.collections
  }

  // Get collections by creator for profile pages
  async getCreatorCollections(creatorAddress: string) {
    const collections = await this.storage.queryCollections({
      creator: creatorAddress
    })

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

    const enriched = 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 {
      collections: enriched,
      totalCreatorRewards: totalCreatorRewards.toString(),
      stats: {
        total: collections.total,
        deployed: enriched.filter(c => c.isDeployed).length,
        pending: enriched.filter(c => !c.isDeployed).length
      }
    }
  }
}

// Usage in marketplace
async function marketplaceDemo() {
  const publicClient = createPublicClient({
    chain: b3Testnet,
    transport: http()
  })

  const marketplace = new NFTMarketplace(publicClient)

  // Get homepage collections
  const featuredCollections = await marketplace.discoverCollections({
    deployed: true
  })
  console.log("Featured collections:", featuredCollections.slice(0, 6))

  // Get trending collections
  const trending = await marketplace.getTrendingCollections('7d')
  console.log("Trending collections:", trending)

  // Search functionality
  const searchResults = await marketplace.searchCollections("art")
  console.log("Search results for 'art':", searchResults)

  // Get specific collection details
  if (featuredCollections.length > 0) {
    const details = await marketplace.getCollectionDetails(
      featuredCollections[0].address
    )
    console.log("Collection details:", details)
  }
}

marketplaceDemo().catch(console.error)

React Components

Frontend components for CreateKit integration:

Testing Examples

Comprehensive testing patterns:

Best Practices Summary

Security

  • Always validate signatures before deployment
  • Use environment variables for sensitive data
  • Implement proper error handling
  • Test thoroughly on testnet first

Performance

  • Cache frequently accessed data
  • Use batch operations when possible
  • Implement proper loading states
  • Optimize for gas efficiency

User Experience

  • Provide clear feedback during operations
  • Show estimated costs upfront
  • Handle errors gracefully
  • Implement proper validation

Maintainability

  • Write comprehensive tests
  • Document your code
  • Use TypeScript for type safety
  • Follow consistent patterns

Next Steps