diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..caf0a8d
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,14 @@
+node_modules
+.next
+.git
+.gitignore
+Dockerfile
+npm-debug.log
+yarn-error.log
+pnpm-debug.log
+.env
+.env.*
+blockchain/artifacts
+blockchain/cache
+blockchain/typechain-types
+blockchain/node_modules
diff --git a/.nvmrc b/.nvmrc
new file mode 100644
index 0000000..209e3ef
--- /dev/null
+++ b/.nvmrc
@@ -0,0 +1 @@
+20
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..fc92771
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,29 @@
+# syntax=docker/dockerfile:1.7
+
+FROM node:20-alpine AS base
+WORKDIR /app
+ENV NEXT_TELEMETRY_DISABLED=1
+
+FROM base AS deps
+RUN apk add --no-cache libc6-compat
+COPY package.json package-lock.json* ./
+RUN npm ci
+
+FROM base AS builder
+RUN apk add --no-cache libc6-compat
+COPY --from=deps /app/node_modules ./node_modules
+COPY . .
+RUN npx prisma generate
+RUN npm run build
+
+FROM base AS runner
+RUN apk add --no-cache libc6-compat
+ENV NODE_ENV=production
+ENV PORT=3000
+
+COPY --from=builder /app/public ./public
+COPY --from=builder /app/.next/standalone ./
+COPY --from=builder /app/.next/static ./.next/static
+
+EXPOSE 3000
+CMD ["node", "server.js"]
diff --git a/README.md b/README.md
index 23f4465..9038403 100644
--- a/README.md
+++ b/README.md
@@ -1,110 +1,215 @@
-# π LexiChain: Professional BFSI Document Intelligence Platform
+# LexiChain
-> **Status**: Production-Ready PFE Project
-> **Target Audience**: Banking, Financial Services, and Insurance (BFSI) Institutions
-> **Key Innovation**: Hybrid integration of Generative AI (Gemini) and Ethereum Blockchain (DocumentRegistry)
+
+
+
----
+
+ BFSI document intelligence platform that combines AI-assisted analysis with blockchain-backed verification.
+
-## ποΈ 1. Project Vision & Mission
+
+
+
+
+
+
+
-**LexiChain** is a next-generation platform designed to bridge the gap between complex legal documentation and user-centric transparency. In the traditional BFSI sector, contracts are often "black boxes"βstatic PDFs that are hard to understand and easy to misplace.
+LexiChain is a team-ready platform for uploading documents, extracting important information, verifying integrity, and tracking records through a polished enterprise interface. It combines a modern Next.js frontend, a Solidity/Hardhat blockchain module, PostgreSQL with Prisma, and Clerk authentication.
-LexiChain transforms these static documents into **dynamic, searchable, and cryptographically secured assets**. Our mission is to automate document analysis while providing an immutable "Digital Notary" service that guarantees trust between financial institutions and their clients.
+## Overview
----
+LexiChain is designed for banking, financial services, and insurance workflows where documents must be understandable, traceable, and trustworthy.
-## π 2. Market Problem & Opportunity
+It addresses four core needs:
-The project addresses several critical "pain points" in the current financial landscape:
+- converting dense documents into structured, reviewable insights
+- reducing repetitive validation and manual review work
+- preserving tamper-evident proof for uploaded files
+- giving end users a clearer and more professional contract experience
-1. **The Transparency Gap**: Clients often sign contracts without understanding specific exclusion clauses or renewal dates.
-2. **Operational Friction**: Insurance agents spend thousands of hours manually checking PDFs for compliance and signature presence.
-3. **The Integrity Risk**: In legal disputes, proving that a specific version of a document was the one actually signed can be difficult and expensive.
-4. **Information Overload**: Users are overwhelmed by the volume of fine print in modern banking.
+## Product Highlights
----
+- AI document analysis powered by Gemini
+- OCR-based ingestion for digital and scanned documents
+- automated extraction of key contract details
+- chat-style retrieval over document content
+- blockchain proof-of-existence for uploaded files
+- document verification against on-chain hashes
+- secure authentication and per-user access control
+- dashboard views for contracts, contacts, and claims workflows
+- responsive UI with a dark, premium visual style
-## π 3. Core Feature Deep-Dive
+## Visual Preview
-### π§ A. The AI "Analyst" Module (Intelligence Layer)
+The screenshots in [public/screens](public/screens) are intentionally included to make the README feel like a product page and to help new contributors understand the interface quickly.
-LexiChain uses **Google Gemini 2.0 Flash** to act as a virtual legal analyst.
+| Landing page | Dashboard |
+| ------------------------------------------------ | ----------------------------------------------- |
+|  |  |
-- **Smart Ingestion**: Uses high-fidelity OCR to read digital PDFs and scanned images.
-- **Automated Extraction**: Identifies 15+ key data points (Amount, Interest Rate, Parties, Expiration Dates, Clauses) instantly.
-- **RAG (Retrieval-Augmented Generation)**: The most advanced part of the AI. It breaks the contract into "Semantic Chunks" and stores them in a vector index. This allows the user to **Chat with their Contract** in natural language.
-- **Intelligent Validation**: The AI automatically flags missing signatures, inconsistent dates, or high-risk clauses before the document is finalized.
+| Login | Register |
+| ---------------------------------------------- | ---------------------------------------------------- |
+|  |  |
-### βοΈ B. The Blockchain "Notary" Module (Security Layer)
+| Contracts |
+| ---------------------------------------------------- |
+|  |
-LexiChain uses a private/public hybrid blockchain strategy to ensure **Non-Repudiation**.
+## Architecture
-- **Proof of Existence (PoE)**: We generate a SHA-256 hash (digital fingerprint) for every file. This hash is sent to a **Solidity Smart Contract** on the Ethereum network.
-- **Immutable Timestamping**: The blockchain records exactly _when_ the document was uploaded. This cannot be changed by any administrator, providing a "Golden Record."
-- **Metadata Leakage Prevention**: We only store the **Hash** on-chain. No personal data (names, amounts) ever touches the public blockchain, ensuring 100% GDPR compliance.
-- **The Explorer**: A built-in "Verification Panel" that allows any auditor to verify a file's integrity by comparing its current hash with the on-chain record.
+LexiChain follows a practical feature-oriented structure:
----
+- [app](app) contains the Next.js app router, layouts, and pages
+- [components](components) contains shared UI and layout building blocks
+- [features](features) contains feature-level business logic
+- [hooks](hooks) contains reusable client hooks
+- [lib](lib) contains shared utilities and helpers
+- [prisma](prisma) contains database schema files
+- [blockchain](blockchain) contains the Hardhat project and smart contracts
+- [public/screens](public/screens) contains screenshots and visual assets
-## ποΈ 4. Technical Architecture
+The solution is split across three main concerns:
-### **Architecture Pattern: Feature-Sliced Design (FSD)**
+| Layer | Purpose |
+| ---------- | ----------------------------------------------------- |
+| Frontend | UI, dashboards, forms, and user interactions |
+| Backend | Server actions and API routes for business workflows |
+| Blockchain | Smart contract registration and document verification |
-The project follows **FSD principles**, which is a modern architectural pattern for scaling large applications.
+## Tech Stack
-- **Layers**: App, Pages, Features, Entities, Shared.
-- **Benefits**: Decouples the Blockchain logic from the AI logic, making the system highly maintainable and ready for enterprise scaling.
+| Area | Stack |
+| -------------- | ------------------------------------ |
+| Frontend | Next.js 16, React 19, Tailwind CSS |
+| Backend | Next.js server actions, API routes |
+| AI | Google Gemini |
+| Blockchain | Solidity, Hardhat, Ethers.js |
+| Database | PostgreSQL, Prisma |
+| Authentication | Clerk |
+| UI Components | Radix UI, shadcn/ui-style primitives |
-### **The Stack**
+## Prerequisites
-| Layer | Technology | Rationale |
-| :------------- | :----------------------- | :-------------------------------------------------------------------------------------------------- |
-| **Frontend** | Next.js 15 (React) | High performance, SEO-friendly, and supports React Server Components. |
-| **Backend** | Server Actions (Next.js) | Allows for secure, server-side blockchain signing and API communication without a separate backend.
-| **LLM** | Gemini | Unbeatable speed and context window size for long legal documents. |
-| **Blockchain** | Solidity / Hardhat | Ethereum-compatible smart contracts for industry-standard security. |
-| **Database** | PostgreSQL + Prisma | Robust relational storage for user data and contract metadata. |
-| **Identity** | Clerk | Enterprise-grade security for user authentication and session management. |
+- Node.js 20 or later
+- npm
+- PostgreSQL database
+- a local or remote blockchain endpoint for development and deployment
+- environment variables for Clerk, Gemini, database, and blockchain access
----
+## Environment Variables
-## π 5. Security & Privacy Philosophy
+The exact values depend on your deployment target, but the project expects environment configuration for the following areas:
-LexiChain is built with a **"Security by Design"** approach:
+| Area | Typical Variables |
+| -------------- | ---------------------------------------------- |
+| App | `NODE_ENV`, app URL settings |
+| Database | `DATABASE_URL` |
+| Authentication | Clerk publishable and secret keys |
+| AI | Gemini API key or equivalent model credentials |
+| Blockchain | RPC URL, contract address, private key |
-- **Hashing vs. Storage**: We never store the actual document on the blockchain. The blockchain only holds the "Proof," while the "Content" remains in encrypted cloud storage.
-- **Server-Side Signing**: Users don't need a crypto wallet (MetaMask). Our backend acts as a **Trusted Custodian**, signing transactions with a secure private key hidden in environment variables.
-- **Authentication Hooks**: Access to contracts is strictly controlled via Clerk Auth, ensuring users only see their own data.
+Keep secrets in environment variables and never commit them to the repository.
----
+## Installation
-## π¨ 6. UX/UI & Aesthetics
+Install the root application dependencies first:
-The application features a **"Premium Glassmorphism"** design system.
+```bash
+npm install
+```
-- **Why?**: In BFSI, the interface must convey **Trust, Modernity, and Clarity**.
-- **Design Tokens**: We use vibrant gradients, subtle blurs, and micro-animations to make the complex task of contract management feel light and intuitive.
-- **Theme Awareness**: The UI is optimized for both Light and Dark modes, adapting to the professional environment of the user.
+Then install the blockchain workspace dependencies:
----
+```bash
+cd blockchain
+npm install
+```
-## π 7. Why this is a 10/10 PFE Project
+## Local Development
-LexiChain isn't just a simple web app; it is a **Multidisciplinary Innovation**:
+The recommended development command starts the app together with the local chain workflow:
-1. **AI Innovation**: Moving beyond simple text extraction to a conversational RAG system.
-2. **Blockchain Innovation**: Implementing a production-ready Document Registry that solves real-world legal issues.
-3. **Architectural Integrity**: Using FSD and Clean Code principles usually found in senior-level software engineering.
-4. **Market Readiness**: The solution is directly applicable to banks and insurance companies looking to digitalize their workflow.
+```bash
+npm run dev
+```
----
+This runs the bootstrap script defined in the root package and is the best option when you want the frontend and blockchain pieces aligned locally.
-## π 8. Glossary for NotebookLM
+If you only need the Next.js app without the chain bootstrap, run:
-- **BFSI**: Banking, Financial Services, and Insurance.
-- **RAG (Retrieval-Augmented Generation)**: A technique that allows AI to answer questions based _only_ on the provided documents, preventing "hallucinations."
-- **Smart Contract**: A programmable contract that executes automatically when conditions are met.
-- **SHA-256**: A one-way cryptographic function. If you change 1 bit of a file, the entire hash changes.
-- **Hardhat**: A professional development environment for Ethereum software.
-- **Sepolia**: The public test network used to simulate the real Ethereum blockchain.
+```bash
+npm run dev:next
+```
+
+## Scripts
+
+### Root workspace
+
+| Command | Description |
+| ------------------------ | ------------------------------------------- |
+| `npm run dev` | Starts the combined development workflow |
+| `npm run dev:with-chain` | Alias for the combined development workflow |
+| `npm run dev:next` | Runs only the Next.js dev server |
+| `npm run build` | Builds the production application |
+| `npm run start` | Starts the production server |
+| `npm run lint` | Runs ESLint |
+
+### Blockchain workspace
+
+| Command | Description |
+| ------------------------ | ------------------------------------ |
+| `npm run compile` | Compiles the smart contracts |
+| `npm run test` | Runs the Hardhat test suite |
+| `npm run node` | Starts a local Hardhat node |
+| `npm run deploy:local` | Deploys to the local Hardhat network |
+| `npm run deploy:sepolia` | Deploys to Sepolia |
+
+## Deployment
+
+This is the clean production path for option 3 in the README.
+
+```bash
+npm run build
+npm run start
+```
+
+Before deploying, verify:
+
+- environment variables are set correctly
+- the database is reachable
+- the blockchain contract address and RPC settings are valid
+- the code passes linting and any required tests
+
+## Team Notes
+
+These are the implementation details future contributors should know before extending the app:
+
+- Contract records store the internal application user id, not the Clerk user id; resolve the Clerk user first before querying contract data.
+- The upload flow triggers analysis automatically after saving a contract, so the UI should show analysis-in-progress feedback immediately.
+- Dashboard and contacts routes live under `/dashboard` and `/contacts`.
+- Trend charts should be aggregated by day with zero-filled windows so 30-day views stay accurate.
+- Q&A over contracts uses Gemini embeddings and an in-memory contract vector cache.
+- Claim status updates are intentionally restricted; the UI should use the allowed next statuses for each claim instead of a global list.
+
+## Contribution Guidelines
+
+If you are continuing this project as a team, keep the following practices in mind:
+
+- make focused changes and avoid mixing unrelated refactors with feature work
+- keep environment-dependent values out of source control
+- prefer the existing feature structure when adding new UI or business logic
+- update screenshots when user-facing screens change significantly
+- document workflow changes in the README or the relevant docs file
+
+## Troubleshooting
+
+- If the app does not start, verify your Node.js version and reinstall dependencies.
+- If blockchain features fail, confirm the local node is running and the contract address points to a deployed contract.
+- If authentication fails, recheck the Clerk environment variables and callback configuration.
+- If database access fails, validate the Prisma connection string and database availability.
+
+## Summary
+
+LexiChain is a BFSI document intelligence platform built for contract review, verification, and operational clarity. The codebase is structured to be maintainable by a team, with a clear split between app, blockchain, data, and shared UI concerns.
diff --git a/app/(dashboard)/blockchain/page.tsx b/app/(dashboard)/blockchain/page.tsx
index fe64db3..adc450e 100644
--- a/app/(dashboard)/blockchain/page.tsx
+++ b/app/(dashboard)/blockchain/page.tsx
@@ -1,7 +1,7 @@
"use client";
import React, { useEffect, useState, useCallback } from "react";
-import { motion } from "motion/react";
+import { motion, AnimatePresence } from "motion/react";
import {
Link2,
Shield,
@@ -18,6 +18,13 @@ import {
Check,
AlertCircle,
Upload,
+ Zap,
+ Fingerprint,
+ Radio,
+ ChevronRight,
+ Terminal,
+ Lock,
+ Globe,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
@@ -25,6 +32,7 @@ import {
getBlockchainStats,
verifyDocumentHashOnBlockchain,
registerContractOnBlockchain,
+ generateContractCertificate,
} from "@/features/blockchain/api/blockchain.action";
import { getContracts } from "@/features/contracts/api/contract.action";
import type {
@@ -34,11 +42,13 @@ import type {
import { toast } from "sonner";
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-// Blockchain Explorer Page
+// Blockchain Explorer β 2026 Edition
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export default function BlockchainExplorerPage() {
- const [transactions, setTransactions] = useState([]);
+ const [transactions, setTransactions] = useState(
+ [],
+ );
const [stats, setStats] = useState(null);
const [loading, setLoading] = useState(true);
const [verifyHash, setVerifyHash] = useState("");
@@ -53,6 +63,12 @@ export default function BlockchainExplorerPage() {
Array<{ id: string; title: string | null; fileName: string }>
>([]);
const [registeringId, setRegisteringId] = useState(null);
+ const [downloadingCertificateId, setDownloadingCertificateId] = useState<
+ string | null
+ >(null);
+ const [activeTab, setActiveTab] = useState<"all" | "verified" | "pending">(
+ "all",
+ );
const loadData = useCallback(async () => {
setLoading(true);
@@ -70,15 +86,14 @@ export default function BlockchainExplorerPage() {
setStats(statsResult.stats);
}
- // Find contracts not yet on blockchain
if (contractsResult.success && contractsResult.contracts) {
const registered = new Set(
- txResult.transactions?.map((tx) => tx.contractId) ?? []
+ txResult.transactions?.map((tx) => tx.contractId) ?? [],
);
const unregistered = contractsResult.contracts
.filter(
(c: { id: string; txHash?: string | null; status: string }) =>
- !c.txHash && !registered.has(c.id) && c.status === "COMPLETED"
+ !c.txHash && !registered.has(c.id) && c.status === "COMPLETED",
)
.map((c: { id: string; title: string | null; fileName: string }) => ({
id: c.id,
@@ -133,6 +148,42 @@ export default function BlockchainExplorerPage() {
}
};
+ const handleDownloadCertificate = async (
+ contractId: string,
+ contractTitle: string,
+ ) => {
+ setDownloadingCertificateId(contractId);
+ try {
+ const result = await generateContractCertificate(contractId);
+ if (result.success && result.certificatePdfBase64) {
+ const base64 = result.certificatePdfBase64;
+ const binary = atob(base64);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i += 1) {
+ bytes[i] = binary.charCodeAt(i);
+ }
+ const blob = new Blob([bytes], { type: "application/pdf" });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download =
+ result.certificateFileName ||
+ `certificate-${contractTitle || contractId}.pdf`;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+ toast.success("Certificate downloaded successfully!");
+ } else {
+ toast.error(result.error || "Failed to generate certificate");
+ }
+ } catch {
+ toast.error("Failed to download certificate");
+ } finally {
+ setDownloadingCertificateId(null);
+ }
+ };
+
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
setCopiedTx(text);
@@ -148,385 +199,630 @@ export default function BlockchainExplorerPage() {
return `${hash.slice(0, chars + 2)}...${hash.slice(-chars)}`;
};
+ const filteredTransactions = transactions.filter((tx) => {
+ if (activeTab === "verified")
+ return tx.status === "CONFIRMED" || tx.status === "SUCCESS";
+ if (activeTab === "pending")
+ return tx.status === "PENDING" || tx.status === "PROCESSING";
+ return true;
+ });
+
return (
-
- {/* Page Header */}
-
-
-
-
-
-
- Blockchain Explorer
-
-
- View on-chain proofs and verify document integrity
-