Skip to content

bonkcomputer/framework

Repository files navigation

Bonk Computer Logo

Bonk Computer Framework❗❗❗

BCT CA: D3CV7esuBSRB9Aw3PHRNHVz4g6b4TqeVLKhgkbonk

Production-grade Solana Web3 development framework built on the most robust and future proof foundation. Completely Open-Sourced and built in Public by the chads at https://operate.fun and https://bonk.computer

Solana Native Next.js 14+ TypeScript First E2B Firecracker AI Powered MIT License

BZZT Welcome to the Bonk Computer Framework, a modular, open-source, Solana-native toolkit for Web3, AI, and Virtual Machines (VMs)/Virtual Private Servers (VPSs). Built on Next-Forge's production-grade foundation and powered by @solana's 400ms block times. BOOP

🚀 Quick Start & Installation

Global Installation

Install the Bonk Computer Framework CLI globally:

# Install globally via npm
npm install -g @bonkcomputer/framework

# Or install via pnpm (recommended)
pnpm add -g @bonkcomputer/framework

# Or install via yarn
yarn global add @bonkcomputer/framework

Create a New Project

# Full command
bonk-computer-framework init my-solana-app

# Or use the short alias
bcf init my-solana-app

# Create with specific template
bcf init my-game --template game
bcf init my-defi-app --template defi
bcf init my-nft-marketplace --template nft
bcf init simple-app --template minimal

Available Templates

  • 🚀 default - Full-stack Solana dApp with all features
  • 🎮 game - Real-time multiplayer game with Convex
  • 🏪 defi - Decentralized exchange and trading platform
  • 🖼️ nft - NFT marketplace and minting application
  • ⚡ minimal - Basic Solana integration only

Add Components to Existing Projects

# Add wallet connection components
bcf add wallet

# Add Jupiter-powered token swap
bcf add swap

# Add NFT gallery and minting
bcf add nft

# Add real-time multiplayer game features
bcf add game

# Add DeFi staking and lending components
bcf add defi

# Add AI-powered development tools
bcf add ai

# Add E2B code execution sandboxes
bcf add vm

Development Commands

# Navigate to your project
cd my-solana-app

# Install dependencies
pnpm install

# Set up environment variables
cp .env.example .env.local
# Add your API keys to .env.local

# Start development server
pnpm run dev

# Start real-time backend (if using Convex)
pnpm run convex:dev

Update Framework

# Check for updates
bcf update --check

# Update to latest version
bcf update

🚀 Why We Use Next-Forge in the Bonk Computer Framework:

This framework leverages Next-Forge's production-grade Turborepo template to provide unmatched benefits for Solana Web3 development:

🏗️ Production-Ready Foundation

  • Next-Forge Integration: Built on Vercel's battle-tested Next.js boilerplate with minimal configuration
  • Turborepo Monorepo: Optimized workspace management for complex Web3 applications
  • TypeScript-First: Pre-configured TypeScript environment with strict type safety
  • Scalable Architecture: Modular design supporting multiple apps and packages

Vercel Ecosystem Synergy

  • Seamless Deployment: Native integration with Vercel's Frontend Cloud and serverless functions
  • AI SDK Integration: Direct access to Vercel's AI SDK for Claude, GPT-4, and Qwen models
  • Edge Runtime: Optimized performance with Vercel's edge computing infrastructure
  • Zero-Config Deployment: One-command deployment with automatic optimization

🔥 Advanced Web3 Capabilities

  • Firecracker MicroVMs: E2B's AWS Firecracker sandboxes with ~150ms boot times
  • Solana-Native: Deep integration with Solana's ecosystem (Helius, Jupiter, Tapestry)
  • AI-Driven Development: Automated smart contract generation and debugging
  • Web3 Authentication: Seamless wallet integration with Privy.io

🌟 Features

  • 🔗 Solana-Native Integration: Connects to Solana via @solana/kit, with APIs from Helius (RPC/DAS), Jupiter (liquidity), and Tapestry (identity)
  • 🤖 AI-Powered Development: Vercel AI SDK integrates Anthropic's Claude, Alibaba's Qwen 2.5/3 VL, and OpenAI's models for code generation and debugging
  • 🔐 Web3 Authentication: Solana, Jup, and Privy.io to enables passwordless $BONK/$BCT wallet access with customizable auth flows
  • ⚡ E2B, Firecracker and MicroVMs: E2B's SDK powers secure, ~150ms sandboxes for Python, Rust, JavaScript, and npm/pip packages
  • 🔄 Real-time Multiplayer: Convex enables instant data synchronization for collaborative dApps, games, and multi-user experiences
  • ☁️ Serverless Deployment: Vercel's Frontend Cloud ensures scalable, low-latency builds with edge optimization
  • 🧩 Modular & Open-Source: MIT-licensed, GitHub-forkable, with community-driven roadmap
  • 🎯 Meme-Powered Community: $BONK & $BCT unlock VMs and fuels operations.

🎯 Use Cases

  • 🏪 dApp Development: Build Solana-based DEXs, marketplaces, or games using browser-based VMs
  • 🎮 Real-time Multiplayer Games: Create collaborative Web3 games with instant state synchronization across players
  • 🖼️ NFT Projects: Mint, manage, and display NFTs with Helius DAS API and AI-generated metadata
  • 💰 DeFi Protocols: Create staking, lending, or trading platforms with Jupiter's liquidity APIs
  • 🧠 AI-Driven Workflows: Use Claude/Qwen to generate smart contracts or analyze Solana transactions
  • 👥 Collaborative dApps: Build real-time collaborative tools like shared whiteboards, code editors, or document editors
  • 🏛️ Community DAOs: Fork the framework for $BCT-gated governance tools or social platforms with live voting
  • 🖥️ Virtual Desktops: Host $BCT-themed dashboards or Web3 apps in E2B's graphical sandboxes with multi-user support

🛠️ Tech Stack

Core Framework

  • Next-Forge: Production-grade Next.js 14+ with Turborepo
  • Next.js: React framework with App Router and Server Components
  • TypeScript: Strict type safety and enhanced developer experience
  • Turborepo: High-performance monorepo build system

Web3 & Blockchain

  • Official Solana SDK (@solana/web3.js): Official Solana JavaScript SDK for blockchain interaction
  • Solana-Starter-Kit: Production-ready Solana development foundation by Primitives-xyz
  • Solana-Agent-Kit: AI-powered Solana agent framework with autonomous transaction capabilities
  • Solana-App-Kit: Comprehensive Solana application development toolkit
  • JupiverseKit: Ultimate React components library for Jupiter-powered Solana applications
  • Helius: Enhanced Solana RPC and DAS API for comprehensive blockchain data
  • Jupiter: Best-in-class liquidity aggregation and DEX trading APIs
  • Tapestry: Advanced social graph and onchain identity management
  • Privy.io: Seamless Web3 authentication and multi-wallet management

AI & Machine Learning

Real-time Backend & Database

  • Convex: Real-time reactive database with serverless functions for multiplayer apps and collaborative dApps
  • TypeScript-First: End-to-end type safety from database to frontend
  • Real-time Sync: Automatic data synchronization across all connected clients
  • Optimistic Updates: Instant UI updates with automatic conflict resolution

Virtualization & Sandboxing

  • E2B SDK: Secure code execution in Firecracker microVMs
  • AWS Firecracker: Lightweight virtualization with KVM isolation
  • Performance: ~150ms boot times, <5 MiB memory overhead, 150 microVMs/second/host

Development & Deployment

  • Vercel: Serverless deployment and edge computing
  • Biome: Fast linter and formatter
  • Vitest: Unit testing framework
  • Playwright: End-to-end testing

📋 Prerequisites

Before getting started, ensure you have:

System Requirements

  • Node.js: >= 18.x (LTS recommended)
  • Package Manager: pnpm >= 8.x (recommended) or npm >= 9.x
  • Git: Latest version for repository management
  • Operating System: Windows 10+, macOS 10.15+, or Linux (Ubuntu 20.04+)

Web3 Requirements

  • Solana Wallet: Phantom, Solflare, or compatible wallet with $BONK/$BCT
  • Solana CLI (optional): For advanced blockchain interactions

API Keys Required

You'll need to obtain API keys from the following services:

Service Purpose Required Free Tier
Convex Real-time Database & Backend
E2B Firecracker Sandbox API
Helius Solana RPC/DAS
Privy Web3 Authentication
Jupiter Liquidity APIs
Tapestry Identity APIs
OpenAI AI Framework
Anthropic Claude AI
Alibaba Qwen Multimodal AI ⚠️
Vercel Deployment/AI SDK

🚀 Quick Start

1. Initialize Project

Create a new Bonk Computer Framework project using Next-Forge:

# Create new project
npx next-forge@latest init bonk-computer-app

# Navigate to project directory
cd bonk-computer-app

# Install Core Solana Dependencies
pnpm add @solana/web3.js @solana/wallet-adapter-react @solana/wallet-adapter-wallets
pnpm add @solana/wallet-adapter-react-ui @solana/wallet-adapter-base

# Install Solana Toolkit Dependencies
pnpm add solana-agent-kit solana-app-kit
pnpm add @coral-xyz/anchor bs58

# Install JupiverseKit for Jupiter Integration
pnpm add jupiverse-kit

# Install E2B and AI Dependencies
pnpm add @e2b/code-interpreter @privy-io/react-auth
pnpm add ai @ai-sdk/anthropic @ai-sdk/openai @ai-sdk/google

# Install Convex for Real-time Backend
pnpm add convex @convex-dev/react

# Install Additional Utilities
pnpm add @metaplex-foundation/js @metaplex-foundation/mpl-token-metadata
pnpm add @project-serum/anchor @project-serum/serum

2. Environment Configuration

Copy and configure your environment variables:

# Copy environment template
cp .env.example .env.local

Update your .env.local file:

# Next.js Configuration
NEXT_PUBLIC_APP_URL=http://localhost:3000
NEXT_PUBLIC_APP_NAME="Bonk Computer"

# E2B Firecracker Sandboxes
NEXT_PUBLIC_E2B_API_KEY=your_e2b_api_key_here

# Solana Configuration
NEXT_PUBLIC_SOLANA_NETWORK=mainnet-beta
NEXT_PUBLIC_RPC_URL=https://api.mainnet-beta.solana.com
NEXT_PUBLIC_HELIUS_API_KEY=your_helius_api_key_here
NEXT_PUBLIC_JUPITER_API_KEY=your_jupiter_api_key_here
NEXT_PUBLIC_TAPESTRY_API_KEY=your_tapestry_api_key_here
SOLANA_PRIVATE_KEY=your_base58_private_key_here

# JupiverseKit Configuration
NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID=your_wallet_connect_project_id_here
NEXT_PUBLIC_JUPITER_THEME=jupiter
NEXT_PUBLIC_JUPITER_ENV=mainnet-beta

# Web3 Authentication
NEXT_PUBLIC_PRIVY_APP_ID=your_privy_app_id_here
PRIVY_APP_SECRET=your_privy_app_secret_here

# AI Configuration
OPENAI_API_KEY=your_openai_api_key_here
ANTHROPIC_API_KEY=your_anthropic_api_key_here
ALIBABA_QWEN_API_KEY=your_qwen_api_key_here

# Vercel Configuration
VERCEL_TOKEN=your_vercel_token_here
NEXT_PUBLIC_VERCEL_URL=your_vercel_url_here

# Convex Real-time Database
CONVEX_DEPLOYMENT=your_convex_deployment_url_here
NEXT_PUBLIC_CONVEX_URL=your_convex_url_here

# Database (if using)
DATABASE_URL=your_database_url_here

# Analytics (optional)
NEXT_PUBLIC_POSTHOG_KEY=your_posthog_key_here
NEXT_PUBLIC_GOOGLE_ANALYTICS_ID=your_ga_id_here

3. Install Dependencies

# Install all dependencies
pnpm install

# Verify installation
pnpm run build

4. Initialize Convex Real-time Backend

Set up Convex for real-time multiplayer capabilities:

# Initialize Convex
npx convex dev --once

# This creates convex/ directory and convex.json
# Follow the prompts to set up your Convex deployment

Add Convex environment variables to your .env.local:

# Add these to your existing .env.local
CONVEX_DEPLOYMENT=your_convex_deployment_url_here
NEXT_PUBLIC_CONVEX_URL=your_convex_url_here

5. Development Server

Start the development server:

# Start Convex backend (in one terminal)
npx convex dev

# Start Next.js development server (in another terminal)
pnpm run dev

# Open in browser
open http://localhost:3000

6. Verify Installation

Your Bonk Computer Framework should now be running with:

  • ✅ Next.js 14+ with App Router
  • ✅ TypeScript configuration
  • ✅ Turborepo monorepo setup
  • ✅ Solana Web3 integration
  • ✅ Convex real-time backend
  • ✅ E2B Firecracker sandboxes
  • ✅ AI-powered development tools

📁 Project Structure

bonk-computer-framework/
├── 📄 README.md                    # This comprehensive guide
├── 📄 package.json                 # Root package configuration
├── 📄 turbo.json                   # Turborepo configuration
├── 📄 tsconfig.json                # TypeScript configuration
├── 📄 biome.json                   # Linting and formatting
├── 📄 .env.example                 # Environment template
├── 📄 .env.local                   # Your API keys (gitignored)
│
├── 📁 convex/                      # Convex real-time backend
│   ├── 📄 convex.json              # Convex configuration
│   ├── 📄 schema.ts                # Database schema definitions
│   ├── 📄 auth.config.ts           # Authentication configuration
│   ├── 📄 game.ts                  # Game state functions
│   ├── 📄 collaboration.ts         # Collaborative features
│   ├── 📄 solana.ts                # Solana integration actions
│   └── 📄 _generated/              # Auto-generated types
│
├── 📁 apps/                        # Next-Forge applications
│   ├── 📁 api/                     # Backend API application
│   │   ├── 📄 package.json         # API-specific dependencies
│   │   ├── 📄 next.config.ts       # Next.js API configuration
│   │   └── 📁 app/                 # API routes and handlers
│   │       ├── 📁 health/          # Health check endpoints
│   │       ├── 📁 webhooks/        # Webhook handlers
│   │       └── 📁 cron/            # Scheduled tasks
│   │
│   ├── 📁 app/                     # Main Web3 application
│   │   ├── 📄 package.json         # App-specific dependencies
│   │   ├── 📄 next.config.ts       # Next.js app configuration
│   │   ├── 📄 middleware.ts        # Authentication middleware
│   │   └── 📁 app/                 # App Router pages
│   │       ├── 📁 (authenticated)/ # Protected routes
│   │       │   ├── 📄 page.tsx     # Dashboard
│   │       │   ├── 📁 components/  # Shared components
│   │       │   ├── 📁 search/      # Search functionality
│   │       │   └── 📁 webhooks/    # Webhook management
│   │       ├── 📁 (unauthenticated)/ # Public routes
│   │       │   ├── 📁 sign-in/     # Authentication pages
│   │       │   └── 📁 sign-up/     # Registration pages
│   │       └── 📁 actions/         # Server actions
│   │
│   ├── 📁 docs/                    # Documentation site
│   │   ├── 📄 mint.json            # Mintlify configuration
│   │   ├── 📁 api-reference/       # API documentation
│   │   └── 📁 essentials/          # Essential guides
│   │
│   ├── 📁 storybook/               # Component library
│   │   ├── 📄 package.json         # Storybook dependencies
│   │   └── 📁 stories/             # Component stories
│   │
│   └── 📁 web/                     # Marketing website
│       ├── 📄 package.json         # Web-specific dependencies
│       └── 📁 app/                 # Marketing pages
│
├── 📁 packages/                    # Shared packages
│   ├── 📁 ai/                      # AI integration package
│   │   ├── 📄 index.ts             # AI SDK exports
│   │   ├── 📁 components/          # AI UI components
│   │   └── 📁 lib/                 # AI utilities
│   │
│   ├── 📁 auth/                    # Authentication package
│   │   ├── 📄 client.ts            # Client-side auth
│   │   ├── 📄 server.ts            # Server-side auth
│   │   ├── 📄 middleware.ts        # Auth middleware
│   │   └── 📁 components/          # Auth components
│   │
│   ├── 📁 design-system/           # UI component library
│   │   ├── 📄 index.tsx            # Component exports
│   │   ├── 📁 components/          # Reusable UI components
│   │   ├── 📁 hooks/               # Custom React hooks
│   │   └── 📁 styles/              # Global styles
│   │
│   ├── 📁 database/                # Database package
│   │   ├── 📄 index.ts             # Database exports
│   │   └── 📁 prisma/              # Prisma schema
│   │
│   ├── 📁 solana/                  # Solana integration (custom)
│   │   ├── 📄 index.ts             # Solana exports
│   │   ├── 📁 lib/                 # Solana utilities
│   │   ├── 📁 hooks/               # Solana React hooks
│   │   └── 📁 components/          # Solana UI components
│   │
│   ├── 📁 vm/                      # E2B VM integration (custom)
│   │   ├── 📄 index.ts             # VM exports
│   │   ├── 📁 lib/                 # VM management
│   │   └── 📁 components/          # VM UI components
│   │
│   └── 📁 [other-packages]/        # Additional Next-Forge packages
│       ├── analytics/              # Analytics integration
│       ├── cms/                    # Content management
│       ├── collaboration/          # Real-time collaboration
│       ├── email/                  # Email templates
│       ├── feature-flags/          # Feature flag management
│       ├── internationalization/   # i18n support
│       ├── notifications/          # Push notifications
│       ├── observability/          # Monitoring and logging
│       ├── payments/               # Payment processing
│       ├── rate-limit/             # API rate limiting
│       ├── security/               # Security utilities
│       ├── seo/                    # SEO optimization
│       ├── storage/                # File storage
│       ├── testing/                # Testing utilities
│       ├── typescript-config/      # Shared TypeScript configs
│       └── webhooks/               # Webhook utilities
│
├── 📁 scripts/                     # Build and deployment scripts
│   ├── 📄 initialize.ts            # Project initialization
│   └── 📄 update.ts                # Dependency updates
│
└── 📁 turbo/                       # Turborepo generators
    └── 📁 generators/              # Code generators

🔧 Configuration

Solana Configuration

Create packages/solana/config.ts:

import { Connection, clusterApiUrl } from '@solana/web3.js';
import { SolanaAgentKit } from 'solana-agent-kit';

export const SOLANA_CONFIG = {
  network: process.env.NEXT_PUBLIC_SOLANA_NETWORK as 'devnet' | 'mainnet-beta',
  rpcUrl: process.env.NEXT_PUBLIC_RPC_URL ||
    (process.env.NEXT_PUBLIC_HELIUS_API_KEY
      ? `https://rpc.helius.xyz/?api-key=${process.env.NEXT_PUBLIC_HELIUS_API_KEY}`
      : clusterApiUrl('mainnet-beta')),
  commitment: 'confirmed' as const,
  jupiterApiKey: process.env.NEXT_PUBLIC_JUPITER_API_KEY,
  heliusApiKey: process.env.NEXT_PUBLIC_HELIUS_API_KEY,
};

export const connection = new Connection(SOLANA_CONFIG.rpcUrl, SOLANA_CONFIG.commitment);

// Solana Agent Kit Configuration
export const AGENT_CONFIG = {
  rpcUrl: SOLANA_CONFIG.rpcUrl,
  openaiApiKey: process.env.OPENAI_API_KEY,
  heliusApiKey: SOLANA_CONFIG.heliusApiKey,
};

JupiverseKit Configuration

Create packages/solana/jupiter-provider.tsx:

"use client";

import { JupiverseKitProvider } from "jupiverse-kit";
import { ReactNode } from "react";

interface JupiterProviderProps {
  children: ReactNode;
}

export function JupiterProvider({ children }: JupiterProviderProps) {
  return (
    <JupiverseKitProvider
      endpoint={process.env.NEXT_PUBLIC_RPC_URL!}
      theme="jupiter"
      autoConnect={true}
      lang="en"
      env={process.env.NEXT_PUBLIC_JUPITER_ENV as "mainnet-beta" | "devnet"}
      walletConnectProjectId={process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID}
      metadata={{
        name: "Bonk Computer",
        description: "Solana-native Web3 development framework",
        url: process.env.NEXT_PUBLIC_APP_URL || "https://bonk.computer",
        iconUrls: ["https://bonk.computer/favicon.ico"],
      }}
    >
      {children}
    </JupiverseKitProvider>
  );
}

E2B Sandbox Configuration

Create packages/vm/config.ts:

import { Sandbox } from '@e2b/code-interpreter';

export const E2B_CONFIG = {
  apiKey: process.env.NEXT_PUBLIC_E2B_API_KEY!,
  timeout: 60000, // 60 seconds
  template: 'base', // or 'python', 'nodejs', etc.
};

export async function createSandbox() {
  return await Sandbox.create({
    apiKey: E2B_CONFIG.apiKey,
    timeout: E2B_CONFIG.timeout,
  });
}

AI Configuration

Create packages/ai/config.ts:

import { anthropic } from '@ai-sdk/anthropic';
import { openai } from '@ai-sdk/openai';

export const AI_CONFIG = {
  anthropic: anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY!,
  }),
  openai: openai({
    apiKey: process.env.OPENAI_API_KEY!,
  }),
  defaultModel: 'claude-3-5-sonnet-20241022',
};

Convex Real-time Backend Configuration

1. Initialize Convex

# Initialize Convex in your project
npx convex dev --once

# This creates the convex/ directory and convex.json

2. Convex Schema Definition

Create convex/schema.ts:

import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";

export default defineSchema({
  // Game state for multiplayer games
  games: defineTable({
    name: v.string(),
    players: v.array(v.string()),
    state: v.any(), // Game-specific state
    isActive: v.boolean(),
    createdAt: v.number(),
    updatedAt: v.number(),
  }).index("by_active", ["isActive"]),

  // Real-time collaboration sessions
  collaborationSessions: defineTable({
    name: v.string(),
    type: v.union(v.literal("code"), v.literal("whiteboard"), v.literal("document")),
    participants: v.array(v.string()),
    content: v.any(),
    isActive: v.boolean(),
    createdAt: v.number(),
    updatedAt: v.number(),
  }).index("by_type", ["type"]).index("by_active", ["isActive"]),

  // User presence for real-time features
  userPresence: defineTable({
    userId: v.string(),
    sessionId: v.string(),
    status: v.union(v.literal("online"), v.literal("away"), v.literal("offline")),
    lastSeen: v.number(),
    currentRoom: v.optional(v.string()),
  }).index("by_user", ["userId"]).index("by_session", ["sessionId"]),

  // Chat messages for collaborative features
  messages: defineTable({
    sessionId: v.string(),
    userId: v.string(),
    content: v.string(),
    type: v.union(v.literal("text"), v.literal("system"), v.literal("ai")),
    timestamp: v.number(),
  }).index("by_session", ["sessionId"]),

  // Solana transaction logs for real-time updates
  solanaTransactions: defineTable({
    signature: v.string(),
    userId: v.string(),
    type: v.string(),
    status: v.union(v.literal("pending"), v.literal("confirmed"), v.literal("failed")),
    data: v.any(),
    timestamp: v.number(),
  }).index("by_user", ["userId"]).index("by_status", ["status"]),
});

3. Authentication Configuration

Create convex/auth.config.ts:

export default {
  providers: [
    {
      domain: process.env.NEXT_PUBLIC_APP_URL!,
      applicationID: "bonk-computer",
    },
  ],
};

4. Convex Functions

Create convex/game.ts:

import { mutation, query } from "./_generated/server";
import { v } from "convex/values";

// Query to get active games
export const getActiveGames = query({
  args: {},
  handler: async (ctx) => {
    return await ctx.db
      .query("games")
      .withIndex("by_active", (q) => q.eq("isActive", true))
      .collect();
  },
});

// Mutation to create a new game
export const createGame = mutation({
  args: {
    name: v.string(),
    playerId: v.string(),
  },
  handler: async (ctx, args) => {
    const gameId = await ctx.db.insert("games", {
      name: args.name,
      players: [args.playerId],
      state: { phase: "waiting", scores: {} },
      isActive: true,
      createdAt: Date.now(),
      updatedAt: Date.now(),
    });
    return gameId;
  },
});

// Mutation to update game state
export const updateGameState = mutation({
  args: {
    gameId: v.id("games"),
    newState: v.any(),
    playerId: v.string(),
  },
  handler: async (ctx, args) => {
    const game = await ctx.db.get(args.gameId);
    if (!game || !game.players.includes(args.playerId)) {
      throw new Error("Unauthorized or game not found");
    }

    await ctx.db.patch(args.gameId, {
      state: args.newState,
      updatedAt: Date.now(),
    });
  },
});

// Mutation to join a game
export const joinGame = mutation({
  args: {
    gameId: v.id("games"),
    playerId: v.string(),
  },
  handler: async (ctx, args) => {
    const game = await ctx.db.get(args.gameId);
    if (!game) throw new Error("Game not found");

    if (!game.players.includes(args.playerId)) {
      await ctx.db.patch(args.gameId, {
        players: [...game.players, args.playerId],
        updatedAt: Date.now(),
      });
    }
  },
});

Create convex/collaboration.ts:

import { mutation, query } from "./_generated/server";
import { v } from "convex/values";

// Query to get collaboration session
export const getSession = query({
  args: { sessionId: v.id("collaborationSessions") },
  handler: async (ctx, args) => {
    return await ctx.db.get(args.sessionId);
  },
});

// Mutation to update collaboration content
export const updateContent = mutation({
  args: {
    sessionId: v.id("collaborationSessions"),
    content: v.any(),
    userId: v.string(),
  },
  handler: async (ctx, args) => {
    const session = await ctx.db.get(args.sessionId);
    if (!session || !session.participants.includes(args.userId)) {
      throw new Error("Unauthorized");
    }

    await ctx.db.patch(args.sessionId, {
      content: args.content,
      updatedAt: Date.now(),
    });
  },
});

// Mutation to update user presence
export const updatePresence = mutation({
  args: {
    userId: v.string(),
    sessionId: v.string(),
    status: v.union(v.literal("online"), v.literal("away"), v.literal("offline")),
    currentRoom: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const existing = await ctx.db
      .query("userPresence")
      .withIndex("by_user", (q) => q.eq("userId", args.userId))
      .first();

    if (existing) {
      await ctx.db.patch(existing._id, {
        sessionId: args.sessionId,
        status: args.status,
        lastSeen: Date.now(),
        currentRoom: args.currentRoom,
      });
    } else {
      await ctx.db.insert("userPresence", {
        userId: args.userId,
        sessionId: args.sessionId,
        status: args.status,
        lastSeen: Date.now(),
        currentRoom: args.currentRoom,
      });
    }
  },
});

Create convex/solana.ts:

import { action, mutation, query } from "./_generated/server";
import { v } from "convex/values";

// Action to process Solana transactions (can call external APIs)
export const processSolanaTransaction = action({
  args: {
    signature: v.string(),
    userId: v.string(),
    type: v.string(),
    data: v.any(),
  },
  handler: async (ctx, args) => {
    // This action can interact with external Solana APIs
    // and then update the Convex database
    
    // Log transaction as pending
    await ctx.runMutation("logTransaction", {
      signature: args.signature,
      userId: args.userId,
      type: args.type,
      status: "pending",
      data: args.data,
    });

    // Here you would integrate with Solana SDKs
    // For example, using the Solana Agent Kit or App Kit
    try {
      // Simulate transaction processing
      // In real implementation, this would call Solana APIs
      
      // Update transaction status to confirmed
      await ctx.runMutation("updateTransactionStatus", {
        signature: args.signature,
        status: "confirmed",
      });
      
      return { success: true, signature: args.signature };
    } catch (error) {
      // Update transaction status to failed
      await ctx.runMutation("updateTransactionStatus", {
        signature: args.signature,
        status: "failed",
      });
      
      throw error;
    }
  },
});

// Mutation to log transaction
export const logTransaction = mutation({
  args: {
    signature: v.string(),
    userId: v.string(),
    type: v.string(),
    status: v.union(v.literal("pending"), v.literal("confirmed"), v.literal("failed")),
    data: v.any(),
  },
  handler: async (ctx, args) => {
    await ctx.db.insert("solanaTransactions", {
      signature: args.signature,
      userId: args.userId,
      type: args.type,
      status: args.status,
      data: args.data,
      timestamp: Date.now(),
    });
  },
});

// Mutation to update transaction status
export const updateTransactionStatus = mutation({
  args: {
    signature: v.string(),
    status: v.union(v.literal("pending"), v.literal("confirmed"), v.literal("failed")),
  },
  handler: async (ctx, args) => {
    const transaction = await ctx.db
      .query("solanaTransactions")
      .filter((q) => q.eq(q.field("signature"), args.signature))
      .first();

    if (transaction) {
      await ctx.db.patch(transaction._id, {
        status: args.status,
        timestamp: Date.now(),
      });
    }
  },
});

// Query to get user transactions
export const getUserTransactions = query({
  args: { userId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("solanaTransactions")
      .withIndex("by_user", (q) => q.eq("userId", args.userId))
      .order("desc")
      .take(50);
  },
});

5. Frontend Integration

Create packages/convex/provider.tsx:

"use client";

import { ConvexProvider, ConvexReactClient } from "@convex-dev/react";
import { ReactNode } from "react";

const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!);

interface ConvexClientProviderProps {
  children: ReactNode;
}

export function ConvexClientProvider({ children }: ConvexClientProviderProps) {
  return <ConvexProvider client={convex}>{children}</ConvexProvider>;
}

6. Real-time Hooks

Create packages/convex/hooks.ts:

import { useQuery, useMutation, useAction } from "@convex-dev/react";
import { api } from "../../convex/_generated/api";

// Game hooks
export function useActiveGames() {
  return useQuery(api.game.getActiveGames);
}

export function useCreateGame() {
  return useMutation(api.game.createGame);
}

export function useUpdateGameState() {
  return useMutation(api.game.updateGameState);
}

export function useJoinGame() {
  return useMutation(api.game.joinGame);
}

// Collaboration hooks
export function useCollaborationSession(sessionId: string) {
  return useQuery(api.collaboration.getSession, { sessionId });
}

export function useUpdateContent() {
  return useMutation(api.collaboration.updateContent);
}

export function useUpdatePresence() {
  return useMutation(api.collaboration.updatePresence);
}

// Solana hooks
export function useUserTransactions(userId: string) {
  return useQuery(api.solana.getUserTransactions, { userId });
}

export function useProcessSolanaTransaction() {
  return useAction(api.solana.processSolanaTransaction);
}

💻 Development Examples

1. Real-time Multiplayer Solana Game with Convex

// apps/app/app/game/page.tsx
'use client';

import { useState, useEffect } from 'react';
import { useQuery, useMutation } from '@convex-dev/react';
import { api } from '../../../convex/_generated/api';
import { useWallet } from '@solana/wallet-adapter-react';
import { Button } from '@/packages/design-system';
import { createBonkAgent } from '@/packages/solana/agent';

interface GameState {
  phase: 'waiting' | 'playing' | 'finished';
  players: Record<string, { score: number; position: { x: number; y: number } }>;
  collectibles: Array<{ id: string; x: number; y: number; value: number }>;
}

export default function MultiplayerGamePage() {
  const { publicKey } = useWallet();
  const [selectedGameId, setSelectedGameId] = useState<string | null>(null);
  
  // Real-time queries - automatically update when data changes
  const activeGames = useQuery(api.game.getActiveGames);
  const currentGame = useQuery(
    api.game.getGame,
    selectedGameId ? { gameId: selectedGameId } : "skip"
  );
  
  // Mutations for real-time updates
  const createGame = useMutation(api.game.createGame);
  const joinGame = useMutation(api.game.joinGame);
  const updateGameState = useMutation(api.game.updateGameState);
  const processSolanaReward = useMutation(api.solana.processSolanaTransaction);
  
  const handleCreateGame = async () => {
    if (!publicKey) return;
    
    const gameId = await createGame({
      name: `${publicKey.toString().slice(0, 8)}'s Game`,
      playerId: publicKey.toString(),
    });
    
    setSelectedGameId(gameId);
  };
  
  const handlePlayerMove = async (newPosition: { x: number; y: number }) => {
    if (!currentGame || !publicKey || !selectedGameId) return;
    
    // Optimistic update - UI updates instantly
    const updatedState: GameState = {
      ...currentGame.state,
      players: {
        ...currentGame.state.players,
        [publicKey.toString()]: {
          ...currentGame.state.players[publicKey.toString()],
          position: newPosition,
        },
      },
    };
    
    // Real-time sync to all players
    await updateGameState({
      gameId: selectedGameId,
      newState: updatedState,
      playerId: publicKey.toString(),
    });
  };
  
  const handleCollectItem = async (collectibleId: string) => {
    if (!currentGame || !publicKey || !selectedGameId) return;
    
    const collectible = currentGame.state.collectibles.find(
      (c: any) => c.id === collectibleId
    );
    
    if (!collectible) return;
    
    // Update game state with real-time sync
    const updatedState: GameState = {
      ...currentGame.state,
      players: {
        ...currentGame.state.players,
        [publicKey.toString()]: {
          ...currentGame.state.players[publicKey.toString()],
          score: currentGame.state.players[publicKey.toString()].score + collectible.value,
        },
      },
      collectibles: currentGame.state.collectibles.filter(
        (c: any) => c.id !== collectibleId
      ),
    };
    
    await updateGameState({
      gameId: selectedGameId,
      newState: updatedState,
      playerId: publicKey.toString(),
    });
    
    // Process Solana reward when score threshold reached
    if (updatedState.players[publicKey.toString()].score >= 100) {
      try {
        const { agent } = await createBonkAgent();
        
        await processSolanaReward({
          signature: `reward_${Date.now()}`,
          userId: publicKey.toString(),
          type: 'game_reward',
          data: {
            gameId: selectedGameId,
            score: updatedState.players[publicKey.toString()].score,
            reward: 'BONK_TOKEN',
          },
        });
      } catch (error) {
        console.error('Failed to process Solana reward:', error);
      }
    }
  };
  
  if (!publicKey) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <p>Please connect your wallet to play</p>
      </div>
    );
  }
  
  return (
    <div className="container mx-auto p-8">
      <h1 className="text-3xl font-bold mb-8">🎮 Real-time Bonk Games</h1>
      
      {!selectedGameId ? (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          <div>
            <h2 className="text-xl font-semibold mb-4">Create New Game</h2>
            <Button onClick={handleCreateGame} className="w-full">
              🚀 Create Game
            </Button>
          </div>
          
          <div>
            <h2 className="text-xl font-semibold mb-4">Join Active Games</h2>
            <div className="space-y-2">
              {activeGames?.map((game) => (
                <div
                  key={game._id}
                  className="flex justify-between items-center p-3 border rounded"
                >
                  <div>
                    <p className="font-medium">{game.name}</p>
                    <p className="text-sm text-gray-600">
                      {game.players.length} players online
                    </p>
                  </div>
                  <Button
                    onClick={() => setSelectedGameId(game._id)}
                    variant="outline"
                    size="sm"
                  >
                    Join
                  </Button>
                </div>
              ))}
            </div>
          </div>
        </div>
      ) : (
        <GameInterface
          game={currentGame}
          onPlayerMove={handlePlayerMove}
          onCollectItem={handleCollectItem}
          onLeaveGame={() => setSelectedGameId(null)}
          currentPlayerId={publicKey.toString()}
        />
      )}
    </div>
  );
}

// Real-time Game Interface Component
function GameInterface({
  game,
  onPlayerMove,
  onCollectItem,
  onLeaveGame,
  currentPlayerId,
}: {
  game: any;
  onPlayerMove: (position: { x: number; y: number }) => void;
  onCollectItem: (collectibleId: string) => void;
  onLeaveGame: () => void;
  currentPlayerId: string;
}) {
  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
      {/* Real-time Game Canvas */}
      <div className="lg:col-span-2">
        <div className="bg-gray-100 p-4 rounded-lg">
          <h3 className="font-semibold mb-4">🎮 {game?.name}</h3>
          <GameCanvas
            gameState={game?.state}
            onPlayerMove={onPlayerMove}
            onCollectItem={onCollectItem}
            currentPlayerId={currentPlayerId}
          />
        </div>
      </div>
      
      {/* Real-time Game Info */}
      <div className="space-y-4">
        <div className="bg-gray-100 p-4 rounded">
          <h3 className="font-semibold mb-2">🏆 Live Leaderboard</h3>
          {Object.entries(game?.state?.players || {})
            .sort(([, a]: [string, any], [, b]: [string, any]) => b.score - a.score)
            .map(([playerId, player]: [string, any]) => (
              <div key={playerId} className="flex justify-between items-center py-1">
                <span className={`text-sm ${playerId === currentPlayerId ? 'font-bold text-blue-600' : ''}`}>
                  {playerId === currentPlayerId ? 'You' : `${playerId.slice(0, 8)}...`}
                </span>
                <span className="font-medium">{player.score} pts</span>
              </div>
            ))}
        </div>
        
        <div className="bg-blue-50 p-4 rounded">
          <h4 className="font-medium text-blue-800 mb-2">💰 Solana Rewards</h4>
          <p className="text-sm text-blue-600">
            Reach 100 points to earn BONK tokens!
          </p>
        </div>
        
        <Button onClick={onLeaveGame} variant="outline" className="w-full">
          Leave Game
        </Button>
      </div>
    </div>
  );
}

// Interactive Game Canvas with Real-time Updates
function GameCanvas({
  gameState,
  onPlayerMove,
  onCollectItem,
  currentPlayerId,
}: {
  gameState: any;
  onPlayerMove: (position: { x: number; y: number }) => void;
  onCollectItem: (collectibleId: string) => void;
  currentPlayerId: string;
}) {
  const handleCanvasClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
    const canvas = event.currentTarget;
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    
    onPlayerMove({ x, y });
    
    // Check for collectible collision
    gameState?.collectibles?.forEach((collectible: any) => {
      const distance = Math.sqrt(
        Math.pow(x - collectible.x, 2) + Math.pow(y - collectible.y, 2)
      );
      
      if (distance < 20) {
        onCollectItem(collectible.id);
      }
    });
  };
  
  // Real-time canvas updates
  useEffect(() => {
    const canvas = document.getElementById('gameCanvas') as HTMLCanvasElement;
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    
    // Clear and redraw on every state change
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // Draw all players in real-time
    Object.entries(gameState?.players || {}).forEach(([playerId, player]: [string, any]) => {
      ctx.fillStyle = playerId === currentPlayerId ? '#ff6b35' : '#676fff';
      ctx.beginPath();
      ctx.arc(player.position.x, player.position.y, 15, 0, 2 * Math.PI);
      ctx.fill();
      
      // Draw player score
      ctx.fillStyle = '#000';
      ctx.font = '12px Arial';
      ctx.fillText(
        player.score.toString(),
        player.position.x - 10,
        player.position.y - 20
      );
    });
    
    // Draw collectibles
    gameState?.collectibles?.forEach((collectible: any) => {
      ctx.fillStyle = '#ffd700';
      ctx.beginPath();
      ctx.arc(collectible.x, collectible.y, 10, 0, 2 * Math.PI);
      ctx.fill();
    });
  }, [gameState, currentPlayerId]);
  
  return (
    <canvas
      id="gameCanvas"
      width={600}
      height={400}
      className="border border-gray-300 cursor-pointer bg-white rounded"
      onClick={handleCanvasClick}
    />
  );
}

2. Comprehensive Solana Agent with All Kits

// packages/solana/agent.ts
import { Sandbox } from '@e2b/code-interpreter';
import { SolanaAgentKit, createVercelAITools } from 'solana-agent-kit';
import { KeypairWallet } from 'solana-agent-kit';
import { Keypair, Connection } from '@solana/web3.js';
import { SolanaAppKit } from 'solana-app-kit';
import bs58 from 'bs58';

export async function createBonkAgent() {
  // Initialize E2B Firecracker sandbox
  const sandbox = await Sandbox.create({
    apiKey: process.env.NEXT_PUBLIC_E2B_API_KEY!
  });
  
  // Setup Solana connection using official SDK
  const connection = new Connection(
    process.env.NEXT_PUBLIC_RPC_URL!,
    'confirmed'
  );
  
  // Setup Solana wallet from Solana-Starter-Kit foundation
  const keyPair = Keypair.fromSecretKey(
    bs58.decode(process.env.SOLANA_PRIVATE_KEY!)
  );
  const wallet = new KeypairWallet(keyPair);
  
  // Initialize Solana Agent Kit with enhanced capabilities
  const agent = new SolanaAgentKit(
    wallet,
    process.env.NEXT_PUBLIC_RPC_URL!,
    {
      OPENAI_API_KEY: process.env.OPENAI_API_KEY!,
      HELIUS_API_KEY: process.env.NEXT_PUBLIC_HELIUS_API_KEY!,
      JUPITER_API_KEY: process.env.NEXT_PUBLIC_JUPITER_API_KEY!,
    }
  );
  
  // Initialize Solana App Kit for additional utilities
  const appKit = new SolanaAppKit({
    connection,
    wallet: keyPair,
    network: process.env.NEXT_PUBLIC_SOLANA_NETWORK as 'mainnet-beta' | 'devnet',
  });
  
  // Test comprehensive sandbox execution
  const execution = await sandbox.runCode(`
    console.log("🐶 Bonk Computer Agent initialized!");
    console.log("✅ Solana-Starter-Kit: Foundation ready");
    console.log("✅ Solana-Agent-Kit: AI agent active");
    console.log("✅ Solana-App-Kit: App utilities loaded");
    console.log("✅ Official Solana SDK: Connection established");
    console.log("✅ JupiverseKit: Jupiter integration ready");
    console.log("Sandbox ready for advanced Solana development");
  `);
  
  console.log(execution.text);
  
  // Create enhanced Vercel AI tools with all capabilities
  const tools = createVercelAITools(agent, {
    ...agent.actions,
    // Add custom actions from App Kit
    getTokenBalance: appKit.getTokenBalance,
    createToken: appKit.createToken,
    swapTokens: appKit.swapTokens,
  });
  
  return {
    agent,
    appKit,
    sandbox,
    tools,
    connection,
    wallet: keyPair
  };
}

// Enhanced agent actions using all kits
export async function executeAgentAction(
  action: string,
  params: Record<string, any>
) {
  const { agent, appKit, sandbox } = await createBonkAgent();
  
  try {
    let result;
    
    switch (action) {
      case 'transfer':
        result = await agent.transfer(params.to, params.amount);
        break;
      case 'swap':
        result = await agent.trade(params.inputMint, params.outputMint, params.amount);
        break;
      case 'mintNFT':
        result = await agent.mintNFT(params);
        break;
      case 'createToken':
        result = await appKit.createToken(params);
        break;
      case 'getBalance':
        result = await appKit.getTokenBalance(params.mint);
        break;
      default:
        throw new Error(`Unknown action: ${action}`);
    }
    
    // Log execution in sandbox
    await sandbox.runCode(`
      console.log("Action executed:", "${action}");
      console.log("Result:", ${JSON.stringify(result)});
    `);
    
    return result;
  } finally {
    await sandbox.close();
  }
}

2. AI-Assisted NFT Minting with Full Stack Integration

// apps/app/app/actions/nft/mint.ts
'use server';

import { generateText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { Sandbox } from '@e2b/code-interpreter';
import { SolanaAgentKit } from 'solana-agent-kit';
import { SolanaAppKit } from 'solana-app-kit';
import { Connection, Keypair } from '@solana/web3.js';
import { Metaplex, keypairIdentity } from '@metaplex-foundation/js';
import bs58 from 'bs58';

export async function mintBonkNFT(prompt: string) {
  // Generate NFT metadata using AI
  const { text: metadata } = await generateText({
    model: anthropic('claude-3-5-sonnet-20241022'),
    prompt: `Generate comprehensive JSON metadata for a Bonk-themed NFT based on: ${prompt}. Include name, description, image, attributes, and properties.`,
  });
  
  // Create sandbox for secure execution
  const sandbox = await Sandbox.create({
    apiKey: process.env.NEXT_PUBLIC_E2B_API_KEY!
  });
  
  try {
    // Setup using Official Solana SDK
    const connection = new Connection(process.env.NEXT_PUBLIC_RPC_URL!, 'confirmed');
    const keyPair = Keypair.fromSecretKey(bs58.decode(process.env.SOLANA_PRIVATE_KEY!));
    
    // Initialize Solana Agent Kit for AI-powered operations
    const agent = new SolanaAgentKit(
      keyPair,
      process.env.NEXT_PUBLIC_RPC_URL!,
      {
        OPENAI_API_KEY: process.env.OPENAI_API_KEY!,
        HELIUS_API_KEY: process.env.NEXT_PUBLIC_HELIUS_API_KEY!,
      }
    );
    
    // Initialize Solana App Kit for enhanced utilities
    const appKit = new SolanaAppKit({
      connection,
      wallet: keyPair,
      network: process.env.NEXT_PUBLIC_SOLANA_NETWORK as 'mainnet-beta' | 'devnet',
    });
    
    // Execute comprehensive NFT minting in sandbox
    const execution = await sandbox.runCode(`
      console.log("🚀 Starting comprehensive NFT minting process...");
      console.log("📝 AI-generated metadata:", ${JSON.stringify(metadata)});
      console.log("🔗 Using Official Solana SDK connection");
      console.log("🤖 Solana-Agent-Kit: AI-powered minting");
      console.log("🛠️ Solana-App-Kit: Enhanced utilities");
      console.log("🎨 Metaplex: NFT standard compliance");
    `);
    
    // Parse AI-generated metadata
    const nftMetadata = JSON.parse(metadata);
    
    // Mint NFT using Agent Kit's AI capabilities
    const nft = await agent.mintNFT({
      collection: 'BonkComputer',
      symbol: 'BONK',
      uri: `https://arweave.net/${Buffer.from(metadata).toString('base64')}`,
      name: nftMetadata.name || `Bonk Computer #${Date.now()}`,
      description: nftMetadata.description || 'AI-generated Bonk Computer NFT',
      attributes: nftMetadata.attributes || [],
    });
    
    // Verify minting with App Kit utilities
    const tokenBalance = await appKit.getTokenBalance(nft.mint);
    
    // Log comprehensive success in sandbox
    await sandbox.runCode(`
      console.log("🎉 NFT minted successfully with full stack integration!");
      console.log("📍 Transaction Signature:", "${nft.signature}");
      console.log("🏷️ NFT Mint Address:", "${nft.mint}");
      console.log("💰 Token Balance:", "${tokenBalance}");
      console.log("✅ All Solana packages working in harmony");
    `);
    
    return {
      success: true,
      nft: {
        signature: nft.signature,
        mint: nft.mint,
        metadata: nftMetadata,
        balance: tokenBalance,
      },
      integrations: {
        solanaSDK: '✅ Official Solana SDK',
        agentKit: '✅ Solana-Agent-Kit',
        appKit: '✅ Solana-App-Kit',
        starterKit: '✅ Solana-Starter-Kit foundation',
        metaplex: '✅ Metaplex NFT standards',
      }
    };
  } finally {
    await sandbox.close();
  }
}

// Enhanced NFT operations using all packages
export async function getNFTDetails(mintAddress: string) {
  const { appKit, sandbox } = await createBonkAgent();
  
  try {
    // Use App Kit for detailed NFT information
    const nftDetails = await appKit.getNFTMetadata(mintAddress);
    
    // Log in sandbox
    await sandbox.runCode(`
      console.log("🔍 NFT Details Retrieved:");
      console.log("Mint:", "${mintAddress}");
      console.log("Details:", ${JSON.stringify(nftDetails)});
    `);
    
    return nftDetails;
  } finally {
    await sandbox.close();
  }
}

3. Comprehensive Web3 Authentication with JupiverseKit

// packages/auth/components/wallet-connect.tsx
'use client';

import { usePrivy } from '@privy-io/react-auth';
import { useWallet } from '@solana/wallet-adapter-react';
import { useWalletModal } from '@solana/wallet-adapter-react-ui';
import { Button } from '@/packages/design-system';
import { Wallet, LogOut, Zap, ArrowUpDown } from 'lucide-react';
import { JupiterProvider } from '@/packages/solana/jupiter-provider';
import { useState } from 'react';

export function WalletConnect() {
  const { ready, authenticated, user, login, logout } = usePrivy();
  const { connected, publicKey, disconnect } = useWallet();
  const { setVisible } = useWalletModal();
  const [showJupiter, setShowJupiter] = useState(false);
  
  if (!ready) {
    return <Button disabled>Loading...</Button>;
  }
  
  if (authenticated && connected) {
    return (
      <div className="flex items-center gap-2">
        <div className="flex flex-col text-sm">
          <span className="font-medium">
            {user?.wallet?.address?.slice(0, 6)}...
            {user?.wallet?.address?.slice(-4)}
          </span>
          <span className="text-xs text-muted-foreground">
            Solana: {publicKey?.toString().slice(0, 4)}...{publicKey?.toString().slice(-4)}
          </span>
        </div>
        
        <Button
          variant="outline"
          size="sm"
          onClick={() => setShowJupiter(!showJupiter)}
          className="flex items-center gap-1"
        >
          <ArrowUpDown className="h-3 w-3" />
          <span className="text-xs">Swap</span>
        </Button>
        
        <Button variant="outline" size="sm" onClick={() => {
          logout();
          disconnect();
        }}>
          <LogOut className="h-4 w-4" />
        </Button>
        
        {showJupiter && (
          <JupiterSwapModal
            isOpen={showJupiter}
            onClose={() => setShowJupiter(false)}
          />
        )}
      </div>
    );
  }
  
  return (
    <div className="flex items-center gap-2">
      <Button onClick={login}>
        <Wallet className="h-4 w-4 mr-2" />
        Connect Web3
      </Button>
      <Button variant="outline" onClick={() => setVisible(true)}>
        <Zap className="h-4 w-4 mr-2" />
        Solana Wallet
      </Button>
    </div>
  );
}

// Jupiter Swap Modal Component
function JupiterSwapModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
  if (!isOpen) return null;
  
  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg p-6 max-w-md w-full mx-4">
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-lg font-semibold">Jupiter Swap</h3>
          <Button variant="ghost" size="sm" onClick={onClose}>
            ×
          </Button>
        </div>
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Powered by JupiverseKit - Best-in-class Solana token swapping
          </p>
          {/* Jupiter swap interface would be integrated here */}
          <div className="bg-gray-100 p-4 rounded-lg text-center">
            <p className="text-sm">Jupiter Swap Interface</p>
            <p className="text-xs text-muted-foreground mt-1">
              Integrated via JupiverseKit components
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

4. Complete App Layout with All Integrations Including Convex

// apps/app/app/layout.tsx
'use client';

import { PrivyProvider } from '@privy-io/react-auth';
import { WalletAdapterNetwork } from '@solana/wallet-adapter-base';
import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';
import { WalletModalProvider } from '@solana/wallet-adapter-react-ui';
import { PhantomWalletAdapter, SolflareWalletAdapter } from '@solana/wallet-adapter-wallets';
import { JupiterProvider } from '@/packages/solana/jupiter-provider';
import { ConvexClientProvider } from '@/packages/convex/provider';
import { clusterApiUrl } from '@solana/web3.js';
import { useMemo, useState } from 'react';

// Import wallet adapter CSS
require('@solana/wallet-adapter-react-ui/styles.css');

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  // Configure Solana network
  const network = WalletAdapterNetwork.Mainnet;
  const endpoint = useMemo(() =>
    process.env.NEXT_PUBLIC_RPC_URL || clusterApiUrl(network),
    [network]
  );
  
  // Configure wallet adapters
  const wallets = useMemo(
    () => [
      new PhantomWalletAdapter(),
      new SolflareWalletAdapter(),
    ],
    []
  );

  return (
    <html lang="en">
      <body>
        {/* Convex Provider - Real-time backend foundation */}
        <ConvexClientProvider>
          <PrivyProvider
            appId={process.env.NEXT_PUBLIC_PRIVY_APP_ID!}
            config={{
              appearance: {
                theme: 'light',
                accentColor: '#676FFF',
              },
              embeddedWallets: {
                createOnLogin: 'users-without-wallets',
              },
            }}
          >
            <ConnectionProvider endpoint={endpoint}>
              <WalletProvider wallets={wallets} autoConnect>
                <WalletModalProvider>
                  <JupiterProvider>
                    <div className="min-h-screen bg-background">
                      <header className="border-b">
                        <div className="container mx-auto px-4 py-4 flex justify-between items-center">
                          <h1 className="text-2xl font-bold">🐶💻 Bonk Computer</h1>
                          <div className="flex items-center gap-4">
                            <RealtimeStatus />
                            <WalletConnect />
                          </div>
                        </div>
                      </header>
                      <main className="container mx-auto px-4 py-8">
                        {children}
                      </main>
                    </div>
                  </JupiterProvider>
                </WalletModalProvider>
              </WalletProvider>
            </ConnectionProvider>
          </PrivyProvider>
        </ConvexClientProvider>
      </body>
    </html>
  );
}

// Real-time Status Indicator Component
function RealtimeStatus() {
  const [isConnected, setIsConnected] = useState(true);
  
  return (
    <div className="flex items-center gap-2 text-sm">
      <div className={`w-2 h-2 rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'}`} />
      <span className="text-gray-600">
        {isConnected ? 'Real-time Connected' : 'Connecting...'}
      </span>
    </div>
  );
}

📦 Comprehensive Solana Package Integration

Official Solana SDK (@solana/web3.js)

The foundation of all Solana interactions, providing core blockchain functionality:

// packages/solana/core.ts
import {
  Connection,
  PublicKey,
  Transaction,
  SystemProgram,
  LAMPORTS_PER_SOL
} from '@solana/web3.js';

export class SolanaCore {
  private connection: Connection;
  
  constructor(rpcUrl: string) {
    this.connection = new Connection(rpcUrl, 'confirmed');
  }
  
  async getBalance(publicKey: PublicKey): Promise<number> {
    return await this.connection.getBalance(publicKey);
  }
  
  async transferSOL(from: Keypair, to: PublicKey, amount: number) {
    const transaction = new Transaction().add(
      SystemProgram.transfer({
        fromPubkey: from.publicKey,
        toPubkey: to,
        lamports: amount * LAMPORTS_PER_SOL,
      })
    );
    
    return await this.connection.sendTransaction(transaction, [from]);
  }
}

Solana-Starter-Kit Integration

Built on the robust foundation from Primitives-xyz:

// packages/solana/starter-kit.ts
import { Connection, Keypair } from '@solana/web3.js';
import bs58 from 'bs58';

export class BonkStarterKit {
  private connection: Connection;
  private network: string;
  
  constructor() {
    this.network = process.env.NEXT_PUBLIC_SOLANA_NETWORK!;
    this.connection = new Connection(process.env.NEXT_PUBLIC_RPC_URL!, 'confirmed');
  }
  
  // Enhanced wallet management from starter kit foundation
  async setupWallet(privateKey?: string) {
    if (privateKey) {
      return Keypair.fromSecretKey(bs58.decode(privateKey));
    }
    return Keypair.generate();
  }
  
  // NFT utilities built on starter kit patterns
  async mintNFTCollection(params: {
    name: string;
    symbol: string;
    description: string;
    image: string;
    attributes: Array<{ trait_type: string; value: string }>;
  }) {
    // Implementation using Solana-Starter-Kit patterns
    return {
      collection: params.name,
      mint: 'generated_mint_address',
      metadata: params,
    };
  }
}

Solana-Agent-Kit Integration

AI-powered autonomous Solana operations from sendaifun:

// packages/solana/agent-kit.ts
import { SolanaAgentKit, createVercelAITools } from 'solana-agent-kit';
import { KeypairWallet } from 'solana-agent-kit';
import { Keypair } from '@solana/web3.js';

export class BonkAgentKit {
  private agent: SolanaAgentKit;
  
  constructor(wallet: Keypair, rpcUrl: string, apiKeys: {
    OPENAI_API_KEY: string;
    HELIUS_API_KEY: string;
  }) {
    const keypairWallet = new KeypairWallet(wallet);
    
    this.agent = new SolanaAgentKit(
      keypairWallet,
      rpcUrl,
      apiKeys
    );
  }
  
  // AI-powered token operations
  async autonomousSwap(instruction: string) {
    return await this.agent.trade(instruction);
  }
  
  // AI-powered NFT creation
  async createAINFT(prompt: string) {
    return await this.agent.mintNFT({
      name: `AI Generated: ${prompt}`,
      symbol: 'BONKAI',
      description: `Created by AI from prompt: ${prompt}`,
      image: await this.generateAIImage(prompt),
    });
  }
  
  // Get Vercel AI tools for chat interfaces
  getAITools() {
    return createVercelAITools(this.agent, this.agent.actions);
  }
  
  private async generateAIImage(prompt: string): Promise<string> {
    // Integration with AI image generation
    return `https://ai-generated-image.com/${encodeURIComponent(prompt)}`;
  }
}

Solana-App-Kit Integration

Comprehensive application utilities from sendaifun:

// packages/solana/app-kit.ts
import { SolanaAppKit } from 'solana-app-kit';
import { Connection, Keypair, PublicKey } from '@solana/web3.js';

export class BonkAppKit extends SolanaAppKit {
  constructor(config: {
    connection: Connection;
    wallet: Keypair;
    network: 'mainnet-beta' | 'devnet';
  }) {
    super(config);
  }
  
  // Enhanced token operations
  async createBonkToken(params: {
    name: string;
    symbol: string;
    decimals: number;
    supply: number;
  }) {
    return await this.createToken({
      ...params,
      metadata: {
        name: params.name,
        symbol: params.symbol,
        description: `${params.name} - Powered by Bonk Computer`,
        image: 'https://bonk.computer/token-logo.png',
      }
    });
  }
  
  // Advanced DeFi operations
  async stakingOperations(action: 'stake' | 'unstake', amount: number) {
    switch (action) {
      case 'stake':
        return await this.stakeTokens(amount);
      case 'unstake':
        return await this.unstakeTokens(amount);
    }
  }
  
  // Portfolio management
  async getPortfolioValue(walletAddress: PublicKey) {
    const tokens = await this.getTokenAccounts(walletAddress);
    let totalValue = 0;
    
    for (const token of tokens) {
      const price = await this.getTokenPrice(token.mint);
      totalValue += token.amount * price;
    }
    
    return totalValue;
  }
}

JupiverseKit Integration

Ultimate React components for Jupiter-powered applications from jupiversekit.xyz:

// packages/solana/jupiter-integration.ts
import { JupiverseKitProvider, useJupiter } from 'jupiverse-kit';

// Enhanced Jupiter Provider with Bonk Computer theming
export function BonkJupiterProvider({ children }: { children: React.ReactNode }) {
  return (
    <JupiverseKitProvider
      endpoint={process.env.NEXT_PUBLIC_RPC_URL!}
      theme="jupiter"
      autoConnect={true}
      lang="en"
      env={process.env.NEXT_PUBLIC_JUPITER_ENV as "mainnet-beta" | "devnet"}
      walletConnectProjectId={process.env.NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID}
      metadata={{
        name: "Bonk Computer",
        description: "Solana-native Web3 development framework with Jupiter integration",
        url: process.env.NEXT_PUBLIC_APP_URL || "https://bonk.computer",
        iconUrls: ["https://bonk.computer/favicon.ico"],
      }}
    >
      {children}
    </JupiverseKitProvider>
  );
}

// Custom Jupiter swap hook
export function useBonkSwap() {
  const jupiter = useJupiter();
  
  const swapWithBonk = async (params: {
    inputMint: string;
    outputMint: string;
    amount: number;
    slippage?: number;
  }) => {
    try {
      const route = await jupiter.getRoutes({
        inputMint: params.inputMint,
        outputMint: params.outputMint,
        amount: params.amount,
        slippageBps: (params.slippage || 1) * 100,
      });
      
      if (route && route.length > 0) {
        return await jupiter.exchange({
          route: route[0],
        });
      }
      
      throw new Error('No routes found');
    } catch (error) {
      console.error('Bonk swap error:', error);
      throw error;
    }
  };
  
  return { swapWithBonk, ...jupiter };
}

Unified Integration Example

Bringing all packages together in a single, powerful interface:

// packages/solana/unified-integration.ts
import { BonkStarterKit } from './starter-kit';
import { BonkAgentKit } from './agent-kit';
import { BonkAppKit } from './app-kit';
import { SolanaCore } from './core';
import { Sandbox } from '@e2b/code-interpreter';
import { Connection, Keypair } from '@solana/web3.js';
import bs58 from 'bs58';

export class UnifiedBonkSolana {
  private core: SolanaCore;
  private starterKit: BonkStarterKit;
  private agentKit: BonkAgentKit;
  private appKit: BonkAppKit;
  private sandbox: Sandbox;
  
  constructor(config: {
    rpcUrl: string;
    privateKey: string;
    apiKeys: {
      OPENAI_API_KEY: string;
      HELIUS_API_KEY: string;
      E2B_API_KEY: string;
    };
  }) {
    // Initialize all components
    this.core = new SolanaCore(config.rpcUrl);
    this.starterKit = new BonkStarterKit();
    
    const wallet = Keypair.fromSecretKey(bs58.decode(config.privateKey));
    this.agentKit = new BonkAgentKit(wallet, config.rpcUrl, config.apiKeys);
    this.appKit = new BonkAppKit({
      connection: new Connection(config.rpcUrl),
      wallet,
      network: 'mainnet-beta',
    });
  }
  
  async initializeSandbox() {
    this.sandbox = await Sandbox.create({
      apiKey: process.env.NEXT_PUBLIC_E2B_API_KEY!
    });
  }
  
  // Unified operations combining all packages
  async executeUnifiedOperation(operation: string, params: any) {
    await this.sandbox.runCode(`
      console.log("🚀 Executing unified Solana operation: ${operation}");
      console.log("📦 Using all integrated packages:");
      console.log("✅ Official Solana SDK");
      console.log("✅ Solana-Starter-Kit");
      console.log("✅ Solana-Agent-Kit");
      console.log("✅ Solana-App-Kit");
      console.log("✅ JupiverseKit");
    `);
    
    switch (operation) {
      case 'ai-powered-defi':
        return await this.aiPoweredDeFi(params);
      case 'nft-marketplace':
        return await this.createNFTMarketplace(params);
      case 'token-launch':
        return await this.launchToken(params);
      default:
        throw new Error(`Unknown operation: ${operation}`);
    }
  }
  
  private async aiPoweredDeFi(params: any) {
    // Combine Agent Kit AI with App Kit DeFi utilities
    const aiAnalysis = await this.agentKit.autonomousSwap(params.strategy);
    const portfolioValue = await this.appKit.getPortfolioValue(params.wallet);
    
    return {
      aiRecommendation: aiAnalysis,
      currentValue: portfolioValue,
      action: 'executed',
    };
  }
  
  private async createNFTMarketplace(params: any) {
    // Use Starter Kit foundation with Agent Kit AI
    const collection = await this.starterKit.mintNFTCollection(params.collection);
    const aiNFT = await this.agentKit.createAINFT(params.aiPrompt);
    
    return {
      collection,
      aiGeneratedNFT: aiNFT,
      marketplace: 'created',
    };
  }
  
  private async launchToken(params: any) {
    // Combine App Kit token creation with Jupiter liquidity
    const token = await this.appKit.createBonkToken(params.tokenConfig);
    
    return {
      token,
      liquidityPool: 'created via Jupiter',
      status: 'launched',
    };
  }
  
  async cleanup() {
    if (this.sandbox) {
      await this.sandbox.close();
    }
  }
}

🧪 Testing

Unit Tests

# Run all tests
pnpm run test

# Run tests in watch mode
pnpm run test:watch

# Run tests with coverage
pnpm run test:coverage

E2E Tests

# Run Playwright tests
pnpm run test:e2e

# Run tests in UI mode
pnpm run test:e2e:ui

Example Test

// apps/app/__tests__/solana-integration.test.ts
import { describe, it, expect } from 'vitest';
import { createBonkAgent } from '@/packages/solana/agent';

describe('Solana Integration', () => {
  it('should create Bonk agent successfully', async () => {
    const { agent, sandbox, tools } = await createBonkAgent();
    
    expect(agent).toBeDefined();
    expect(sandbox).toBeDefined();
    expect(tools).toBeDefined();
    
    await sandbox.close();
  });
});

🚀 Deployment

Vercel Deployment

# Install Vercel CLI
npm i -g vercel

# Deploy to production
vercel --prod

# Set environment variables
vercel env add NEXT_PUBLIC_E2B_API_KEY
vercel env add NEXT_PUBLIC_HELIUS_API_KEY
# ... add all other environment variables

Environment Variables Setup

In your Vercel dashboard, add all environment variables from your .env.local file:

  1. Go to your project settings
  2. Navigate to "Environment Variables"
  3. Add each variable with appropriate scope (Production, Preview, Development)

Custom Deployment Script

# scripts/deploy.sh
#!/bin/bash

echo "🚀 Deploying Bonk Computer Framework..."

# Build all packages
pnpm run build

# Run tests
pnpm run test

# Deploy to Vercel
vercel --prod

echo "✅ Deployment complete!"

📚 Documentation

API Documentation

External Resources

🤝 Contributing

We welcome contributions from the community! Here's how to get started:

Development Setup

# Fork the repository
git clone https://github.com/rxdha1/bonk-computer-framework
cd bonk-computer-framework

# Install dependencies
pnpm install

# Create a new branch
git checkout -b feature/your-feature-name

# Make your changes and commit
git commit -m "feat: add your feature"

# Push and create a pull request
git push origin feature/your-feature-name

Contribution Guidelines

  1. Code Style: Follow the existing code style and use Biome for linting
  2. Testing: Add tests for new features and ensure all tests pass
  3. Documentation: Update documentation for any new features
  4. Commit Messages: Use conventional commit format

Community

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgements

  • Next-Forge for the production-grade Next.js foundation
  • E2B and Firecracker for secure microVM sandboxes
  • Solana ecosystem: Helius, Jupiter, Tapestry, Privy.io
  • Vercel for AI SDK and deployment infrastructure
  • AI Partners: Anthropic, OpenAI, Alibaba Qwen
  • $BONK Community for the vibes, with 400K+ Bonkbot users
  • **Convex

🗺️ Framework Developement Roadmap

  • Q3 2025: Enhanced AI code and multimedia generation with multi-model support
  • Q3 2025: Add $BONK to staking model as well as the $BCT for VM resource boosts
  • Q3 2025: Solana Pay integration for in-VM transactions
  • Q4 2025: Solana Mobile Stack (SMS) support for native dApp deployment
  • Ongoing: Community-driven modules for DAOs, gaming, and social platforms

SYSTEM STATUS: Bonk Computer Framework = Production-ready Solana Web3 development. Modular, AI-powered, $BCT-fueled. Fork the repo, join the pack, build the decentralized future!

BZZT #LetsBONK 🐶💻⚡


🆘 Support

Need help? Here are your options:

  1. Documentation: Check our comprehensive docs
  2. GitHub Issues: Report bugs or request features
  3. Telegram Community: Get help from other developers
  4. X/Twitter Community: Follow @BonkComputer for updates

Happy Building! 🚀

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published