Fair prices for farmers. Transparency for consumers. Blockchain without cryptocurrency.
Built for BGSCET Hackathon 2025
Cybersecurity + Blockchain = Self-hosted agricultural marketplace with immutable transaction records
- Farmer Portal (
/farmer) - List crops, view offers, track payments, blockchain receipts - Buyer Marketplace (
/buyer) - Browse crops, make offers, view AI quality grades - Consumer QR Trace (
/consumer) - Scan product QR code to verify full supply chain - Admin Dashboard (
/admin) - Real-time transaction monitoring, fraud alerts, blockchain explorer - USSD Dual-Phone Simulator (
/ussd-simulation) - Real-time P2P USSD transactions with dual virtual phones π± - Smart Contracts - CropMarketplace.sol + PriceOracle.sol with immutable records
- Payment System - UPI/NEFT bank transfer tracking (no cryptocurrency)
- Blockchain Records - Ganache local blockchain for immutable audit trail
- AI Fraud Detection - Machine learning-based fraud scoring + smart contract validation
- Voice/USSD API - Express.js backend for voice alerts & market price queries
- AI Service - Python-based quality grading & advanced fraud detection
- Production Ready - Nginx reverse proxy, PM2 process manager, PostgreSQL database
POST /api/auth/signup- NEW: User registration with mandatory database storagePOST /api/auth/login- User authentication (requires prior sign-up) & session managementGET /api/crops/list- Fetch all available crops with quality gradesPOST /api/offers/create- Create new purchase offers (validated by smart contract)POST /api/payments/commit- Record bank transfer & payment commitmentsPOST /api/fraud/detect- Analyze offers for fraud using AI + rulesGET /api/blockchain/transaction- Retrieve blockchain transaction details & proofs- USSD Endpoints (see USSD_GUIDE.md):
- Next.js 15 - React framework with SSR/SSG
- React 19 (RC) - UI components
- TypeScript - Type-safe development
- Tailwind CSS - Utility-first styling
- ethers.js v6 - Ethereum blockchain interaction
- html5-qrcode - QR code scanning
- qrcode.react - QR code generation
- React Leaflet - Interactive maps
- Recharts - Data visualization
- Node.js + Express.js - Voice/USSD API (port 4000)
- Socket.IO - Real-time WebSocket server for USSD events
- Python Flask/FastAPI - AI service (port 5000) for quality grading & fraud detection
- Solidity 0.8.20 - Smart contracts
- Hardhat - Ethereum development framework
- Ganache - Local blockchain for development/testing
- TypeChain - TypeScript bindings for contracts
- PostgreSQL 14+ - Production database
- Supabase - Database migrations (5 schemas)
- Nginx - Reverse proxy (production)
- PM2 - Process manager (production)
- Ubuntu Server 20.04+ - Deployment target
- GitHub - Version control
- Node.js 18+
- npm / yarn
- Ganache CLI (for blockchain local node)
- PostgreSQL 14+ (optional, for testing database migrations)
- Python 3.8+ (for AI service backend)
Step 1: Clone & Install Dependencies
git clone https://github.com/ADEEP13/win_hack.git
cd win_hack
npm install --legacy-peer-depsStep 2: Create Environment File
# Create .env.local in the root directory
cat > .env.local << 'EOF'
# Blockchain Configuration
NEXT_PUBLIC_GANACHE_RPC_URL=http://127.0.0.1:8545
GANACHE_PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb476c6b8d6c1f02960247590f589
NEXT_PUBLIC_CROP_MARKETPLACE_ADDRESS=0x0000000000000000000000000000000000000000
NEXT_PUBLIC_PRICE_ORACLE_ADDRESS=0x0000000000000000000000000000000000000000
# Server Configuration
NODE_ENV=development
NEXT_PUBLIC_SERVER_IP=localhost
SERVER_PORT=3000
# Optional: Database (comment out if not using PostgreSQL locally)
# DATABASE_URL=postgresql://localhost:5432/jandhan_plus
EOFStep 3: Start Ganache Blockchain (Terminal 1)
npm install -g ganache
ganache --database.dbPath ./blockchain-data --server.port 8545Step 4: Compile & Deploy Smart Contracts (Terminal 2)
npm run contracts:compile
npm run contracts:deployNote: Copy the deployed contract addresses from the output and update .env.local:
NEXT_PUBLIC_CROP_MARKETPLACE_ADDRESS=0x<from_deploy_output>
NEXT_PUBLIC_PRICE_ORACLE_ADDRESS=0x<from_deploy_output>
Step 5: Start Backend Services (Terminal 3)
# Optional: Voice/USSD API (Express.js - port 4000)
node backend/voice-api.jsStep 6: Start AI Service (Terminal 4 - Optional)
# AI quality grading & fraud detection (Python - port 5000)
# Requirements: Python 3.8+
python backend/ai-service.pyStep 7: Start Next.js Development Server (Terminal 5)
npm run devAccess the Application
- Landing Page: http://localhost:3000
- Farmer Portal: http://localhost:3000/farmer
- Buyer Marketplace: http://localhost:3000/buyer
- Consumer QR Trace: http://localhost:3000/consumer
- Admin Dashboard: http://localhost:3000/admin
- Ubuntu 20.04+ server
- SSH access & sudo privileges
- Minimum 2GB RAM, 20GB disk space
- Public IP address or domain name
If you already have an older version running, use the automated update script:
ssh user@your-server-ip
cd ~/jandhan-plus
bash UPDATE_SERVER.shThis script will:
- β Back up your current version
- β Pull latest code from GitHub
- β Install new dependencies (Socket.IO)
- β Compile smart contracts
- β Create USSD database tables
- β Build for production
- β Restart all services
- β Verify everything works
For detailed guides:
- QUICK_UPDATE.md - Quick copy-paste commands
- UPDATE_SERVER.md - Full step-by-step guide
Step 1: SSH into Server
ssh user@your-server-ipStep 2: Run Automated Setup Script
# Download and run the setup script
bash <(curl -fsSL https://raw.githubusercontent.com/ADEEP13/win_hack/main/setup.sh)Step 3: Manual Setup (if needed)
# Install Node.js, PostgreSQL, Nginx, PM2
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt update && sudo apt upgrade -y
sudo apt install -y nodejs postgresql postgresql-contrib nginx git
# Install global tools
npm install -g ganache pm2
# Create PostgreSQL database & user
sudo -u postgres psql << EOF
CREATE USER jandhan_user WITH PASSWORD 'your_secure_password';
CREATE DATABASE jandhan_plus OWNER jandhan_user;
EOFStep 4: Clone Repository & Install
cd ~
git clone https://github.com/ADEEP13/win_hack.git jandhan-plus
cd jandhan-plus
npm install --legacy-peer-depsStep 5: Configure Environment
cat > .env.local << 'EOF'
NEXT_PUBLIC_GANACHE_RPC_URL=http://127.0.0.1:8545
GANACHE_PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb476c6b8d6c1f02960247590f589
NEXT_PUBLIC_CROP_MARKETPLACE_ADDRESS=0x0000000000000000000000000000000000000000
NEXT_PUBLIC_PRICE_ORACLE_ADDRESS=0x0000000000000000000000000000000000000000
DATABASE_URL=postgresql://jandhan_user:your_secure_password@localhost:5432/jandhan_plus
NODE_ENV=production
NEXT_PUBLIC_SERVER_IP=your-server-ip
SERVER_PORT=3000
EOFStep 6: Run Database Migrations
cd ~/jandhan-plus
psql -U jandhan_user -d jandhan_plus -h localhost -f supabase/migrations/001_create_users.sql
psql -U jandhan_user -d jandhan_plus -h localhost -f supabase/migrations/002_create_crops.sql
psql -U jandhan_user -d jandhan_plus -h localhost -f supabase/migrations/003_create_offers.sql
psql -U jandhan_user -d jandhan_plus -h localhost -f supabase/migrations/004_create_payments.sql
psql -U jandhan_user -d jandhan_plus -h localhost -f supabase/migrations/005_create_transactions.sqlStep 7: Compile & Deploy Smart Contracts
npm run contracts:compile
npm run contracts:deploy
# Copy deployed contract addresses and update .env.localStep 8: Build Next.js Application
npm run buildStep 9: Start All Services with PM2
# Start Ganache blockchain
pm2 start "ganache --database.dbPath ~/jandhan-plus/blockchain-data" --name "ganache"
# Start Next.js production server
pm2 start npm --name "jandhan-next" -- start
# Start Voice API (Express.js)
pm2 start ~/jandhan-plus/backend/voice-api.js --name "jandhan-voice"
# Start AI Service (Python)
pm2 start ~/jandhan-plus/backend/ai-service.py --name "jandhan-ai" --interpreter python3
# Save PM2 configuration and startup
pm2 save
pm2 startupStep 10: Configure Nginx Reverse Proxy
# Copy Nginx configuration
sudo cp ~/jandhan-plus/server-setup/nginx.conf /etc/nginx/sites-available/jandhan-plus
# Enable the site
sudo ln -sf /etc/nginx/sites-available/jandhan-plus /etc/nginx/sites-enabled/jandhan-plus
# Remove default site
sudo rm -f /etc/nginx/sites-enabled/default
# Test Nginx configuration
sudo nginx -t
# Reload Nginx
sudo systemctl reload nginxStep 11: Configure Firewall
sudo ufw enable
sudo ufw allow 22/tcp # SSH
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS (for future SSL)Step 12: Access Application
http://your-server-ip/
Demo Roles:
- Farmer: http://your-server-ip/farmer
- Buyer: http://your-server-ip/buyer
- Consumer: http://your-server-ip/consumer
- Admin: http://your-server-ip/admin
npm run contracts:deploy
cat > .env.local << 'EOF' NEXT_PUBLIC_GANACHE_RPC_URL=http://127.0.0.1:8545 GANACHE_PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb476c6b8d6c1f02960247590f589 NEXT_PUBLIC_CROP_MARKETPLACE_ADDRESS=0x<FROM_DEPLOY_OUTPUT> NEXT_PUBLIC_PRICE_ORACLE_ADDRESS=0x<FROM_DEPLOY_OUTPUT> DATABASE_URL=postgresql://jandhan_user:changeme123@localhost:5432/jandhan_plus NEXT_PUBLIC_SERVER_IP=100.108.95.3 SERVER_PORT=3001 NODE_ENV=production EOF
npm run build
pm2 start pm2-ecosystem.config.js
sudo cp ~/jandhan-plus/server-setup/nginx.conf /etc/nginx/sites-available/jandhan-plus sudo ln -sf /etc/nginx/sites-available/jandhan-plus /etc/nginx/sites-enabled/jandhan-plus sudo rm /etc/nginx/sites-enabled/default sudo nginx -t sudo systemctl restart nginx
Open browser: http://100.108.95.3
# 6. Deploy contracts (in main terminal)
npm run contracts:deploy
# 7. Update .env.local with contract addresses
cat > .env.local << 'EOF'
NEXT_PUBLIC_GANACHE_RPC_URL=http://127.0.0.1:8545
GANACHE_PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb476c6b8d6c1f02960247590f589
NEXT_PUBLIC_CROP_MARKETPLACE_ADDRESS=0x<FROM_DEPLOY_OUTPUT>
NEXT_PUBLIC_PRICE_ORACLE_ADDRESS=0x<FROM_DEPLOY_OUTPUT>
DATABASE_URL=postgresql://jandhan_user:changeme123@localhost:5432/jandhan_plus
NEXT_PUBLIC_SERVER_IP=100.108.95.3
SERVER_PORT=3001
NODE_ENV=production
EOF
# 8. Build Next.js app
npm run build
# 9. Start services with PM2
pm2 start pm2-ecosystem.config.js
# 10. Configure Nginx
sudo cp ~/jandhan-plus/server-setup/nginx.conf /etc/nginx/sites-available/jandhan-plus
sudo ln -sf /etc/nginx/sites-available/jandhan-plus /etc/nginx/sites-enabled/jandhan-plus
sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t
sudo systemctl restart nginx
# 11. Access the application
# Open browser: http://100.108.95.3
- List Crops: Register new crops with details (quantity, quality grade, price)
- View Offers: Browse all incoming purchase offers from buyers
- Offer Management: Accept or reject buyer offers
- Payment Tracking: Monitor payment status and bank transfer confirmation
- Blockchain Proof: See immutable transaction hash for transparency
- Quality Verification: AI-assessed quality grades (A/B/C with confidence scores)
- Crop Listing: Browse all available crops from registered farmers
- Quality Information: AI quality grades with confidence scores
- Price Analysis: Compare market prices with minimum guarantee
- Make Offers: Submit purchase offers (validated by smart contract)
- Fraud Detection: View fraud risk scores before committing
- Purchase History: Track previous purchases and relationships
- Smart Contract Validation: Automatic price validation (β₯85% market price)
- QR Code Scanning: Scan product QR code to verify authenticity
- Supply Chain Transparency:
- Farm location & farmer details
- Crop quality grade with assessment date
- Price paid & fair trade verification
- Bank transfer payment reference (UPI/NEFT)
- Blockchain transaction hash
- Blockchain Verification: Immutable proof on decentralized ledger
- Fair Trade Score: Ensure farmers received fair prices
- Export Report: Download supply chain certificate
- Real-time Monitoring: Live transaction feed
- Fraud Alerts: Automated fraud detection & alerting
- Blockchain Explorer: View all transactions on deployed contracts
- User Management: Monitor farmer and buyer accounts
- Performance Analytics: Charts and statistics
- Contract Details: Deployed contract addresses & ABIs
- Transaction History: Searchable transaction logs
- Real-Time P2P Communication: Sender and Receiver interact in real-time via WebSocket
- Virtual Keypad Phones: Dual feature phone interface (left: Sender, right: Receiver)
- USSD Menu Navigation:
- Sender Flow: Dial β Select action β Enter details β Confirm with PIN β Send
- Receiver Flow: Get notification β Accept/Reject via keypad β Transaction recorded
- Live Demo: See both phones responding to each other instantly
- Transaction Types: Send Money, View Offers, List Crop, Market Rates
- WebSocket Integration: Real-time event synchronization using Socket.IO
- Test Users: Pre-configured demo accounts with balances and PINs
- No AI in Daily Ops: Transaction flow uses deterministic rules, not ML models
- Blockchain Integration: Accepted transactions recorded on smart contract
For detailed USSD documentation, see USSD_GUIDE.md
win_hack/
βββ app/ # Next.js App Router (React components)
β βββ layout.tsx # Root layout & navbar
β βββ page.tsx # Landing page
β βββ globals.css # Tailwind CSS globals
β βββ login/page.tsx # **UPDATED:** Mandatory sign-up-first UI
β βββ admin/page.tsx # Admin dashboard
β βββ farmer/page.tsx # Farmer portal
β βββ buyer/page.tsx # Buyer marketplace
β βββ consumer/page.tsx # QR code tracing
β βββ verify-qr/page.tsx # QR verification page
β βββ ussd-simulation/page.tsx # π± USSD dual-phone simulator
β βββ api/ # REST API routes
β βββ auth/
β β βββ login/route.ts # **UPDATED:** DB-backed authentication
β β βββ signup/route.ts # **NEW:** User registration endpoint
β βββ crops/list/route.ts # Get all crops
β βββ offers/create/route.ts # Create new offer
β βββ payments/commit/route.ts # Record payment
β βββ fraud/detect/route.ts # Fraud detection analysis
β βββ blockchain/transaction/route.ts # Blockchain query
β
βββ contracts/ # Solidity smart contracts
β βββ CropMarketplace.sol # Main marketplace contract (211 lines)
β β βββ Structs: Crop, Offer, PaymentRecord
β β βββ Functions: createCrop, makeOffer, acceptOffer, commitPayment
β β βββ Validations: Price checks, fraud detection rules
β βββ PriceOracle.sol # Price validation contract (45 lines)
β βββ Market price tracking
β βββ Fair price validation (β₯85% rule)
β
βββ lib/
β βββ db.ts # **NEW:** PostgreSQL connection pool
β β βββ Pool management
β β βββ Query execution
β β βββ Error handling
β βββ use-auth.ts # **UPDATED:** Auth hook with signup()
β β βββ login() - DB-backed authentication
β β βββ signup() - **NEW:** User registration
β β βββ sendOTP() - OTP delivery
β β βββ logout() - Session cleanup
β βββ blockchain.ts # ethers.js provider & contract ABIs
β β βββ Ganache provider configuration
β β βββ Contract instance helpers
β β βββ Web3 utility functions
β βββ ussd-client.ts # π± USSD REST API client
β β βββ sendUSSDRequest()
β β βββ respondToUSSDRequest()
β β βββ getIncomingRequests()
β β βββ Other USSD helpers
β βββ ussd-hooks.ts # π± React hooks for Socket.IO
β β βββ useUSSDSocket() - WebSocket management
β β βββ useUSSDMenu() - Menu state management
β βββ pg.d.ts # **NEW:** TypeScript declaration for pg module
β
βββ backend/
β βββ voice-api.js # Express.js voice/USSD API + WebSocket
β β βββ Socket.IO server
β β βββ USSD menu endpoints
β β βββ Transaction endpoints
β β βββ User management
β βββ ai-service.py # Python AI quality grading & fraud detection
β
βββ typechain-types/ # Generated TypeScript contract bindings
β βββ CropMarketplace.ts
β βββ PriceOracle.ts
β βββ factories/
β βββ common.ts
β
βββ supabase/migrations/ # PostgreSQL database schemas
β βββ 001_create_users.sql # User profiles (farmers, buyers, admins)
β βββ 002_create_crops.sql # Crop listings table
β βββ 003_create_offers.sql # Purchase offers table
β βββ 004_create_payments.sql # Payment records table
β βββ 005_create_transactions.sql # Blockchain transaction audit trail
β βββ 006_create_ussd_requests.sql # π± USSD requests & sessions tables
β
βββ artifacts/ # Compiled contract artifacts
β βββ contracts/
β β βββ CropMarketplace.sol/CropMarketplace.json # ABI & bytecode
β β βββ PriceOracle.sol/PriceOracle.json
β βββ build-info/
β
βββ server-setup/
β βββ nginx.conf # Nginx reverse proxy config
β βββ pm2-ecosystem.config.js # PM2 process manager config
β βββ setup.sh # Automated Ubuntu server setup
β
βββ scripts/
β βββ deploy.ts # Hardhat deployment script
β
βββ cache/ # Build cache files
βββ blockchain-data/ # Ganache local blockchain data
β
βββ hardhat.config.ts # Hardhat Solidity configuration
βββ tsconfig.json # TypeScript configuration
βββ next.config.js # Next.js configuration
βββ package.json # Node.js dependencies & scripts
βββ tailwind.config.ts # Tailwind CSS configuration
βββ postcss.config.js # PostCSS configuration
βββ DEPLOYMENT.md # Deployment guide
βββ PROJECT_STATUS.md # Development status
βββ QUICKSTART.md # Quick start guide
βββ USSD_GUIDE.md # π± USSD simulator documentation
βββ README.md # This file
β βββ 005_create_transactions.sql β βββ scripts/ β βββ deploy.ts # Smart contract deployment β βββ server-setup/ β βββ nginx.conf # Nginx reverse proxy config β βββ pm2-ecosystem.config.js # PM2 process manager config β βββ setup.sh # Ubuntu server auto-setup (automated) β βββ package.json # Dependencies βββ tsconfig.json # TypeScript config βββ tailwind.config.ts # Tailwind CSS config βββ hardhat.config.ts # Hardhat blockchain config βββ next.config.js # Next.js config βββ .env.local # Environment variables (created manually) βββ README.md # This file
## π Smart Contracts (Solidity)
### CropMarketplace.sol
**Main agricultural marketplace contract**
Functions:
- `listCrop(name, quality, price, farmLocation)` - Farmer lists crop on blockchain
- `makeOffer(cropId, offeredPrice, buyerPhone, upiId)` - Buyer makes offer
- `acceptOffer(offerId)` - Farmer accepts specific offer
- `commitPayment(offerId, bankRefNumber)` - Record payment commitment
- `confirmPayment(offerId)` - Record payment completion
- `getCropDetails(cropId)` - Query crop information
- `getOffers(cropId)` - Get all offers for a crop
Key Features:
- Records all transactions immutably on blockchain
- Stores farm location, quality grades, and payment details
- NO cryptocurrency transfers (blockchain only records commitment)
- Payment proof: UPI ref numbers stored on chain
### PriceOracle.sol
**Price validation & fraud prevention contract**
Functions:
- `setMandiPrice(crop, price)` - (Admin) Update reference prices
- `getMandiPrice(crop)` - Get market reference price
- `getMinAllowedPrice(crop)` - Calculate 85% threshold
- `validateOffer(cropId, offeredPrice)` - Validate offer meets 85% minimum
Fraud Rules Enforced:
- β Reject offers < 85% of mandi price
- β Block buyers with fraud history
- β Flag quality mismatches
Example:
Mandi Price: βΉ37.5/kg (rice) Minimum Allowed: βΉ31.875/kg (85%) Offer: βΉ25/kg β REJECTED π¨
## π‘ API Endpoints
### Authentication
**New User Sign-Up (Mandatory)**
POST /api/auth/signup Body: { phone, name, role, email?, bankAccount?, ifsCode?, upiId?, location? } Response: { success, message, user: { id, phone, name, role, createdAt } }
**Existing User Login**
POST /api/auth/login Body: { phone, role } Response: { success, token, userId, phone, name, role, trustScore } Note: User must exist in PostgreSQL users table (created via sign-up first)
**Flow Requirements:**
1. All users MUST sign up first via `/api/auth/signup`
2. Sign-up data is stored in PostgreSQL `users` table
3. Login endpoint verifies user exists in database before issuing token
4. Users without database records cannot login
### Crops
GET /api/crops/list Response: [{ id, name, farmer, quality, price, blockchainId }]
### Offers
POST /api/offers/create Body: { cropId, offeredPrice, buyerName, upiId } Response: { offerId, status, fraudScore, validated }
### Payments
POST /api/payments/commit Body: { offerId, bankRefNumber, amount } Response: { paymentId, status, blockchainHash }
### Fraud Detection
POST /api/fraud/detect Body: { cropId, offeredPrice, buyerHistory } Response: { fraudScore, isBlocked, reason }
### Blockchain
GET /api/blockchain/transaction Query: ?txHash=0x... Response: { blockNumber, timestamp, from, to, data }
## π€ Voice API
**Backend Express.js server (port 4000)**
Endpoints:
GET /market/prices Response: { rice, wheat, tomato, onion } (in JSON)
POST /ussd/menu Body: { phone, userInput } Response: { message, options }
## ποΈ Database Schema (PostgreSQL)
### users
```sql
- id (primary key)
- phone (unique)
- name
- role (farmer/buyer)
- bank_account (UPI ID or account number)
- created_at
- id (primary key)
- farmer_id (foreign key)
- name
- quality_grade (A/B/C)
- ai_confidence (0-100%)
- price_per_unit
- blockchain_id
- farm_location
- created_at- id (primary key)
- crop_id (foreign key)
- buyer_id (foreign key)
- offered_price
- fraud_score (0-100)
- status (pending/accepted/rejected)
- blockchain_id
- created_at- id (primary key)
- offer_id (foreign key)
- amount
- bank_transfer_ref (UPI ref)
- status (committed/confirmed)
- blockchain_hash
- timestamp- id (primary key)
- tx_type (list_crop/make_offer/payment/fraud_alert)
- blockchain_hash
- details (JSON)
- created_atBlockchain provides:
- β Immutability - Records cannot be altered
- β Transparency - Anyone can verify
- β Decentralization - No single point of control
Payments happen via:
- β Real bank transfers (UPI/NEFT)
- β NOT cryptocurrency
- β Blockchain only records proof of payment
- Go to
/farmer - Enter farm name, phone, and bank account (UPI ID)
- Add crop details: name, quality grade (A/B/C), price/unit
- Click "List Crop on Blockchain"
- β See blockchain transaction hash
- Crop now appears in buyer marketplace
- Go to
/buyer - See all available crops with quality grades
- Click crop to see details
- Enter offer price (must be β₯ 85% of mandi price)
- Smart contract validates price β shows fraud score
- Click "Make Offer" β offer recorded on blockchain
- Go back to
/farmer - See incoming offers
- Review offer amount and buyer details
- Click "Accept Offer"
- Offer status changes to "Accepted" on blockchain
- Payment details (UPI ref) committed to blockchain
- Admin dashboard shows transaction
- Blockchain records immutable payment proof
- Status: "Payment Confirmed"
- Go to
/consumer - Click "Scan QR Code" (simulated)
- See complete journey:
- π Farm location & farmer details
- πΎ Crop name & quality grade (A with 94% confidence)
- π³ Payment proof (UPI ref: UPI202501131030XXXX)
- βοΈ Blockchain hash (immutable proof)
- β Fair trade score: 88% (farmer got fair share)
- All records verified on blockchain
# Start development server (hot reload)
npm run dev
# Build for production
npm run build
# Start production server
npm start
# Compile smart contracts
npm run contracts:compile
# Deploy contracts to Ganache
npm run contracts:deploy
# Lint code
npm run lint
# Format code (if prettier is set up)
npm run format- Next.js 15 - React framework with SSR
- React 19 - UI components
- TypeScript - Type safety
- Tailwind CSS 3 - Styling
- shadcn/ui - Pre-built components
- Node.js 18+ - JavaScript runtime
- Next.js API Routes - REST endpoints
- Express.js - Voice/USSD API (port 4000)
- ethers.js v6 - Blockchain interaction
- Hardhat v2 - Smart contract toolkit
- PostgreSQL 14 - Main database
- Redis 6 - Caching (optional)
- Ganache 7.9 - Local Ethereum blockchain (port 8545)
- Solidity 0.8.20 - Smart contracts
- Typechain - TypeScript contract interfaces
- Ubuntu 20.04 - Server OS
- Nginx - Reverse proxy & web server (port 80)
- PM2 - Node.js process manager
- Git - Version control
- Google Cloud Vision - Image quality grading
- Google Cloud TTS - Voice alerts in Indian languages
- β No private keys hardcoded
- β No cryptocurrency transfers (can't lose real money)
- β Smart contracts validate all offers
- β Bank account field is just text (no crypto)
- β Blockchain is immutable audit log
The app uses hardcoded mock data for:
- Mandi prices (reference rates)
- Crop listings
- Fraud detection rules
- Payment confirmations
In production, these would connect to:
- Real AGMARKNET API
- PostgreSQL database
- Google Vision API (image quality)
- Google TTS API (voice alerts)
- Real payment gateway (Razorpay/PayU)
Automatically blocked offers:
- β Less than 85% of mandi price
- β Buyer with high fraud history
- β Quality mismatch (Grade A demanded but B supplied)
Example:
Mandi price: βΉ1,820/quintal
Min allowed: βΉ1,547/quintal (85%)
Rogue offer: βΉ1,092/quintal β BLOCKED π¨
- β Mobile-first approach
- β Tailwind CSS responsive grid
- β Works on phones, tablets, laptops
- β Touch-friendly buttons
βββββββββββββββββββββββββββββββββββββββββββ
β User Browser (Your Laptop) β
β http://100.108.95.3 β
ββββββββββββββββ¬βββββββββββββββββββββββββββ
β (Port 80)
β
ββββββββββββββββββββββββββββββββββββββββββββ
β Nginx Reverse Proxy β
β Listens on 0.0.0.0:80 β
ββββββββββββββββ¬βββββββββββββββββββββββββββ€
β Routes to β Routes to β
β Next.js β Voice API β
β Port 3001 β Port 4000 β
ββββββββ¬ββββββββ΄βββββββββββββββββββββββββββ
β β
β β
βββββββββββββββ ββββββββββββββββ
β Next.js App β β Voice API β
β (PM2) β β (Express) β
β PORT: 3001 β β PORT: 4000 β
ββββββββ¬βββββββ ββββββββββββββββ
β
ββββββ΄βββββ
β β
ββββββββ ββββββββββ
β DB β βGanache β
β :5432β β :8545 β
ββββββββ ββββββββββ
| Service | Port | Purpose |
|---|---|---|
| Nginx | 80 | Public entry point |
| Next.js | 3001 | Frontend + API |
| Voice API | 4000 | USSD alerts |
| Ganache | 8545 | Blockchain RPC |
| PostgreSQL | 5432 | Database |
| Redis | 6379 | Caching (optional) |
- nginx.conf - Reverse proxy routing to ports 3001 & 4000
- pm2-ecosystem.config.js - PM2 process manager configuration
- .env.local - Environment variables (contract addresses, database URL, etc.)
After completing setup, verify each component is working:
curl http://127.0.0.1:8545 -X POST -H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'
# Expected: {"jsonrpc":"2.0","result":"0x0","id":1}curl http://localhost:3000
# Expected: HTML response with landing page contentcurl http://localhost:4000/market/prices
# Expected: JSON with market pricesAfter running npm run contracts:deploy, verify:
- β CropMarketplace contract deployed
- β PriceOracle contract deployed
- β
Copy addresses to
.env.local
psql -U jandhan_user -d jandhan_plus -h localhost -c "SELECT * FROM users;"
# Expected: Empty table (success if no errors)Solution:
npm install --legacy-peer-deps
npm install ethersSolution:
# Make sure Ganache is running
ganache --database.dbPath ./blockchain-data --server.port 8545
# Check if port 8545 is in use
netstat -ano | findstr 8545 # Windows
lsof -i :8545 # macOS/LinuxSolution:
Run deployment again and update .env.local:
npm run contracts:deploy
# Copy the output addresses
# Update NEXT_PUBLIC_CROP_MARKETPLACE_ADDRESS and NEXT_PUBLIC_PRICE_ORACLE_ADDRESSSolution:
# Make sure PostgreSQL is running
sudo service postgresql status # Linux
brew services list # macOS
# Verify database exists
sudo -u postgres psql -c "\l"Solution:
# Check Nginx syntax
sudo nginx -t
# View Nginx error log
sudo tail -f /var/log/nginx/error.log
# Restart Nginx
sudo systemctl restart nginxSolution:
# Windows: Find and kill process
netstat -ano | findstr :3000
taskkill /PID <PID> /F
# macOS/Linux
lsof -i :3000
kill -9 <PID>
# Or use different port
npm run dev -- -p 3001# Development
npm run dev # Start Next.js dev server (hot reload)
npm run build # Build for production
npm start # Start production server
# Smart Contracts
npm run contracts:compile # Compile Solidity contracts
npm run contracts:deploy # Deploy to Ganache
# Code Quality
npm run lint # Run ESLint
npm run format # Format code with Prettier (if configured)
# Database (manual if PostgreSQL used)
# psql -U jandhan_user -d jandhan_plus -h localhost < supabase/migrations/001_create_users.sqlWhen updating code, follow this process:
# 1. Pull latest code
git pull origin main
# 2. Install/update dependencies
npm install
# 3. Restart services
npm run dev # For development
# OR
npm run build && npm start # For production
# 4. If smart contracts changed
npm run contracts:compile
npm run contracts:deploy
# Update .env.local with new addresses
# 5. If database schema changed
# Run new migrations manually
psql -U jandhan_user -d jandhan_plus -h localhost < supabase/migrations/XXX_new_table.sqlβββ Frontend
β βββ next (15.0.0) - React framework
β βββ react (19.0.0-rc) - UI library
β βββ tailwindcss (3.4) - CSS utility framework
β βββ ethers (6.13.5) - Blockchain interaction
β βββ qrcode.react (3.1.0) - QR code generation
β βββ html5-qrcode (2.3.8) - QR code scanning
β βββ recharts (2.12.7) - Charts & graphs
β βββ react-leaflet (4.2.1) - Map component
β
βββ Backend
β βββ express (4.18.2) - HTTP server
β βββ cors (2.8.5) - Cross-origin support
β
βββ Utilities
βββ uuid (9.0.1) - ID generation
βββ Smart Contract Tools
β βββ hardhat (2.20.0) - Solidity toolkit
β βββ @hardhat-toolbox - bundled tools
β βββ typechain (8.3.2) - Type generation
β βββ solidity-coverage - test coverage
β
βββ Blockchain Libs
β βββ ethers (6.13.5) - already listed above
β βββ hardhat-ethers - Hardhat integration
β
βββ TypeScript & Types
β βββ typescript (5.6.2)
β βββ @types/node (20.0.0)
β βββ @types/react (19.0.0)
β βββ @types/chai (4.3.20)
β
βββ Linting & Formatting
βββ eslint (8.57.0)
βββ autoprefixer (10.4.20)
- β Self-hosted working demo
- β Functional farmer β buyer β consumer flow
- β Real smart contracts on blockchain
- β Fraud detection and blocking
- β Transparent payment proof
- β Professional UI/UX
- β No cryptocurrency complexity
Built for BGSCET Hackathon 2025. All rights reserved.
β Implemented:
- No private keys hardcoded (stored in
.env.localwhich is gitignored) - No cryptocurrency transfers (blockchain is immutable ledger only)
- Smart contracts validate all offers via PriceOracle
- Bank account fields for payment tracking (not crypto wallets)
- Fraud detection rules enforced at smart contract level
- Role-based access control (farmer, buyer, consumer, admin)
β Recommended for Production:
- HTTPS/SSL certificates (Certbot + Let's Encrypt)
- Firewall rules (SSH: 22, HTTP: 80, HTTPS: 443)
- Database encryption & regular backups
- Rate limiting on API endpoints (1000 req/hour per IP)
- JWT token signing with strong secrets
- Nginx request throttling & DDoS protection
- Regular smart contract audits
- Use hardware wallet for prod contract deployment
| Feature | Type | Location | Status |
|---|---|---|---|
| Farmer Portal | Frontend | /app/farmer/page.tsx |
β Complete |
| Buyer Marketplace | Frontend | /app/buyer/page.tsx |
β Complete |
| Consumer QR Trace | Frontend | /app/consumer/page.tsx |
β Complete |
| Admin Dashboard | Frontend | /app/admin/page.tsx |
β Complete |
| USSD Dual-Phone Simulator | Frontend | /app/ussd-simulation/page.tsx |
β Complete |
| Authentication | API | /app/api/auth/login/route.ts |
β Complete |
| Crop Listing | API | /app/api/crops/list/route.ts |
β Complete |
| Offer Creation | API | /app/api/offers/create/route.ts |
β Complete |
| Payment Tracking | API | /app/api/payments/commit/route.ts |
β Complete |
| Fraud Detection | API | /app/api/fraud/detect/route.ts |
β Complete |
| Blockchain Query | API | /app/api/blockchain/transaction/route.ts |
β Complete |
| CropMarketplace.sol | Smart Contract | /contracts/CropMarketplace.sol |
β Complete |
| PriceOracle.sol | Smart Contract | /contracts/PriceOracle.sol |
β Complete |
| Voice/USSD API | Backend | /backend/voice-api.js |
β Complete |
| USSD WebSocket Server | Backend | /backend/voice-api.js |
β Complete |
| AI Service | Backend | /backend/ai-service.py |
β Complete |
| Database Schema | PostgreSQL | /supabase/migrations/ |
β Complete (6 tables) |
| USSD Tables | PostgreSQL | /supabase/migrations/006_create_ussd_requests.sql |
β Complete |
| Nginx Config | DevOps | /server-setup/nginx.conf |
β Complete |
| PM2 Config | DevOps | /server-setup/pm2-ecosystem.config.js |
β Complete |
"Your crop, your price, fair. Your money, your right, protected."
This platform proves that blockchain can solve transparency problems WITHOUT cryptocurrency, and that agricultural supply chains can be revolutionized with simple, effective technology accessible to rural India.
No middlemen. No exploitation. Pure fairness. Immutably recorded.
For issues or questions:
- Check existing code in
/app - Review smart contracts in
/contracts - Test manually in your browser
- Check browser console for errors
Happy building! ππΎ