instruction
stringlengths
25
121
input
stringclasses
1 value
output
stringlengths
0
296k
Describe the contents of the file app/layout.tsx.
import './globals.css' import NextTopLoader from 'nextjs-toploader'; import { Providers } from './Providers'; export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body> <NextTopLoader/> <Providers> {children} </Providers> </body> </html> ) }
Describe the contents of the file app/page.tsx.
"use client"; import { Button } from "@/components/ui/button"; import { ArrowRight, Bitcoin, Wallet, BarChart2, Lock, Zap, Globe, Menu, X, ChevronRight, } from "lucide-react"; import Link from "next/link"; import Image from "next/image"; import { useRouter } from "next/navigation"; import { motion, AnimatePresence } from "framer-motion"; import { useState, useEffect } from "react"; import { useSession } from "next-auth/react"; import Footer from "@/components/core/Footer"; export default function Component() { const router = useRouter(); const session = useSession(); const [isMenuOpen, setIsMenuOpen] = useState(false); const [cryptoPrices, setCryptoPrices] = useState({ BTC: 65000, ETH: 12000, }); const navItems = [ { name: "Markets", href: "/markets" }, { name: "Trade", href: "/trade/btcusdt" }, { name: "Wallet", href: "/wallet" }, { name: "Learn", href: "/learn" }, ]; useEffect(() => { const interval = setInterval(() => { setCryptoPrices({ BTC: Math.random() * 10000 + 30000, ETH: Math.random() * 1000 + 2000, }); }, 3000); return () => clearInterval(interval); }, []); if (session.data?.user) { router.push("/"); } const containerVariants = { hidden: { opacity: 0 }, visible: { opacity: 1, transition: { staggerChildren: 0.1, delayChildren: 0.3, }, }, }; const itemVariants = { hidden: { y: 20, opacity: 0 }, visible: { y: 0, opacity: 1, transition: { type: "spring", stiffness: 100, }, }, }; return ( <div className="flex flex-col min-h-screen bg-gray-900 text-white"> <header className="bg-gray-800 py-4 px-6 sm:px-10 fixed w-full z-50"> <div className="container mx-auto flex justify-between items-center"> <Link href="/" className="flex items-center space-x-2"> <Bitcoin className="h-8 w-8 text-yellow-500" /> <span className="text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-yellow-400 to-yellow-600"> Web3Crypto.ai </span> </Link> <nav className="hidden md:flex space-x-8"> {navItems.map((item) => ( <Link key={item.href} href={item.href} className="text-gray-300 hover:text-yellow-500 transition-colors" > {item.name} </Link> ))} </nav> <div className="hidden md:block"> <Button onClick={() => router.push("/auth/signin")} className="bg-yellow-500 text-gray-900 hover:bg-yellow-600" > Get Started </Button> </div> <Button variant="ghost" size="icon" className="md:hidden text-gray-300" onClick={() => setIsMenuOpen(!isMenuOpen)} > {isMenuOpen ? ( <X className="h-6 w-6" /> ) : ( <Menu className="h-6 w-6" /> )} </Button> </div> </header> <AnimatePresence> {isMenuOpen && ( <motion.nav initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -20 }} className="md:hidden bg-gray-800 py-4 px-6 mt-16 fixed w-full z-40" > {["Markets", "Trade", "Wallet", "Learn"].map((item) => ( <Link key={item} href="#" className="block py-2 text-gray-300 hover:text-yellow-500 transition-colors" > {item} </Link> ))} <Button onClick={() => router.push("/auth/signin")} className="w-full mt-4 bg-yellow-500 text-gray-900 hover:bg-yellow-600" > Get Started </Button> </motion.nav> )} </AnimatePresence> <main className="flex-grow pt-20"> <section className="py-20 sm:py-32 relative overflow-hidden"> <div className="absolute inset-0 bg-[url('/placeholder.svg?height=1080&width=1920')] bg-cover bg-center opacity-10" /> <div className="container mx-auto px-4 sm:px-6 relative z-10"> <motion.div variants={containerVariants} initial="hidden" animate="visible" className="text-center space-y-8" > <motion.h1 variants={itemVariants} className="text-4xl sm:text-6xl font-bold leading-tight" > Learn Crypto with <span className="bg-clip-text text-transparent bg-gradient-to-r from-yellow-400 to-yellow-600"> {" "} Confidence </span> </motion.h1> <motion.p variants={itemVariants} className="text-xl sm:text-2xl text-gray-400 max-w-3xl mx-auto" > Join the of Journey about Crypto on the {"world's "}most powerful crypto learning platform. </motion.p> <motion.div variants={itemVariants} className="flex flex-col sm:flex-row justify-center items-center space-y-4 sm:space-y-0 sm:space-x-4" > <Button onClick={() => router.push("/auth/signin")} className="w-full sm:w-auto bg-yellow-500 text-gray-900 hover:bg-yellow-600 text-lg py-6 px-8" > Start Trading Now <ArrowRight className="ml-2 h-5 w-5" /> </Button> <Button variant="outline" className="w-full sm:w-auto text-yellow-500 border-yellow-500 hover:bg-yellow-500 hover:text-gray-900 text-lg py-6 px-8" > Explore Markets </Button> </motion.div> </motion.div> </div> </section> <section className="py-16 bg-gray-800"> <div className="container mx-auto px-4 sm:px-6"> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8"> {[ { icon: Wallet, title: "Secure Wallet", description: "Store your crypto assets safely", }, { icon: BarChart2, title: "Advanced Trading", description: "Access powerful trading tools", }, { icon: Lock, title: "Bank-grade Security", description: "Your funds are always protected", }, { icon: Zap, title: "Instant Transactions", description: "Lightning-fast crypto transfers", }, ].map((feature, index) => ( <motion.div key={index} variants={itemVariants} initial="hidden" whileInView="visible" viewport={{ once: true }} className="bg-gray-700 p-6 rounded-lg shadow-lg hover:shadow-yellow-500/20 transition-shadow duration-300" > <feature.icon className="h-12 w-12 text-yellow-500 mb-4" /> <h3 className="text-xl font-semibold mb-2"> {feature.title} </h3> <p className="text-gray-400">{feature.description}</p> </motion.div> ))} </div> </div> </section> <section className="py-20 bg-gray-900"> <div className="container mx-auto px-4 sm:px-6"> <motion.h2 initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} transition={{ duration: 0.5 }} className="text-3xl sm:text-4xl font-bold text-center mb-12" > Popular Cryptocurrencies </motion.h2> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8"> {[ { icon: Bitcoin, name: "Bitcoin", symbol: "BTC", color: "yellow", }, { icon: Bitcoin, name: "Ethereum", symbol: "ETH", color: "blue", }, { icon: Globe, name: "Ripple", symbol: "XRP", color: "indigo" }, ].map((crypto, index) => ( <motion.div key={index} variants={itemVariants} initial="hidden" whileInView="visible" viewport={{ once: true }} className="bg-gray-800 p-6 rounded-lg shadow-lg hover:shadow-yellow-500/20 transition-shadow duration-300 flex items-center justify-between" > <div className="flex items-center space-x-4"> <crypto.icon className={`h-12 w-12 text-${crypto.color}-500`} /> <div> <h3 className="text-xl font-semibold">{crypto.name}</h3> <p className="text-gray-400">{crypto.symbol}</p> </div> </div> <div className="text-right"> <p className="text-2xl font-bold">$ 0.00</p> <p className={`text-sm ${ index % 2 === 0 ? "text-green-500" : "text-red-500" }`} > {index % 2 === 0 ? "+" : "-"} {(Math.random() * 5).toFixed(2)}% </p> </div> </motion.div> ))} </div> <div className="text-center mt-12"> <Button variant="outline" className="text-yellow-500 border-yellow-500 hover:bg-yellow-500 hover:text-gray-900" > View All Markets <ChevronRight className="ml-2 h-4 w-4" /> </Button> </div> </div> </section> <section className="py-20 bg-gray-800"> <div className="container mx-auto px-4 sm:px-6"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center"> <motion.div variants={containerVariants} initial="hidden" whileInView="visible" viewport={{ once: true }} className="space-y-6" > <motion.h2 variants={itemVariants} className="text-3xl sm:text-4xl font-bold" > Start Your Crypto Journey Today </motion.h2> <motion.p variants={itemVariants} className="text-xl text-gray-400" > Join millions of users worldwide and experience the power of decentralized finance. </motion.p> <motion.ul variants={containerVariants} className="space-y-4"> {[ "Create your account in minutes", "Secure storage for your digital assets", "24/7 access to global markets", "Advanced trading tools and analytics", ].map((item, index) => ( <motion.li key={index} variants={itemVariants} className="flex items-center space-x-3" > <svg className="h-5 w-5 text-yellow-500" fill="none" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" viewBox="0 0 24 24" stroke="currentColor" > <path d="M5 13l4 4L19 7"></path> </svg> <span>{item}</span> </motion.li> ))} </motion.ul> <motion.div variants={itemVariants}> <Button onClick={() => router.push("/auth/signin")} className="bg-yellow-500 text-gray-900 hover:bg-yellow-600 text-lg py-6 px-8" > Create Your Free Account <ArrowRight className="ml-2 h-5 w-5" /> </Button> </motion.div> </motion.div> <motion.div variants={itemVariants} initial="hidden" whileInView="visible" viewport={{ once: true }} className="relative" > <div className="absolute inset-0 bg-gradient-to-r from-yellow-400 to-yellow-600 rounded-lg transform -rotate-6"></div> <Image fill={true} src="/placeholder.svg?height=600&width=800" alt="Crypto trading platform" className="relative z-10 rounded-lg shadow-xl" /> </motion.div> </div> </div> </section> </main> <Footer /> </div> ); }
Describe the contents of the file app/favicon.ico.
<Error reading file: 'utf-8' codec can't decode byte 0x96 in position 18: invalid start byte>
Describe the folder app/auth/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/test/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(pages)/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(server)/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/utils/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/api/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/auth/signin/.
This is a directory. It may contain files or subdirectories.
Describe the contents of the file app/auth/signin/page.tsx.
"use client"; import React, { useEffect } from 'react'; import { motion } from 'framer-motion'; import { signIn, useSession } from 'next-auth/react'; import { FcGoogle } from 'react-icons/fc'; import { Button } from "@/components/ui/button"; import { useRouter } from 'next/navigation'; export default function GoogleSignIn() { const { data: session, status } = useSession(); // Access the session status const router = useRouter(); const containerVariants = { hidden: { opacity: 0, scale: 0.8 }, visible: { opacity: 1, scale: 1, transition: { type: "spring", stiffness: 100, damping: 15, staggerChildren: 0.1 } } }; const itemVariants = { hidden: { opacity: 0, y: 20 }, visible: { opacity: 1, y: 0 } }; useEffect(() => { if (status === "authenticated") { console.log(`User : ${session.user}`); router.push('/markets'); } }, [status, session, router]); return ( <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-500 to-purple-600 p-4"> <motion.div className="bg-white dark:bg-gray-800 p-8 rounded-lg shadow-2xl w-full max-w-md" variants={containerVariants} initial="hidden" animate="visible" > <motion.div className="flex justify-center mb-8" variants={itemVariants} > <FcGoogle className="w-16 h-16" /> </motion.div> <motion.h1 className="text-3xl font-bold text-center mb-6 text-gray-800 dark:text-white" variants={itemVariants} > Sign in with Google </motion.h1> <motion.p className="text-center text-gray-600 dark:text-gray-400 mb-8" variants={itemVariants} > Use your Google account to sign in securely and quickly. </motion.p> <motion.div variants={itemVariants}> <Button variant="default" className="w-full flex items-center justify-center space-x-2 bg-blue-600 hover:bg-blue-700 text-white" onClick={async () => await signIn('google')} > <FcGoogle className="w-5 h-5 bg-white rounded-full" /> <span>Continue with Google</span> </Button> </motion.div> <motion.p variants={itemVariants} className="mt-6 text-sm text-center text-gray-600 dark:text-gray-400" > By continuing, you agree to our <a href="#" className="text-blue-500 hover:underline ml-1">Terms of Service</a> and <a href="#" className="text-blue-500 hover:underline ml-1">Privacy Policy</a>. </motion.p> </motion.div> </div> ); }
Describe the contents of the file app/test/page.tsx.
'use client' export default function Home() { return ( <main className="flex min-h-screen flex-col items-center justify-between p-24"> <h1>Welcome to Your App</h1> </main> ) }
Describe the contents of the file app/(pages)/layout.tsx.
'use client' import { useEffect, useState } from 'react' import { Appbar } from '@/components/core/Appbar' import SideNavbar from '@/components/core/sideNavBar' import { Toast } from '@/components/ui/toast' export default function RootLayout({ children, }: { children: React.ReactNode }) { const [isOpen, setIsOpen] = useState(false) const toggleSidebar = () => setIsOpen(!isOpen) useEffect(()=>{ const innerWidth = window.innerWidth if(innerWidth > 768) { setIsOpen(true) } }, []) return ( <div className="flex flex-col min-h-screen"> <div className='fixed top-0 left-0 w-full z-50'> <Appbar toggleSidebar={toggleSidebar}/> </div> <div className="flex flex-grow pt-16"> <SideNavbar isOpen={isOpen} /> <div className={`flex-grow p-4 transition-all duration-300 ${isOpen ? 'ml-[240px]' : ''}`}> {children} </div> <Toast/> </div> </div> ) }
Describe the folder app/(pages)/orders/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(pages)/profile/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(pages)/markets/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(pages)/trades/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(pages)/trade/.
This is a directory. It may contain files or subdirectories.
Describe the contents of the file app/(pages)/orders/page.tsx.
'use client' import { useState, useEffect } from 'react' import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import { CheckCircle, XCircle, TrendingUp, TrendingDown, Package2, Clock } from 'lucide-react' import { Skeleton } from "@/components/ui/skeleton" type Order = { id: string transactionType: 'Buy' | 'Sell' amount: number status: 'Pending' | 'Success' | 'Failed' crypto: { currency: string } } export default function OrderDisplay() { const [orders, setOrders] = useState<Order[]>([]) const [loading, setLoading] = useState(true) const [error, setError] = useState<string | null>(null) useEffect(() => { const fetchOrders = async () => { try { const response = await fetch('/api/orders') const data = await response.json() if (data.success) { setOrders(data.orders) } else { setError(data.message) } } catch (err) { setError('Failed to fetch orders') } finally { setLoading(false) } } fetchOrders() }, []) if (error) return ( <div className="text-center p-4 bg-red-100 text-red-800 rounded-md"> <XCircle className="w-6 h-6 mx-auto mb-2" /> <p>{error}</p> </div> ) if (loading) { return ( <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3"> {[...Array(6)].map((_, index) => ( <Card key={index} className="overflow-hidden"> <CardHeader className="bg-primary"> <Skeleton className="h-6 w-24" /> </CardHeader> <CardContent className="pt-4"> <Skeleton className="h-4 w-20 mb-2" /> <Skeleton className="h-4 w-16" /> </CardContent> </Card> ))} </div> ) } if (orders.length === 0) { return ( <Card className="w-full max-w-md mx-auto"> <CardContent className="flex flex-col items-center justify-center p-6"> <Package2 className="w-12 h-12 text-muted-foreground mb-4" /> <h2 className="text-xl font-semibold mb-2">No Orders Placed</h2> <p className="text-center text-muted-foreground"> {" You haven't placed any orders yet. Start trading to see your order history here."} </p> </CardContent> </Card> ) } return ( <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3"> {orders.map((order) => ( <Card key={order.id} className="overflow-hidden"> <CardHeader className={`${order.transactionType === 'Buy' ? 'bg-green-100' : 'bg-red-100'} text-foreground`}> <CardTitle className="flex items-center justify-between"> <span>{order.crypto.currency}</span> <Badge variant={order.transactionType === 'Buy' ? 'default' : 'secondary'}> {order.transactionType} </Badge> </CardTitle> </CardHeader> <CardContent className="pt-4"> <div className="flex items-center justify-between mb-2"> <span className="text-lg font-semibold">${order.amount.toFixed(2)}</span> {order.status === 'Success' && <CheckCircle className="text-green-500 w-5 h-5" />} {order.status === 'Failed' && <XCircle className="text-red-500 w-5 h-5" />} {order.status === 'Pending' && <Clock className="text-yellow-500 w-5 h-5" />} </div> <div className="flex items-center text-sm text-muted-foreground"> {order.transactionType === 'Buy' ? ( <TrendingUp className="mr-1 h-4 w-4 text-green-500" /> ) : ( <TrendingDown className="mr-1 h-4 w-4 text-red-500" /> )} <span>{order.transactionType === 'Buy' ? 'Bought' : 'Sold'}</span> <span className="ml-2 px-2 py-1 bg-gray-100 rounded-full text-xs"> {order.status} </span> </div> </CardContent> </Card> ))} </div> ) }
Describe the contents of the file app/(pages)/profile/page.tsx.
import { getServerSession } from "next-auth/next" import { redirect } from "next/navigation" import { prisma } from "@/lib/prisma" import ProfileForm from "@/components/account/ProfilePage" export default async function ProfilePage() { const session = await getServerSession() if (!session || !session.user?.email) { redirect("/login") } const user = await prisma.user.findUnique({ where: { email: session.user.email }, select: { id: true, name: true, email: true, image: true, balance: true, createdAt: true, updatedAt: true, }, }) if (!user) { return <div>User not found</div> } return ( <div className="container mx-auto py-8"> <h1 className="text-2xl font-bold mb-6">Profile</h1> <ProfileForm user={user} /> </div> ) }
Describe the contents of the file app/(pages)/markets/page.tsx.
import CryptoList from "@/components/trade/markets/cryptoPage" export default function CryptoDashboard() { return ( <div className="relative flex h-screen overflow-hidden"> <main className="flex-1 overflow-hidden p-4 "> <CryptoList /> </main> </div> ) }
Describe the contents of the file app/(pages)/trades/page.tsx.
'use client' import { useState, useEffect, useCallback } from 'react' import { useSession } from 'next-auth/react' import axios from 'axios' import { useToast } from "@/components/ui/use-toast" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" import { Button } from "@/components/ui/button" import { ArrowUpIcon, ArrowDownIcon } from 'lucide-react' interface Holding { id: number currency: string amount: number buyPrice: number currentPrice: number } export default function TradingPage() { const [holdings, setHoldings] = useState<Holding[]>([]) const [socket, setSocket] = useState<WebSocket | null>(null) const { data: session } = useSession() const { toast } = useToast() const fetchHoldings = useCallback(async () => { if (session?.user?.email) { try { const response = await axios.get('/api/holdings') console.log(response.data) setHoldings(response.data) } catch (error) { console.error('Error fetching holdings:', error) toast({ title: "Error", description: "Failed to fetch holdings. Please try again.", variant: "destructive", }) } } }, [session?.user?.email, toast]) useEffect(() => { fetchHoldings() }, [fetchHoldings]) useEffect(() => { const ws = new WebSocket('wss://stream.binance.com:9443/ws') setSocket(ws) ws.onopen = () => { console.log('Connected to Binance WebSocket') const subscribeMsg = { method: 'SUBSCRIBE', params: holdings.map(h => `${h.currency.toLowerCase()}usdt@ticker`), id: 1 } ws.send(JSON.stringify(subscribeMsg)) } ws.onmessage = (event) => { const data = JSON.parse(event.data) if (data.e === '24hrTicker') { setHoldings(prevHoldings => prevHoldings.map(holding => holding.currency.toLowerCase() === data.s.slice(0, -4).toLowerCase() ? { ...holding, currentPrice: parseFloat(data.c) } : holding ) ) } } return () => { if (ws) { ws.close() } } }, [holdings]) const handleSell = async (holdingId: number) => { try { await axios.post('/api/sell', { holdingId }) toast({ title: "Sell order placed", description: "Your sell order has been successfully placed.", }) fetchHoldings() } catch (error) { console.error('Error placing sell order:', error) toast({ title: "Error", description: "Failed to place sell order. Please try again.", variant: "destructive", }) } } const calculatePercentChange = (buyPrice: number, currentPrice: number) => { return ((currentPrice - buyPrice) / buyPrice) * 100 } return ( <div className="container mx-auto p-4"> <Card className="mb-8"> <CardHeader> <CardTitle>Your Crypto Holdings</CardTitle> </CardHeader> <CardContent> <Table> <TableHeader> <TableRow> <TableHead>Currency</TableHead> <TableHead>Amount</TableHead> <TableHead>Buy Price</TableHead> <TableHead>Current Price</TableHead> <TableHead>Profit/Loss</TableHead> <TableHead>Action</TableHead> </TableRow> </TableHeader> <TableBody> {holdings.map((holding) => { const percentChange = calculatePercentChange(holding.buyPrice, holding.currentPrice) const isProfit = percentChange >= 0 return ( <TableRow key={holding.id}> <TableCell>{holding.currency}</TableCell> <TableCell>{holding.amount.toFixed(8)}</TableCell> <TableCell>${holding.buyPrice.toFixed(2)}</TableCell> <TableCell>${holding.currentPrice.toFixed(2)}</TableCell> <TableCell className={isProfit ? 'text-green-500' : 'text-red-500'}> {isProfit ? <ArrowUpIcon className="inline mr-1" /> : <ArrowDownIcon className="inline mr-1" />} {Math.abs(percentChange).toFixed(2)}% </TableCell> <TableCell> <Button onClick={() => handleSell(holding.id)} variant="destructive"> Sell </Button> </TableCell> </TableRow> ) })} </TableBody> </Table> </CardContent> </Card> </div> ) }
Describe the folder app/(pages)/trade/[market]/.
This is a directory. It may contain files or subdirectories.
Describe the contents of the file app/(pages)/trade/[market]/page.tsx.
"use client"; import { useState, useEffect } from "react"; import useWebSocket from "react-use-websocket"; import { Card } from "@/components/ui/card"; import { Ask } from "@/components/trade/markets/AskTable"; import { Bid } from "@/components/trade/markets/BidTable"; import { useParams } from "next/navigation"; import { Skeleton } from "@/components/ui/skeleton"; import { TradeViewChartSkeleton } from "@/components/Skeletons/TradingViewSkeleton"; import { AskSkeleton } from "@/components/Skeletons/AskBidSkeleton"; import TradeViewChart from "@/components/trade/markets/TradeView"; import { OrderUI } from "@/components/trade/markets/OrderUI"; import { MarketBar } from "@/components/trade/markets/MarketBar"; type Order = [string, string]; type OrderBookUpdate = { e: string; E: number; s: string; U: number; u: number; b: Order[]; a: Order[]; }; type OrderBookState = { bids: Map<string, string>; asks: Map<string, string>; }; export default function Markets() { const { market } = useParams(); const [orderBook, setOrderBook] = useState<OrderBookState>({ bids: new Map(), asks: new Map(), }); const [isLoading, setIsLoading] = useState(true); const { lastJsonMessage } = useWebSocket( `wss://stream.binance.com:9443/ws/${market}@depth` ); useEffect(() => { if (lastJsonMessage) { const update = lastJsonMessage as OrderBookUpdate; setIsLoading(false); setOrderBook((prevOrderBook) => { const newBids = new Map(prevOrderBook.bids); const newAsks = new Map(prevOrderBook.asks); update.b.forEach(([price, quantity]) => { if (parseFloat(quantity) === 0) { newBids.delete(price); } else { newBids.set(price, quantity); } }); update.a.forEach(([price, quantity]) => { if (parseFloat(quantity) === 0) { newAsks.delete(price); } else { newAsks.set(price, quantity); } }); return { bids: newBids, asks: newAsks }; }); setIsLoading(false); } }, [lastJsonMessage]); return ( <div className="container mx-auto p-4"> <MarketBar market={market as string} /> <div className="flex gap-4"> <Card className="mb-4 flex-1 w-[4/7] border-none"> <div className="h-[400px]"> {isLoading ? ( <TradeViewChartSkeleton /> ) : ( <TradeViewChart market={market.toString()} /> )} </div> </Card> <div className="hidden sm:flex flex-col md:grid-cols-2 gap-4"> {isLoading ? <AskSkeleton /> : <Ask asks={orderBook.asks} />} {isLoading ? <AskSkeleton /> : <Bid bids={orderBook.bids} />} </div> <div className="flex h-full justify-items-end"> {isLoading ? ( <Skeleton className="h-[500px] w-[300px]" /> ) : ( <OrderUI market={market as string} /> )} </div> </div> </div> ); }
Describe the folder app/(server)/actions/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(server)/api/.
This is a directory. It may contain files or subdirectories.
Describe the contents of the file app/(server)/actions/getBalance.ts.
'use server' import { authOptions } from "@/lib/auth"; import { prisma } from "@/lib/prisma"; import { getServerSession } from "next-auth"; export async function getBalance() { const session = await getServerSession(authOptions); if (!session?.user?.email) { return 0; } const user = await prisma.user.findUnique({ where: { email: session.user.email, }, }); return user?.balance ?? 0; }
Describe the contents of the file app/(server)/actions/changeUserProfile.ts.
'use server' import { prisma } from '@/lib/prisma' import { revalidatePath } from 'next/cache' export async function updateUserProfile(userId: string, formData: FormData) { const name = formData.get('name') as string const email = formData.get('email') as string const image = formData.get('image') as string try { await prisma.user.update({ where: { id: userId }, data: { name, email, image }, }) revalidatePath('/profile') return { success: true, message: 'Profile updated successfully' } } catch (error) { console.error('Failed to update profile:', error) return { success: false, message: 'Failed to update profile' } } } export async function getUserProfile(userId: string) { try { const user = await prisma.user.findUnique({ where: { id: userId }, select: { name: true, email: true, image: true, balance: true, createdAt: true, updatedAt: true, }, }) return user } catch (error) { console.error('Failed to fetch user profile:', error) return null } }
Describe the contents of the file app/(server)/api/route.ts.
import { NextResponse} from "next/server"; export async function GET(request: Request) { return NextResponse.json({ message: "Server is Running", }); }
Describe the folder app/(server)/api/orders/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(server)/api/sell-crypto/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(server)/api/buy-crypto/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(server)/api/holdings/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(server)/api/get-profile/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(server)/api/create-order/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(server)/api/verify-payment/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/(server)/api/update-profile/.
This is a directory. It may contain files or subdirectories.
Describe the contents of the file app/(server)/api/orders/route.ts.
import { NextRequest, NextResponse } from "next/server"; import { PrismaClient } from "@prisma/client"; import { getServerSession } from "next-auth"; import { authOptions } from "@/lib/auth"; const prisma = new PrismaClient(); export async function GET(request: NextRequest) { try { const session = await getServerSession(authOptions); if (!session || !session.user?.email) { return NextResponse.json( { success: false, message: "User not authenticated" }, { status: 401 } ); } const user = await prisma.user.findUnique({ where: { email: session.user.email }, select: { id: true }, }); if (!user) { return NextResponse.json( { success: false, message: "User not found" }, { status: 404 } ); } const orders = await prisma.order.findMany({ where: { userId: user.id }, include: { crypto: { select: { currency: true, }, }, }, }); const transformedOrders = orders.map(order => ({ id: order.id, transactionType: order.transactionType, amount: order.amount, status: order.status, crypto: { currency: order.crypto?.currency || 'Unknown', }, })); return NextResponse.json( { success: true, orders: transformedOrders }, { status: 200 } ); } catch (error) { console.error("Error fetching orders:", error); return NextResponse.json( { success: false, message: "An error occurred while fetching orders." }, { status: 500 } ); } finally { await prisma.$disconnect(); } }
Describe the contents of the file app/(server)/api/sell-crypto/route.ts.
import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/prisma"; import { getServerSession } from "next-auth"; import { authOptions } from "@/lib/auth"; export async function POST(request: NextRequest) { const session = await getServerSession(authOptions); const emailId = session?.user?.email; if (!emailId) { return NextResponse.json( { success: false, message: "Not logged in" }, { status: 401 } ); } let result = null; try { const { market, price , marketPrice } = await request.json(); const crypto = market const amount = price if (!crypto || !amount) { return NextResponse.json( { success: false, message: "Missing crypto or amount" }, { status: 400 } ); } const user = await prisma.user.findUnique({ where: { email: emailId }, }); if (!user) { return NextResponse.json( { success: false, message: "User not found" }, { status: 404 } ); } const userCrypto = await prisma.crypto.findFirst({ where: { userId: user.id, currency: crypto, }, }); if (!userCrypto) { return NextResponse.json( { success: false, message: `${crypto} not found in your wallet` }, { status: 404 } ); } const cryptoAmount = userCrypto.buyAt; const amountNum = marketPrice * 0.99; if (isNaN(amountNum) || amountNum <= 0) { return NextResponse.json( { success: false, message: "Invalid amount specified" }, { status: 400 } ); } if (cryptoAmount < amountNum) { return NextResponse.json( { success: false, message: `Insufficient ${crypto} amount to sell` }, { status: 400 } ); } result = await prisma.$transaction(async (tx) => { const newOrder = await tx.order.create({ data: { userId: user.id, cryptoId: userCrypto.id, amount: amountNum, transactionType: "Sell", status: "Pending", }, }); const updatedCrypto = await tx.crypto.update({ where: { id: userCrypto.id }, data: { buyAt: cryptoAmount - amountNum, soldAt: userCrypto.soldAt ? userCrypto.soldAt + amountNum : amountNum, timeSoldAt: new Date().toISOString(), }, }); return { newOrder, updatedCrypto }; }); await prisma.order.update({ where: { id: result.newOrder.id }, data: { status: "Success" }, }); return NextResponse.json( { success: true, message: `${crypto} sold successfully`, data: result }, { status: 200 } ); } catch (error) { console.error(error); // Check if result is not null and if newOrder exists if (result?.newOrder?.id) { await prisma.order.update({ where: { id: result.newOrder.id }, data: { status: "Failed" }, }); } return NextResponse.json( { success: false, message: "An error occurred. Please try again." }, { status: 500 } ); } }
Describe the contents of the file app/(server)/api/buy-crypto/route.ts.
import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/prisma"; import { getServerSession } from "next-auth"; import { authOptions } from "@/lib/auth"; export async function POST(request: NextRequest) { const session = await getServerSession(authOptions); const emailId = session?.user?.email; if (!emailId) { return NextResponse.json( { success: false, message: "User not authenticated" }, { status: 401 } ); } let result = null; try { const { market , price , marketPrice } = await request.json(); const crypto = market const amount = Number(price) if (!crypto || !amount) { return NextResponse.json( { success: false, message: "Missing crypto or amount" }, { status: 400 } ); } const user = await prisma.user.findUnique({ where: { email: emailId }, }); if (!user) { return NextResponse.json( { success: false, message: "User not found" }, { status: 404 } ); } const amountNum: number = amount; if (isNaN(amountNum) || amountNum <= 0) { return NextResponse.json( { success: false, message: "Invalid amount specified" }, { status: 400 } ); } if (user.balance < amountNum) { return NextResponse.json( { success: false, message: "Insufficient balance. Please deposit more.", }, { status: 400 } ); } result = await prisma.$transaction(async (tx) => { const cryptoOrder = await tx.crypto.create({ data: { userId: user.id, currency: crypto, buyAt: Number(marketPrice) - Number(marketPrice * 0.02) , timeBuyAt: new Date().toISOString(), transactionFee: amountNum * 0.2, soldAt: 0, }, }); const newOrder = await tx.order.create({ data: { amount, status: "Pending", userId: user.id, cryptoId: cryptoOrder.id, transactionType : "Buy" }, }); await tx.user.update({ where: { id: user.id }, data: { balance: { decrement: amountNum } }, }); return { newOrder, cryptoOrder }; }); await prisma.order.update({ where: { id: result.newOrder.id }, data: { status: "Success" }, }); return NextResponse.json( { success: true, message: "Crypto purchased successfully", data: result }, { status: 200 } ); } catch (error) { console.error(error); if (result?.newOrder?.id) { await prisma.order.update({ where: { id: result.newOrder.id }, data: { status: "Failed" }, }); } return NextResponse.json( { success: false, message: "An error occurred. Please try again." }, { status: 500 } ); } }
Describe the contents of the file app/(server)/api/holdings/route.ts.
import { NextResponse } from 'next/server' import { getServerSession } from "next-auth/next" import { authOptions } from "@/lib/auth" import { prisma } from "@/lib/prisma" export async function GET() { const session = await getServerSession(authOptions) if (!session || !session.user?.email) { return NextResponse.json({ error: "Not authenticated" }, { status: 401 }) } try { const user = await prisma.user.findUnique({ where: { email: session.user.email }, include: { crypto: { where: { soldAt: null }, include: { orders: { where: { status: 'Success' } } } } } }) if (!user) { return NextResponse.json({ error: "User not found" }, { status: 404 }) } const holdings = user.crypto.map(crypto => { const totalBought = crypto.orders .filter(order => order.transactionType === 'Buy') .reduce((sum, order) => sum + order.amount, 0) const totalSold = crypto.orders .filter(order => order.transactionType === 'Sell') .reduce((sum, order) => sum + order.amount, 0) const currentAmount = totalBought - totalSold return { id: crypto.id, currency: crypto.currency, amount: currentAmount / 100000000, buyPrice: crypto.buyAt / 100, currentPrice: 0, } }).filter(holding => holding.amount > 0) console.log(holdings); return NextResponse.json(holdings) } catch (error) { console.error('Error fetching holdings:', error) return NextResponse.json({ error: "Failed to fetch holdings" }, { status: 500 }) } }
Describe the contents of the file app/(server)/api/get-profile/route.ts.
import { prisma } from "@/lib/prisma"; import { getServerSession } from "next-auth"; export async function GET(req: Request) { const session = await getServerSession(); const email = session?.user?.email; if (!email) { return new Response(JSON.stringify({ message: "User not authenticated" }), { status: 401, }); } const user = await prisma.user.findUnique({ where: { email, }, select: { name: true, email: true, image: true, createdAt: true, updatedAt: true, id: true, }, }); return new Response(JSON.stringify(user), { status: 200 }) }
Describe the contents of the file app/(server)/api/create-order/route.ts.
import { NextResponse } from 'next/server' import { getServerSession } from 'next-auth/next' import { authOptions } from '@/lib/auth' import { prisma } from '@/lib/prisma' import Razorpay from 'razorpay' const razorpay = new Razorpay({ key_id: process.env.RAZORPAY_KEY_ID!, key_secret: process.env.RAZORPAY_KEY_SECRET!, }) export async function POST(req: Request) { try { const session = await getServerSession(authOptions) const userEmail = session?.user?.email if (!userEmail) { return NextResponse.json({ success: false, message: "Please login to deposit", status: 401 }) } const user = await prisma.user.findUnique({ where: { email: userEmail } }) if (!user) { return NextResponse.json({ success: false, message: "User not found", status: 404 }) } const { amount } = await req.json() if (!amount || isNaN(amount) || amount <= 0) { return NextResponse.json({ success: false, message: "Invalid amount", status: 400 }) } const amountInPaise = Math.round(parseFloat(amount) * 100) const order = await razorpay.orders.create({ amount: amountInPaise, currency: 'INR', receipt: 'receipt_' + Math.random().toString(36).substring(7), }) // Create a new Deposit record in the database await prisma.deposit.create({ data: { id: order.id, userId: user.id, amount: amountInPaise, amount_due: order.amount_due, amount_paid: order.amount_paid, currency: order.currency, receipt: order.receipt, status: 'Pending', } }) return NextResponse.json({ success: true, order: { id: order.id, amount: order.amount, currency: order.currency } }) } catch (error) { console.error('Error creating order:', error) return NextResponse.json({ success: false, error: 'Failed to create order' }, { status: 500 }) } }
Describe the contents of the file app/(server)/api/verify-payment/route..ts.
import { NextResponse } from 'next/server' import { prisma } from '@/lib/prisma' import crypto from 'crypto' export async function POST(req: Request) { try { const { razorpay_order_id, razorpay_payment_id, razorpay_signature } = await req.json() const body = razorpay_order_id + "|" + razorpay_payment_id const expectedSignature = crypto .createHmac('sha256', process.env.RAZORPAY_KEY_SECRET!) .update(body.toString()) .digest('hex') const isAuthentic = expectedSignature === razorpay_signature if (isAuthentic) { // Update the deposit status in the database await prisma.deposit.update({ where: { id: razorpay_order_id }, data: { status: 'Success', amount_paid: await getPaymentAmount(razorpay_payment_id) } }) // Update user's balance const deposit = await prisma.deposit.findUnique({ where: { id: razorpay_order_id }, include: { user: true } }) if (deposit) { await prisma.user.update({ where: { id: deposit.userId }, data: { balance: { increment: deposit.amount / 100 } } // Convert paise to rupees }) } return NextResponse.json({ success: true }) } else { await prisma.deposit.update({ where: { id: razorpay_order_id }, data: { status: 'Failed' } }) return NextResponse.json({ success: false, message: 'Invalid signature' }, { status: 400 }) } } catch (error) { console.error('Error verifying payment:', error) return NextResponse.json({ success: false, error: 'Failed to verify payment' }, { status: 500 }) } } async function getPaymentAmount(paymentId: string): Promise<number> { const razorpay = new (require('razorpay'))({ key_id: process.env.RAZORPAY_KEY_ID, key_secret: process.env.RAZORPAY_KEY_SECRET, }) const payment = await razorpay.payments.fetch(paymentId) return payment.amount }
Describe the contents of the file app/(server)/api/update-profile/route.ts.
import { getServerSession } from "next-auth/next" import { NextResponse } from "next/server" import { prisma } from "@/lib/prisma" export async function PUT(req: Request) { const session = await getServerSession() if (!session || !session.user?.email) { return NextResponse.json({ error: "Not authenticated" }, { status: 401 }) } const data = await req.json() try { const updatedUser = await prisma.user.update({ where: { email: session.user.email }, data: { name: data.name, image: data.image, }, }) return NextResponse.json(updatedUser) } catch (error) { console.error("Error updating user:", error) return NextResponse.json({ error: "Failed to update user" }, { status: 500 }) } }
Describe the contents of the file app/utils/Query.ts.
// import { useQuery } from "@tanstack/react-query"; // import axios from "axios"; // export function useGetCrypto(){ // const { data , isLoading } = useQuery({ // queryKey: ["market-trades"], // queryFn: async () => { // const response = await axios.get(Market_URL); // return response.data; // } // }); // return { data , isLoading }; // }
Describe the contents of the file app/utils/Algorithms.ts.
export function formatNumber(number: number): string { const thresholds: [number, string][] = [ [1e12, 'T'], [1e9, 'B'], [1e6, 'M'], [1e3, 'K'], ]; const isNegative = number < 0; number = Math.abs(number); for (const [threshold, suffix] of thresholds) { if (number >= threshold) { const value = number / threshold; const formattedNumber = `${value.toFixed(2)}${suffix}`; return isNegative ? `-${formattedNumber}` : formattedNumber; } } return isNegative ? `-${number.toFixed(2)}` : number.toFixed(2); } type AskBidArray = [string, string][]; export function removeZeroEntries(asks: AskBidArray) { const filteredAsks = asks.filter(entry => entry[1] !== "0.000"); return filteredAsks } export function removeZeroAsks(ask:any){ for (let i = 0; i < ask.length; i++) { if (ask[i][1] === "0.000") { ask.splice(i, 1); i--; // decrement i to account for the removed element console.log("ask removed" + ask ) return ask } } }
Describe the contents of the file app/utils/ChartManager.ts.
import { ColorType, createChart as createLightWeightChart, CrosshairMode, ISeriesApi, UTCTimestamp, } from "lightweight-charts"; export class ChartManager { private candleSeries: ISeriesApi<"Candlestick">; private lastUpdateTime: number = 0; private chart: any; private currentBar: { open: number | null; high: number | null; low: number | null; close: number | null; } = { open: null, high: null, low: null, close: null, }; constructor( ref: any, initialData: any[], layout: { background: string; color: string } ) { const chart = createLightWeightChart(ref, { autoSize: true, overlayPriceScales: { ticksVisible: true, borderVisible: true, }, crosshair: { mode: CrosshairMode.Normal, }, rightPriceScale: { visible: true, ticksVisible: true, entireTextOnly: true, }, grid: { horzLines: { visible: false, }, vertLines: { visible: false, }, }, layout: { background: { type: ColorType.Solid, color: layout.background, }, textColor: "white", }, }); this.chart = chart; this.candleSeries = chart.addCandlestickSeries(); this.candleSeries.setData( initialData.map((data) => ({ ...data, time: (data.timestamp / 1000) as UTCTimestamp, })) ); } public update(updatedPrice: any) { if (!this.lastUpdateTime) { this.lastUpdateTime = new Date().getTime(); } this.candleSeries.update({ time: (this.lastUpdateTime / 1000) as UTCTimestamp, close: updatedPrice.close, low: updatedPrice.low, high: updatedPrice.high, open: updatedPrice.open, }); if (updatedPrice.newCandleInitiated) { this.lastUpdateTime = updatedPrice.time; } } public destroy() { this.chart.remove(); } }
Describe the contents of the file app/utils/nothing.ts.
Describe the contents of the file app/utils/ServerProps.ts.
import axios from "axios"; const Market_URL = "https://price-indexer.workers.madlads.com/?ids=solana,usd-coin,pyth-network,jito-governance-token,tether,bonk,helium,helium-mobile,bitcoin,ethereum,dogwifcoin,jupiter-exchange-solana,parcl,render-token,sharky-fi,tensor,wormhole,wen-4,cat-in-a-dogs-world,book-of-meme,raydium,hivemapper,kamino,drift-protocol,nyan,jeo-boden,habibi-sol,io,zeta,mother-iggy,shuffle-2,pepe,shiba-inu,chainlink,uniswap,ondo-finance,holograph,starknet,matic-network,fantom,mon-protocol,blur,worldcoin-wld,polyhedra-network,unagi-token,layerzero" export async function getCrypto(): Promise<string[]> { // console.log("req came") const response = await axios.get(Market_URL); // console.log(response.data); return response.data; }
Describe the contents of the file app/utils/SignalingManager.ts.
import { TickerProps } from "./types"; export const BASE_URL = "wss://ws.backpack.exchange/" export class SignalingManager { private ws: WebSocket; private static instance: SignalingManager; private bufferedMessages: any[] = []; private callbacks: any = {}; private id: number; private initialized: boolean = false; private constructor() { this.ws = new WebSocket(BASE_URL); this.bufferedMessages = []; this.id = 1; this.init(); } public static getInstance() { if (!this.instance) { this.instance = new SignalingManager(); } return this.instance; } init() { this.ws.onopen = () => { this.initialized = true; this.bufferedMessages.forEach(message => { this.ws.send(JSON.stringify(message)); }); this.bufferedMessages = []; } this.ws.onmessage = (event) => { const message = JSON.parse(event.data); const type = message.data.e; if (this.callbacks[type]) { this.callbacks[type].forEach(({ callback }:any) => { if (type === "ticker") { const newTicker: Partial<TickerProps> = { lastPrice: message.data.c, high: message.data.h, low: message.data.l, volume: message.data.v, quoteVolume: message.data.V, symbol: message.data.s, } callback(newTicker); } if (type === "depth") { // const newTicker: Partial<Ticker> = { // lastPrice: message.data.c, // high: message.data.h, // low: message.data.l, // volume: message.data.v, // quoteVolume: message.data.V, // symbol: message.data.s, // } // console.log(newTicker); // callback(newTicker); const updatedBids = message.data.b; const updatedAsks = message.data.a; callback({ bids: updatedBids, asks: updatedAsks }); } }); } } } sendMessage(message: any) { const messageToSend = { ...message, id: this.id++ } if (!this.initialized) { this.bufferedMessages.push(messageToSend); return; } this.ws.send(JSON.stringify(messageToSend)); } async registerCallback(type: string, callback: any, id: string) { this.callbacks[type] = this.callbacks[type] || []; this.callbacks[type].push({ callback, id }); // "ticker" => callback } async deRegisterCallback(type: string, id: string) { if (this.callbacks[type]) { //@ts-ignore const index = this.callbacks[type].findIndex(callback => callback.id === id); if (index !== -1) { this.callbacks[type].splice(index, 1); } } } }
Describe the contents of the file app/utils/types.ts.
import zod from "zod" export interface KLine { close: string; end: string; high: string; low: string; open: string; quoteVolume: string; start: string; trades: string; volume: string; } export interface Trade { "id": number, "isBuyerMaker": boolean, "price": string, "quantity": string, "quoteQuantity": string, "timestamp": number } export interface Depth { bids: [string, string][], asks: [string, string][], lastUpdateId: string } export interface TickerProps { "firstPrice": string, "high": string, "lastPrice": string, "low": string, "priceChange": string, "priceChangePercent": string, "quoteVolume": string, "symbol": string, "trades": string, "volume": string } export const orderVefication = zod.object({ amount: zod.number(), name : zod.string(), }) export interface SellProps { crypto:string amount : string soldAt :string userId : string } export interface AuthProps{ username:string, password:string } export interface TickerProps { symbol: string; lastPrice: string; high: string; low: string; volume: string; quoteVolume: string; priceChange: string; priceChangePercent: string; } export interface DepthProps { bids: [string, string][]; asks: [string, string][]; } export interface KlineProps { openTime: number; open: string; high: string; low: string; close: string; volume: string; closeTime: number; }
Describe the contents of the file app/utils/wsClient.ts.
Describe the folder app/api/auth/.
This is a directory. It may contain files or subdirectories.
Describe the folder app/api/auth/[...nextauth]/.
This is a directory. It may contain files or subdirectories.
Describe the contents of the file app/api/auth/[...nextauth]/route.ts.
import { authOptions } from "@/lib/auth" import NextAuth from "next-auth" const handler = NextAuth(authOptions) export { handler as GET, handler as POST }