{"slug": "how-we-automated-fraud-and-metric-inconsistency-detection-on-a-digital-asset-in", "title": "How we automated fraud and metric inconsistency detection on a digital asset marketplace in under 800ms using Next.js App Router and DeepSeek", "summary": "A developer at Lunil, a marketplace for buying and selling digital assets such as SaaS products, websites and domains, built a synchronous listing-moderation pipeline using Next.js App Router route handlers, the DeepSeek chat model in strict JSON mode, and Zod schemas to enforce typed outputs. The system runs deterministic sanitization first, then scores each submission for fraud and metric inconsistency, routing listings to instant publish, inline correction or a fraud block based on risk thresholds, with a target round-trip under 1.2 seconds.", "body_md": "`\n\nWhen building [Lunil](https://marketplace.lunil.com/en/signin)—a marketplace where founders buy and sell digital assets like SaaS products, websites, domains, and social channels—the hardest architectural problem wasn't escrow integration or database design.\n\nIt was **trust**.\n\nIn the digital asset space, fraud is rarely obvious spam like cheap pharma links. It's subtle:\n\nInitially, every listing had to wait in an admin review queue. For sellers, waiting hours or days killed momentum. For us, manual verification didn't scale.\n\nWe needed a **real-time moderation pipeline** that evaluates submissions during form completion, gives actionable feedback instantly, and stops deceptive listings before they hit our database.\n\nHere is how we designed and deployed this system using **Next.js App Router**, **DeepSeek**, and **Zod structured outputs**.\n\nMost platforms push moderation to background workers (`bullmq`, Celery, etc.). But if a seller makes an honest typo in their revenue metric or pastes a broken verification link, discovering it via email 6 hours later creates a terrible user experience.\n\nWe aimed for a **synchronous round-trip under 1.2 seconds**:\n\n`plaintext`\n\n[Seller Submits Listing]\n\n          │\n\n          ▼\n\n┌─────────────────────────┐\n\n│ Next.js Route Handler   │\n\n└──────────┬──────────────┘\n\n           │ 1. Deterministic Sanitization (Regex / Honeypot)\n\n           ▼\n\n┌─────────────────────────┐\n\n│ DeepSeek Structured API │ ◄── Inconsistency & Fraud Detection\n\n└──────────┬──────────────┘\n\n           │ 2. Typed JSON Response (Zod)\n\n           ▼\n\n     ┌───────────┐\n\n     │ Risk Tier │\n\n     └─────┬─────┘\n\n           ├─ Score < 0.25 ──► Instant Publish\n\n           ├─ Score 0.25-0.70 ► Form Warning & Inline Correction\n\n           └─ Score > 0.70 ──► Blocked / Fraud Flag\n\nWe use **Zod** to guarantee strict type safety between the LLM output and our Next.js backend. The model is forced to return a JSON object adhering to this schema:\n\n`` `typescript ``\n\n// lib/moderation/schema.ts\n\nimport { z } from \"zod\";\n\nexport const ModerationResultSchema = z.object({\n\n  status: z.enum([\"APPROVED\", \"NEEDS_REVISION\", \"REJECTED\"]),\n\n  riskScore: z.number().min(0).max(1), // 0 = legit, 1 = malicious\n\n  issues: z.array(\n\n    z.object({\n\n      field: z.enum([\"title\", \"description\", \"financials\", \"urls\", \"general\"]),\n\n      severity: z.enum([\"low\", \"medium\", \"critical\"]),\n\n      message: z.string(),\n\n      suggestion: z.string().optional(),\n\n    })\n\n  ),\n\n  metricConsistency: z.object({\n\n    revenueVsTrafficPlausible: z.boolean(),\n\n    valuationMultipleReasonable: z.boolean(),\n\n    notes: z.string().optional(),\n\n  }),\n\n});\n\nexport type ModerationResult = z.infer;\n\n`\n\nHere is the core verification logic running inside a Next.js App Router API route (`app/api/listings/verify/route.ts`).\n\nWe use **DeepSeek** (`deepseek-chat`) with strict JSON output mode. DeepSeek offers exceptional reasoning on structured tabular data and financial metrics at a fraction of the cost of legacy models.\n\n`` `typescript ``\n\n// app/api/listings/verify/route.ts\n\nimport { NextResponse } from \"next/server\";\n\nimport { ModerationResultSchema } from \"@/lib/moderation/schema\";\n\nconst SYSTEM_PROMPT = `\n\nYou are a senior due diligence auditor for Lunil, a marketplace for buying and selling digital businesses (SaaS, content sites, domains).\n\nYour task is to analyze listing data for fraud, inflated metrics, and policy violations.\n\nEvaluate:\n\nAlways return valid JSON matching the exact schema requested. Be objective, strict on fraud, but forgiving of normal startup variances.\n\n`;\n\nexport async function POST(req: Request) {\n\n  try {\n\n    const listingData = await req.json();\n\n```\n// 1. Quick deterministic heuristic checks\nif (!listingData.title || !listingData.description) {\n  return NextResponse.json({ error: \"Missing required fields\" }, { status: 400 });\n}\n\n// 2. Query DeepSeek\nconst response = await fetch(\"https://api.deepseek.com/chat/completions\", {\n  method: \"POST\",\n  headers: {\n    \"Content-Type\": \"application/json\",\n    Authorization: `Bearer ${process.env.DEEPSEEK_API_KEY}`,\n  },\n  body: JSON.stringify({\n    model: \"deepseek-chat\",\n    response_format: { type: \"json_object\" },\n    messages: [\n      { role: \"system\", content: SYSTEM_PROMPT },\n      {\n        role: \"user\",\n        content: `Analyze this listing submission:\n```\n\nTitle: ${listingData.title}\n\nAsset Type: ${listingData.type}\n\nAsking Price: $${listingData.askingPrice}\n\nMonthly Revenue: $${listingData.monthlyRevenue}\n\nMonthly Profit: $${listingData.monthlyProfit}\n\nMonthly Pageviews: ${listingData.pageviews}\n\nDescription:\n\n${listingData.description}\n\nURL / Proof: ${listingData.proofUrl || \"None provided\"}`,\n\n          },\n\n        ],\n\n        temperature: 0.1, // Near-deterministic for evaluation\n\n      }),\n\n    });\n\n```\nif (!response.ok) {\n  throw new Error(`DeepSeek API error: ${response.statusText}`);\n}\n\nconst rawData = await response.json();\nconst parsedContent = JSON.parse(rawData.choices[0].message.content);\n\n// 3. Validate response structure with Zod\nconst validationResult = ModerationResultSchema.safeParse(parsedContent);\n\nif (!validationResult.success) {\n  console.error(\"Schema mismatch:\", validationResult.error);\n  // Fallback: send to manual review queue if AI output is malformed\n  return NextResponse.json({ status: \"MANUAL_REVIEW\" });\n}\n\nreturn NextResponse.json(validationResult.data);\n```\n\n} catch (error) {\n\n    console.error(\"Listing verification failed:\", error);\n\n    return NextResponse.json({ error: \"Verification unavailable\" }, { status: 500 });\n\n  }\n\n}\n\n`\n\nRunning this in production on [Lunil](https://lunil.com) highlighted some subtle nuances:\n\n`Starter Project` vs `Established Cash-Flowing SaaS`) into the system prompt.` field: \"financials\"`), the client UI immediately highlights the exact input in red with the AI’s explanation (e.g., While DeepSeek handles deep reasoning well in ~800ms, our long-term goal is to make listing moderation feel as instantaneous as form validation (`< 150ms`).\n\nGenerative LLMs are fundamentally **System 2** thinkers: they predict tokens sequentially, consuming unnecessary computational overhead when all we truly need is a deterministic categorical status and risk score.\n\nThrough December, we are benchmarking **Jev**, a high-speed \"System 1\" model developed by **TypeSafe AI**. \n\nBecause System 1 architectures focus on fast, direct pattern recognition without multi-step autoregressive generation:\n\nIf the benchmark proves that Jev matches DeepSeek’s accuracy on financial anomaly detection, our production pipeline will evolve into a two-tier engine:\n\nAutomating trust on a digital asset marketplace doesn't require multi-million dollar ML budgets. A disciplined setup using **Next.js App Router**, **Zod**, and **DeepSeek** allows a lean team to deliver real-time fraud protection that protects buyers while keeping the seller onboarding frictionless.\n\nIf you are building marketplaces or UGC platforms, how are you handling metric validation and fraud detection? Are you sticking to deterministic queues, or moving toward hybrid real-time architectures?\n\n*Built with Next.js, DeepSeek, and deployed on [Lunil](https://lunil.com).*", "url": "https://wpnews.pro/news/how-we-automated-fraud-and-metric-inconsistency-detection-on-a-digital-asset-in", "canonical_source": "https://dev.to/johnfelicita/how-we-automated-fraud-and-metric-inconsistency-detection-on-a-digital-asset-marketplace-in-under-4ifn", "published_at": "2026-11-04 16:10:59+00:00", "updated_at": "2026-11-04 16:24:01.603746+00:00", "lang": "en", "topics": ["artificial-intelligence", "ai-agents", "ai-tools", "developer-tools", "large-language-models"], "entities": ["Lunil", "DeepSeek", "Next.js", "Zod", "Vercel"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/how-we-automated-fraud-and-metric-inconsistency-detection-on-a-digital-asset-in", "markdown": "https://wpnews.pro/news/how-we-automated-fraud-and-metric-inconsistency-detection-on-a-digital-asset-in.md", "text": "https://wpnews.pro/news/how-we-automated-fraud-and-metric-inconsistency-detection-on-a-digital-asset-in.txt", "jsonld": "https://wpnews.pro/news/how-we-automated-fraud-and-metric-inconsistency-detection-on-a-digital-asset-in.jsonld"}}