import React, { useState, useEffect } from 'react'; import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from './ui/card'; import { Button } from './ui/button'; import { Badge } from './ui/badge'; import { Input } from './ui/input'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select'; import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs'; import { Alert, AlertDescription, AlertTitle } from './ui/alert'; import { Search, Filter, ShoppingCart, Star, TrendingUp, Clock, CheckCircle, XCircle } from 'lucide-react'; import { useToast } from '@/hooks/use-toast'; import { useWallet } from '@/hooks/use-wallet'; interface KnowledgeGraph { graphId: string; cid: string; creator: string; price: number; tags: string[]; qualityScore: number; accessCount: number; totalRevenue: number; royaltyRate: number; isActive: boolean; createdAt: string; description: string; metadata: string; } interface PurchaseRecord { graphId: string; buyer: string; purchasedAt: string; expiresAt: string; decryptionKey: string; isActive: boolean; } const KnowledgeMarketplace: React.FC = () => { const { toast } = useToast(); const { isConnected, address } = useWallet(); const [graphs, setGraphs] = useState([]); const [filteredGraphs, setFilteredGraphs] = useState([]); const [searchQuery, setSearchQuery] = useState(''); const [selectedTags, setSelectedTags] = useState([]); const [priceRange, setPriceRange] = useState({ min: 0, max: 1000 }); const [sortBy, setSortBy] = useState('quality'); const [loading, setLoading] = useState(true); const [purchasedGraphs, setPurchasedGraphs] = useState([]); const [activeTab, setActiveTab] = useState('browse'); // Mock data for demonstration const mockGraphs: KnowledgeGraph[] = [ { graphId: 'graph_001', cid: 'QmXxx...123', creator: '0x1234...5678', price: 100, tags: ['nlp', 'transformer', 'language'], qualityScore: 950, accessCount: 156, totalRevenue: 15600, royaltyRate: 500, isActive: true, createdAt: '2024-01-15T10:30:00Z', description: 'Advanced NLP knowledge graph with transformer architectures', metadata: '{"nodes": 1250, "edges": 3400, "domains": ["nlp", "ai"]}' }, { graphId: 'graph_002', cid: 'QmYyy...456', creator: '0xabcd...efgh', price: 250, tags: ['computer-vision', 'cnn', 'image'], qualityScore: 890, accessCount: 89, totalRevenue: 22250, royaltyRate: 300, isActive: true, createdAt: '2024-01-20T14:15:00Z', description: 'Computer vision knowledge graph with CNN architectures', metadata: '{"nodes": 890, "edges": 2100, "domains": ["vision", "ml"]}' }, { graphId: 'graph_003', cid: 'QmZzz...789', creator: '0x5678...9abc', price: 75, tags: ['reinforcement-learning', 'rl', 'gaming'], qualityScore: 920, accessCount: 234, totalRevenue: 17550, royaltyRate: 400, isActive: true, createdAt: '2024-01-25T09:45:00Z', description: 'Reinforcement learning knowledge graph for gaming AI', metadata: '{"nodes": 670, "edges": 1890, "domains": ["rl", "gaming"]}' } ]; useEffect(() => { // Load mock data setTimeout(() => { setGraphs(mockGraphs); setFilteredGraphs(mockGraphs); setLoading(false); }, 1000); }, []); useEffect(() => { filterAndSortGraphs(); }, [searchQuery, selectedTags, priceRange, sortBy, graphs]); const filterAndSortGraphs = () => { let filtered = graphs.filter(graph => { // Search query filter if (searchQuery) { const query = searchQuery.toLowerCase(); const matchesSearch = graph.description.toLowerCase().includes(query) || graph.tags.some(tag => tag.toLowerCase().includes(query)) || graph.creator.toLowerCase().includes(query); if (!matchesSearch) return false; } // Tags filter if (selectedTags.length > 0) { const hasSelectedTag = selectedTags.some(tag => graph.tags.includes(tag)); if (!hasSelectedTag) return false; } // Price range filter if (graph.price < priceRange.min || graph.price > priceRange.max) { return false; } return true; }); // Sort filtered.sort((a, b) => { switch (sortBy) { case 'quality': return b.qualityScore - a.qualityScore; case 'price_low': return a.price - b.price; case 'price_high': return b.price - a.price; case 'popularity': return b.accessCount - a.accessCount; case 'newest': return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(); default: return 0; } }); setFilteredGraphs(filtered); }; const handlePurchase = async (graph: KnowledgeGraph) => { if (!isConnected) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet to purchase knowledge graphs", variant: "destructive" }); return; } try { // Simulate purchase process const purchaseRecord: PurchaseRecord = { graphId: graph.graphId, buyer: address || '', purchasedAt: new Date().toISOString(), expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(), // 30 days decryptionKey: `key_${Math.random().toString(36).substr(2, 9)}`, isActive: true }; setPurchasedGraphs([...purchasedGraphs, purchaseRecord]); toast({ title: "Purchase Successful!", description: `You now have access to "${graph.description}"`, variant: "default" }); } catch (error) { toast({ title: "Purchase Failed", description: "There was an error processing your purchase", variant: "destructive" }); } }; const hasPurchased = (graphId: string) => { return purchasedGraphs.some(record => record.graphId === graphId && record.isActive && new Date(record.expiresAt) > new Date() ); }; const getQualityColor = (score: number) => { if (score >= 900) return 'bg-green-500'; if (score >= 700) return 'bg-yellow-500'; return 'bg-red-500'; }; const allTags = Array.from(new Set(graphs.flatMap(g => g.tags))); return (

Knowledge Graph Marketplace

Discover and purchase high-quality knowledge graphs to enhance your AI agents

{graphs.length} Graphs Available {graphs.reduce((sum, g) => sum + g.accessCount, 0)} Total Accesses
Browse Graphs My Purchases Create Graph {/* Search and Filters */} Search & Filter
setSearchQuery(e.target.value)} className="w-full" />
setPriceRange(prev => ({ ...prev, min: Number(e.target.value) }))} className="w-24" /> setPriceRange(prev => ({ ...prev, max: Number(e.target.value) }))} className="w-24" />
{allTags.map(tag => ( { setSelectedTags(prev => prev.includes(tag) ? prev.filter(t => t !== tag) : [...prev, tag] ); }} > {tag} ))}
{/* Graph Listings */} {loading ? (

Loading knowledge graphs...

) : filteredGraphs.length === 0 ? ( No graphs found Try adjusting your search criteria or filters to find knowledge graphs. ) : (
{filteredGraphs.map((graph) => { const isPurchased = hasPurchased(graph.graphId); return (
{graph.description} by {graph.creator.slice(0, 6)}...{graph.creator.slice(-4)}
{graph.qualityScore}
{graph.tags.map(tag => ( {tag} ))}
{graph.accessCount} accesses
{graph.totalRevenue} AITBC
Created {new Date(graph.createdAt).toLocaleDateString()}
{graph.price} AITBC
{isPurchased ? ( ) : ( )}
); })}
)}
My Purchased Knowledge Graphs Knowledge graphs you have purchased and can access {purchasedGraphs.length === 0 ? (

No purchased knowledge graphs yet

) : (
{purchasedGraphs.map((record) => { const graph = graphs.find(g => g.graphId === record.graphId); if (!graph) return null; return (

{graph.description}

Purchased on {new Date(record.purchasedAt).toLocaleDateString()}

Expires on {new Date(record.expiresAt).toLocaleDateString()}

{record.graphId}
); })}
)}
Create Knowledge Graph Upload and monetize your knowledge graphs on the marketplace Coming Soon Knowledge graph creation tools will be available in the next update.
); }; export default KnowledgeMarketplace;