-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup.sh
More file actions
1411 lines (1226 loc) · 48.8 KB
/
setup.sh
File metadata and controls
1411 lines (1226 loc) · 48.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# ============================================================
# ⛓️ ExamChain — Full Project Scaffold
# Run: bash setup.sh
# ============================================================
set -e
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo ""
echo -e "${CYAN}⛓️ ExamChain — Scaffolding your project...${NC}"
echo ""
# ── 1. Create Next.js app ────────────────────────────────────
npx create-next-app@latest examchain \
--typescript \
--tailwind \
--eslint \
--app \
--src-dir \
--import-alias "@/*" \
--no-git \
<< 'EOF'
EOF
cd examchain
echo -e "${GREEN}✅ Next.js created${NC}"
# ── 2. Install dependencies ──────────────────────────────────
echo -e "${CYAN}📦 Installing dependencies...${NC}"
npm install \
@anthropic-ai/sdk \
@solana/web3.js \
@solana/wallet-adapter-base \
@solana/wallet-adapter-react \
@solana/wallet-adapter-react-ui \
@solana/wallet-adapter-phantom \
@coral-xyz/anchor \
@pinata/sdk \
axios \
bcryptjs \
jsonwebtoken \
jose \
pdf-parse \
multer \
next-auth \
@auth/core \
zustand \
react-dropzone \
react-hot-toast \
lucide-react \
clsx \
tailwind-merge
npm install -D \
@types/bcryptjs \
@types/jsonwebtoken \
@types/multer \
@types/pdf-parse
echo -e "${GREEN}✅ Dependencies installed${NC}"
# ── 3. Environment file ──────────────────────────────────────
cat > .env.local << 'EOF'
# Anthropic
ANTHROPIC_API_KEY=your_anthropic_api_key_here
# Auth
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production
NEXTAUTH_SECRET=your_nextauth_secret_here
NEXTAUTH_URL=http://localhost:3000
# Pinata (IPFS)
PINATA_API_KEY=your_pinata_api_key_here
PINATA_SECRET_API_KEY=your_pinata_secret_here
PINATA_JWT=your_pinata_jwt_here
# Solana
NEXT_PUBLIC_SOLANA_NETWORK=devnet
NEXT_PUBLIC_SOLANA_RPC_URL=https://api.devnet.solana.com
SOLANA_PROGRAM_ID=your_anchor_program_id_here
# Database (simple JSON file for now, swap with Postgres later)
DB_PATH=./data/db.json
EOF
echo -e "${GREEN}✅ .env.local created${NC}"
# ── 4. Create folder structure ───────────────────────────────
mkdir -p src/app/\(auth\)/login
mkdir -p src/app/\(auth\)/register
mkdir -p src/app/dashboard
mkdir -p src/app/upload
mkdir -p src/app/quiz/\[id\]
mkdir -p src/app/summary/\[id\]
mkdir -p src/app/history
mkdir -p src/app/api/auth/login
mkdir -p src/app/api/auth/register
mkdir -p src/app/api/auth/me
mkdir -p src/app/api/upload
mkdir -p src/app/api/generate
mkdir -p src/app/api/summary
mkdir -p src/app/api/quiz/save
mkdir -p src/components/ui
mkdir -p src/components/quiz
mkdir -p src/components/wallet
mkdir -p src/lib
mkdir -p src/hooks
mkdir -p src/types
mkdir -p src/store
mkdir -p data
mkdir -p programs/examchain/src
echo -e "${GREEN}✅ Folder structure created${NC}"
# ── 5. Types ─────────────────────────────────────────────────
cat > src/types/index.ts << 'EOF'
export interface User {
id: string;
email: string;
passwordHash: string;
walletAddress?: string;
createdAt: string;
}
export interface QuizSession {
id: string;
userId: string;
pdfName: string;
ipfsHash: string;
questions: Question[];
score?: number;
completedAt?: string;
onChainTx?: string;
createdAt: string;
}
export interface Question {
id: string;
question: string;
options: string[];
correctAnswer: number;
explanation: string;
}
export interface Summary {
id: string;
userId: string;
pdfName: string;
ipfsHash: string;
bulletPoints: string[];
paragraph: string;
createdAt: string;
}
export interface AuthToken {
userId: string;
email: string;
}
EOF
# ── 6. Lib: DB (simple JSON store) ──────────────────────────
cat > src/lib/db.ts << 'EOF'
import fs from 'fs';
import path from 'path';
const DB_PATH = path.join(process.cwd(), 'data', 'db.json');
interface DB {
users: any[];
sessions: any[];
summaries: any[];
}
function readDB(): DB {
if (!fs.existsSync(DB_PATH)) {
const empty: DB = { users: [], sessions: [], summaries: [] };
fs.writeFileSync(DB_PATH, JSON.stringify(empty, null, 2));
return empty;
}
return JSON.parse(fs.readFileSync(DB_PATH, 'utf-8'));
}
function writeDB(data: DB) {
fs.writeFileSync(DB_PATH, JSON.stringify(data, null, 2));
}
export const db = {
getUsers: () => readDB().users,
getSessions: () => readDB().sessions,
getSummaries: () => readDB().summaries,
addUser: (user: any) => {
const data = readDB();
data.users.push(user);
writeDB(data);
},
addSession: (session: any) => {
const data = readDB();
data.sessions.push(session);
writeDB(data);
},
addSummary: (summary: any) => {
const data = readDB();
data.summaries.push(summary);
writeDB(data);
},
findUserByEmail: (email: string) => readDB().users.find((u: any) => u.email === email),
findUserById: (id: string) => readDB().users.find((u: any) => u.id === id),
findSessionsByUser: (userId: string) => readDB().sessions.filter((s: any) => s.userId === userId),
findSummariesByUser: (userId: string) => readDB().summaries.filter((s: any) => s.userId === userId),
findSessionById: (id: string) => readDB().sessions.find((s: any) => s.id === id),
findSummaryById: (id: string) => readDB().summaries.find((s: any) => s.id === id),
};
EOF
# ── 7. Lib: Auth ─────────────────────────────────────────────
cat > src/lib/auth.ts << 'EOF'
import { SignJWT, jwtVerify } from 'jose';
import { cookies } from 'next/headers';
const secret = new TextEncoder().encode(process.env.JWT_SECRET || 'fallback-secret');
export async function signToken(payload: { userId: string; email: string }) {
return await new SignJWT(payload)
.setProtectedHeader({ alg: 'HS256' })
.setExpirationTime('7d')
.sign(secret);
}
export async function verifyToken(token: string) {
try {
const { payload } = await jwtVerify(token, secret);
return payload as { userId: string; email: string };
} catch {
return null;
}
}
export async function getAuthUser() {
const cookieStore = cookies();
const token = cookieStore.get('auth_token')?.value;
if (!token) return null;
return verifyToken(token);
}
EOF
# ── 8. Lib: Claude AI ────────────────────────────────────────
cat > src/lib/claude.ts << 'EOF'
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
export async function generateQuestions(pdfText: string, pdfName: string) {
const response = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 4000,
messages: [{
role: 'user',
content: `You are an expert exam question generator. Analyze this academic content and generate 10 high-quality multiple choice questions that mirror the style and difficulty of real past exam questions for this subject.
PDF Name: ${pdfName}
Content:
${pdfText.slice(0, 8000)}
Generate exactly 10 questions. Each question must:
- Be based on key concepts from the content
- Have 4 options (A, B, C, D)
- Have exactly one correct answer
- Include a brief explanation of why the answer is correct
- Mirror real exam question patterns (application, analysis, not just recall)
Respond ONLY with valid JSON in this exact format:
{
"questions": [
{
"id": "q1",
"question": "Question text here?",
"options": ["Option A", "Option B", "Option C", "Option D"],
"correctAnswer": 0,
"explanation": "This is correct because..."
}
]
}`
}]
});
const text = response.content[0].type === 'text' ? response.content[0].text : '';
const clean = text.replace(/```json|```/g, '').trim();
return JSON.parse(clean);
}
export async function generateSummary(pdfText: string, pdfName: string) {
const response = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 2000,
messages: [{
role: 'user',
content: `You are an expert academic summarizer. Summarize this content in two formats.
PDF Name: ${pdfName}
Content:
${pdfText.slice(0, 8000)}
Respond ONLY with valid JSON:
{
"bulletPoints": [
"Key point 1",
"Key point 2",
"Key point 3",
"Key point 4",
"Key point 5",
"Key point 6",
"Key point 7",
"Key point 8"
],
"paragraph": "A comprehensive 3-4 sentence paragraph summary of the entire content..."
}`
}]
});
const text = response.content[0].type === 'text' ? response.content[0].text : '';
const clean = text.replace(/```json|```/g, '').trim();
return JSON.parse(clean);
}
EOF
# ── 9. Lib: IPFS ─────────────────────────────────────────────
cat > src/lib/ipfs.ts << 'EOF'
import axios from 'axios';
import FormData from 'form-data';
export async function uploadToIPFS(buffer: Buffer, fileName: string): Promise<string> {
const formData = new FormData();
formData.append('file', buffer, { filename: fileName, contentType: 'application/pdf' });
formData.append('pinataMetadata', JSON.stringify({ name: fileName }));
const response = await axios.post(
'https://api.pinata.cloud/pinning/pinFileToIPFS',
formData,
{
headers: {
Authorization: `Bearer ${process.env.PINATA_JWT}`,
...formData.getHeaders(),
},
maxBodyLength: Infinity,
}
);
return response.data.IpfsHash;
}
EOF
# ── 10. Lib: Solana ──────────────────────────────────────────
cat > src/lib/solana.ts << 'EOF'
import { Connection, PublicKey, clusterApiUrl } from '@solana/web3.js';
export const connection = new Connection(
process.env.NEXT_PUBLIC_SOLANA_RPC_URL || clusterApiUrl('devnet'),
'confirmed'
);
export function getSolanaExplorerUrl(tx: string) {
return `https://explorer.solana.com/tx/${tx}?cluster=devnet`;
}
EOF
# ── 11. Store: Auth ──────────────────────────────────────────
cat > src/store/authStore.ts << 'EOF'
import { create } from 'zustand';
interface AuthState {
user: { id: string; email: string } | null;
walletAddress: string | null;
setUser: (user: { id: string; email: string } | null) => void;
setWallet: (address: string | null) => void;
logout: () => void;
}
export const useAuthStore = create<AuthState>((set) => ({
user: null,
walletAddress: null,
setUser: (user) => set({ user }),
setWallet: (walletAddress) => set({ walletAddress }),
logout: () => set({ user: null, walletAddress: null }),
}));
EOF
# ── 12. API: Register ────────────────────────────────────────
cat > src/app/api/auth/register/route.ts << 'EOF'
import { NextRequest, NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import { db } from '@/lib/db';
import { signToken } from '@/lib/auth';
import { v4 as uuid } from 'crypto';
export async function POST(req: NextRequest) {
try {
const { email, password, walletAddress } = await req.json();
if (!email || !password) return NextResponse.json({ error: 'Email and password required' }, { status: 400 });
const existing = db.findUserByEmail(email);
if (existing) return NextResponse.json({ error: 'Email already registered' }, { status: 409 });
const passwordHash = await bcrypt.hash(password, 12);
const user = {
id: crypto.randomUUID(),
email,
passwordHash,
walletAddress: walletAddress || null,
createdAt: new Date().toISOString(),
};
db.addUser(user);
const token = await signToken({ userId: user.id, email: user.email });
const res = NextResponse.json({ success: true, user: { id: user.id, email: user.email } });
res.cookies.set('auth_token', token, { httpOnly: true, maxAge: 60 * 60 * 24 * 7, path: '/' });
return res;
} catch (err) {
return NextResponse.json({ error: 'Server error' }, { status: 500 });
}
}
EOF
# ── 13. API: Login ───────────────────────────────────────────
cat > src/app/api/auth/login/route.ts << 'EOF'
import { NextRequest, NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import { db } from '@/lib/db';
import { signToken } from '@/lib/auth';
export async function POST(req: NextRequest) {
try {
const { email, password } = await req.json();
const user = db.findUserByEmail(email);
if (!user) return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
const valid = await bcrypt.compare(password, user.passwordHash);
if (!valid) return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
const token = await signToken({ userId: user.id, email: user.email });
const res = NextResponse.json({ success: true, user: { id: user.id, email: user.email } });
res.cookies.set('auth_token', token, { httpOnly: true, maxAge: 60 * 60 * 24 * 7, path: '/' });
return res;
} catch {
return NextResponse.json({ error: 'Server error' }, { status: 500 });
}
}
EOF
# ── 14. API: Me ──────────────────────────────────────────────
cat > src/app/api/auth/me/route.ts << 'EOF'
import { NextResponse } from 'next/server';
import { getAuthUser } from '@/lib/auth';
import { db } from '@/lib/db';
export async function GET() {
const auth = await getAuthUser();
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
const user = db.findUserById(auth.userId);
if (!user) return NextResponse.json({ error: 'User not found' }, { status: 404 });
return NextResponse.json({ user: { id: user.id, email: user.email, walletAddress: user.walletAddress } });
}
EOF
# ── 15. API: Upload PDF ──────────────────────────────────────
cat > src/app/api/upload/route.ts << 'EOF'
import { NextRequest, NextResponse } from 'next/server';
import { getAuthUser } from '@/lib/auth';
import { uploadToIPFS } from '@/lib/ipfs';
export async function POST(req: NextRequest) {
try {
const auth = await getAuthUser();
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
const formData = await req.formData();
const file = formData.get('pdf') as File;
if (!file) return NextResponse.json({ error: 'No file provided' }, { status: 400 });
if (file.type !== 'application/pdf') return NextResponse.json({ error: 'File must be a PDF' }, { status: 400 });
const buffer = Buffer.from(await file.arrayBuffer());
const ipfsHash = await uploadToIPFS(buffer, file.name);
return NextResponse.json({ success: true, ipfsHash, fileName: file.name });
} catch (err: any) {
console.error(err);
return NextResponse.json({ error: 'Upload failed' }, { status: 500 });
}
}
EOF
# ── 16. API: Generate Questions ──────────────────────────────
cat > src/app/api/generate/route.ts << 'EOF'
import { NextRequest, NextResponse } from 'next/server';
import { getAuthUser } from '@/lib/auth';
import { generateQuestions } from '@/lib/claude';
import { db } from '@/lib/db';
export async function POST(req: NextRequest) {
try {
const auth = await getAuthUser();
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
const { pdfText, pdfName, ipfsHash } = await req.json();
if (!pdfText) return NextResponse.json({ error: 'PDF text required' }, { status: 400 });
const { questions } = await generateQuestions(pdfText, pdfName);
const session = {
id: crypto.randomUUID(),
userId: auth.userId,
pdfName,
ipfsHash,
questions,
createdAt: new Date().toISOString(),
};
db.addSession(session);
return NextResponse.json({ success: true, sessionId: session.id, questions });
} catch (err: any) {
console.error(err);
return NextResponse.json({ error: 'Generation failed' }, { status: 500 });
}
}
EOF
# ── 17. API: Summary ─────────────────────────────────────────
cat > src/app/api/summary/route.ts << 'EOF'
import { NextRequest, NextResponse } from 'next/server';
import { getAuthUser } from '@/lib/auth';
import { generateSummary } from '@/lib/claude';
import { db } from '@/lib/db';
export async function POST(req: NextRequest) {
try {
const auth = await getAuthUser();
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
const { pdfText, pdfName, ipfsHash } = await req.json();
if (!pdfText) return NextResponse.json({ error: 'PDF text required' }, { status: 400 });
const { bulletPoints, paragraph } = await generateSummary(pdfText, pdfName);
const summary = {
id: crypto.randomUUID(),
userId: auth.userId,
pdfName,
ipfsHash,
bulletPoints,
paragraph,
createdAt: new Date().toISOString(),
};
db.addSummary(summary);
return NextResponse.json({ success: true, summaryId: summary.id, bulletPoints, paragraph });
} catch (err: any) {
console.error(err);
return NextResponse.json({ error: 'Summary generation failed' }, { status: 500 });
}
}
EOF
# ── 18. API: Save Quiz Score ─────────────────────────────────
cat > src/app/api/quiz/save/route.ts << 'EOF'
import { NextRequest, NextResponse } from 'next/server';
import { getAuthUser } from '@/lib/auth';
import { db } from '@/lib/db';
export async function POST(req: NextRequest) {
try {
const auth = await getAuthUser();
if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
const { sessionId, score, onChainTx } = await req.json();
const sessions = db.getSessions();
const session = sessions.find((s: any) => s.id === sessionId && s.userId === auth.userId);
if (!session) return NextResponse.json({ error: 'Session not found' }, { status: 404 });
session.score = score;
session.completedAt = new Date().toISOString();
session.onChainTx = onChainTx || null;
// Write updated sessions back
const data = { users: db.getUsers(), sessions: sessions, summaries: db.getSummaries() };
const fs = require('fs');
const path = require('path');
fs.writeFileSync(path.join(process.cwd(), 'data', 'db.json'), JSON.stringify(data, null, 2));
return NextResponse.json({ success: true });
} catch (err) {
return NextResponse.json({ error: 'Failed to save score' }, { status: 500 });
}
}
EOF
# ── 19. Root Layout ──────────────────────────────────────────
cat > src/app/layout.tsx << 'EOF'
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import './globals.css';
import { Toaster } from 'react-hot-toast';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = {
title: 'ExamChain — AI Study Tool on Solana',
description: 'Upload your PDFs, get AI-generated exam questions, store your progress on the Solana blockchain.',
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body className={inter.className}>
{children}
<Toaster position="top-right" />
</body>
</html>
);
}
EOF
# ── 20. Global CSS ───────────────────────────────────────────
cat > src/app/globals.css << 'EOF'
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--green: #00FFA3;
--purple: #9945FF;
--blue: #00C2FF;
--bg: #060910;
--card: #0a0f1a;
--border: #1e2840;
}
body {
background: var(--bg);
color: #e2e8f0;
font-family: 'Inter', sans-serif;
}
.btn-primary {
@apply bg-[#00FFA3] text-black font-bold px-6 py-3 rounded-xl hover:bg-[#00e090] transition-all duration-200;
}
.btn-secondary {
@apply bg-[#0a0f1a] border border-[#1e2840] text-white font-semibold px-6 py-3 rounded-xl hover:border-[#00FFA3] transition-all duration-200;
}
.card {
@apply bg-[#0a0f1a] border border-[#1e2840] rounded-2xl p-6;
}
.input {
@apply bg-[#060910] border border-[#1e2840] text-white rounded-xl px-4 py-3 w-full focus:outline-none focus:border-[#00FFA3] transition-colors;
}
EOF
# ── 21. Landing Page ─────────────────────────────────────────
cat > src/app/page.tsx << 'EOF'
import Link from 'next/link';
export default function Home() {
return (
<main className="min-h-screen flex flex-col items-center justify-center px-6 text-center">
{/* Badge */}
<div className="mb-6 inline-flex items-center gap-2 bg-[#0a0f1a] border border-[#1e2840] rounded-full px-4 py-1.5 text-sm text-[#00FFA3]">
⛓️ Built on Solana
</div>
{/* Hero */}
<h1 className="text-5xl md:text-7xl font-black tracking-tight mb-6 leading-none">
Study Smarter.<br />
<span className="text-[#00FFA3]">On-Chain.</span>
</h1>
<p className="text-lg text-gray-400 max-w-xl mb-10">
Upload your lecture notes or textbook. Our AI generates real exam-style questions
from your content and stores your progress permanently on the Solana blockchain.
</p>
{/* CTA */}
<div className="flex flex-col sm:flex-row gap-4">
<Link href="/register" className="btn-primary text-lg">
Get Started Free →
</Link>
<Link href="/login" className="btn-secondary text-lg">
Sign In
</Link>
</div>
{/* Features */}
<div className="mt-24 grid grid-cols-1 md:grid-cols-3 gap-6 max-w-4xl w-full">
{[
{ icon: '🤖', title: 'AI Question Generation', desc: 'Claude AI infers exam-style questions directly from your PDF content — not random, but relevant.' },
{ icon: '📝', title: 'Smart Summaries', desc: 'Get bullet-point or paragraph summaries of any PDF in seconds. Study faster, retain more.' },
{ icon: '⛓️', title: 'On-Chain History', desc: 'Your quiz scores and sessions are stored immutably on Solana. Own your academic record.' },
].map((f) => (
<div key={f.title} className="card text-left">
<div className="text-3xl mb-3">{f.icon}</div>
<h3 className="font-bold text-white mb-2">{f.title}</h3>
<p className="text-gray-400 text-sm leading-relaxed">{f.desc}</p>
</div>
))}
</div>
</main>
);
}
EOF
# ── 22. Login Page ───────────────────────────────────────────
cat > "src/app/(auth)/login/page.tsx" << 'EOF'
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import toast from 'react-hot-toast';
import { useAuthStore } from '@/store/authStore';
export default function LoginPage() {
const router = useRouter();
const setUser = useAuthStore(s => s.setUser);
const [form, setForm] = useState({ email: '', password: '' });
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
try {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error);
setUser(data.user);
toast.success('Welcome back!');
router.push('/dashboard');
} catch (err: any) {
toast.error(err.message || 'Login failed');
} finally {
setLoading(false);
}
}
return (
<div className="min-h-screen flex items-center justify-center px-6">
<div className="card w-full max-w-md">
<div className="text-center mb-8">
<div className="text-3xl mb-2">⛓️</div>
<h1 className="text-2xl font-black">Sign In to ExamChain</h1>
<p className="text-gray-400 text-sm mt-1">Your AI study companion on Solana</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium mb-1 text-gray-300">Email</label>
<input
type="email"
className="input"
placeholder="you@university.edu"
value={form.email}
onChange={e => setForm({ ...form, email: e.target.value })}
required
/>
</div>
<div>
<label className="block text-sm font-medium mb-1 text-gray-300">Password</label>
<input
type="password"
className="input"
placeholder="••••••••"
value={form.password}
onChange={e => setForm({ ...form, password: e.target.value })}
required
/>
</div>
<button type="submit" disabled={loading} className="btn-primary w-full mt-2">
{loading ? 'Signing in...' : 'Sign In →'}
</button>
</form>
<p className="text-center text-gray-400 text-sm mt-6">
No account?{' '}
<Link href="/register" className="text-[#00FFA3] hover:underline">
Create one free
</Link>
</p>
</div>
</div>
);
}
EOF
# ── 23. Register Page ────────────────────────────────────────
cat > "src/app/(auth)/register/page.tsx" << 'EOF'
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import toast from 'react-hot-toast';
import { useAuthStore } from '@/store/authStore';
export default function RegisterPage() {
const router = useRouter();
const setUser = useAuthStore(s => s.setUser);
const [form, setForm] = useState({ email: '', password: '', confirm: '' });
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (form.password !== form.confirm) { toast.error('Passwords do not match'); return; }
setLoading(true);
try {
const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: form.email, password: form.password }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error);
setUser(data.user);
toast.success('Account created!');
router.push('/dashboard');
} catch (err: any) {
toast.error(err.message || 'Registration failed');
} finally {
setLoading(false);
}
}
return (
<div className="min-h-screen flex items-center justify-center px-6">
<div className="card w-full max-w-md">
<div className="text-center mb-8">
<div className="text-3xl mb-2">⛓️</div>
<h1 className="text-2xl font-black">Create Your Account</h1>
<p className="text-gray-400 text-sm mt-1">Start studying smarter today</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium mb-1 text-gray-300">Email</label>
<input type="email" className="input" placeholder="you@university.edu"
value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} required />
</div>
<div>
<label className="block text-sm font-medium mb-1 text-gray-300">Password</label>
<input type="password" className="input" placeholder="Min. 8 characters"
value={form.password} onChange={e => setForm({ ...form, password: e.target.value })} required />
</div>
<div>
<label className="block text-sm font-medium mb-1 text-gray-300">Confirm Password</label>
<input type="password" className="input" placeholder="••••••••"
value={form.confirm} onChange={e => setForm({ ...form, confirm: e.target.value })} required />
</div>
<button type="submit" disabled={loading} className="btn-primary w-full mt-2">
{loading ? 'Creating account...' : 'Create Account →'}
</button>
</form>
<p className="text-center text-gray-400 text-sm mt-6">
Already have an account?{' '}
<Link href="/login" className="text-[#00FFA3] hover:underline">Sign in</Link>
</p>
</div>
</div>
);
}
EOF
# ── 24. Dashboard Page ───────────────────────────────────────
cat > src/app/dashboard/page.tsx << 'EOF'
'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import toast from 'react-hot-toast';
export default function Dashboard() {
const router = useRouter();
const [user, setUser] = useState<any>(null);
useEffect(() => {
fetch('/api/auth/me').then(r => {
if (!r.ok) { router.push('/login'); return; }
return r.json();
}).then(d => d && setUser(d.user));
}, []);
async function logout() {
document.cookie = 'auth_token=; Max-Age=0; path=/';
router.push('/');
}
return (
<div className="min-h-screen px-6 py-12 max-w-4xl mx-auto">
{/* Header */}
<div className="flex items-center justify-between mb-12">
<div>
<div className="text-xs text-[#00FFA3] tracking-widest mb-1">⛓️ EXAMCHAIN</div>
<h1 className="text-3xl font-black">Dashboard</h1>
{user && <p className="text-gray-400 text-sm mt-1">Welcome back, {user.email}</p>}
</div>
<button onClick={logout} className="btn-secondary text-sm px-4 py-2">Sign Out</button>
</div>
{/* Quick Actions */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-12">
<Link href="/upload" className="card hover:border-[#00FFA3] transition-colors group cursor-pointer">
<div className="text-4xl mb-3">📄</div>
<h2 className="text-xl font-bold mb-1 group-hover:text-[#00FFA3] transition-colors">Upload PDF</h2>
<p className="text-gray-400 text-sm">Generate AI questions or summary from any PDF</p>
<div className="mt-4 text-[#00FFA3] text-sm font-semibold">Start studying →</div>
</Link>
<Link href="/history" className="card hover:border-[#9945FF] transition-colors group cursor-pointer">
<div className="text-4xl mb-3">⛓️</div>
<h2 className="text-xl font-bold mb-1 group-hover:text-[#9945FF] transition-colors">On-Chain History</h2>
<p className="text-gray-400 text-sm">View your quiz scores stored on Solana</p>
<div className="mt-4 text-[#9945FF] text-sm font-semibold">View history →</div>
</Link>
</div>
{/* Stats placeholder */}
<div className="card">
<h2 className="font-bold text-lg mb-4">Your Stats</h2>
<div className="grid grid-cols-3 gap-4 text-center">
{[['PDFs Uploaded', '—'], ['Quizzes Taken', '—'], ['Avg Score', '—%']].map(([label, val]) => (
<div key={label}>
<div className="text-2xl font-black text-[#00FFA3]">{val}</div>
<div className="text-xs text-gray-400 mt-1">{label}</div>
</div>
))}
</div>
</div>
</div>
);
}
EOF
# ── 25. Upload Page ──────────────────────────────────────────
cat > src/app/upload/page.tsx << 'EOF'
'use client';
import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { useDropzone } from 'react-dropzone';
import toast from 'react-hot-toast';
type Mode = 'quiz' | 'summary' | null;
export default function UploadPage() {
const router = useRouter();
const [file, setFile] = useState<File | null>(null);
const [mode, setMode] = useState<Mode>(null);
const [loading, setLoading] = useState(false);
const [step, setStep] = useState('');
const onDrop = useCallback((accepted: File[]) => {
if (accepted[0]) setFile(accepted[0]);
}, []);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop,
accept: { 'application/pdf': ['.pdf'] },
maxFiles: 1,
});
async function extractText(file: File): Promise<string> {
// Simple text extraction - in production use pdf-parse on server
return `PDF content from: ${file.name}`;
}
async function handleProcess() {
if (!file || !mode) return;
setLoading(true);
try {
// Step 1: Upload to IPFS
setStep('Uploading to IPFS...');
const formData = new FormData();
formData.append('pdf', file);
const uploadRes = await fetch('/api/upload', { method: 'POST', body: formData });
const { ipfsHash } = await uploadRes.json();
// Step 2: Extract text (client-side simple extraction)