P2P Solar Energy Trading Platform for India
A comprehensive full-stack web application enabling peer-to-peer renewable energy trading between consumers and prosumers (solar panel owners), with real-time pricing, blockchain-backed settlements, and utility oversight.
Built for the Hackathon using MERN Stack (MongoDB, Express, React, Node.js) with Socket.io, DaisyUI, and a custom SHA-256 blockchain ledger.
Sun Swap is a production-ready P2P energy marketplace that allows:
- Consumers to buy clean energy directly from local solar producers at dynamic market prices
- Prosumers (solar panel owners) to sell surplus energy and track ROI
- Utilities (DISCOM/Admin) to monitor the grid, manage users, and offer cashback incentives
All transactions are settled atomically with wallet debits/credits and recorded on an immutable custom blockchain ledger.
- Node.js v20+ with ES modules (
"type": "module") - Express.js v5 — REST API + Socket.io WebSocket server
- MongoDB + Mongoose — NoSQL database with atomic transactions
- JWT (HTTP-only cookies) — Secure session management
- Socket.io — Real-time meter readings, pricing updates, live trade feed
- crypto-js — SHA-256 blockchain (Proof-of-Work, difficulty=2)
- bcryptjs — Password hashing
- React 18 + TypeScript (Vite build)
- Tailwind CSS v4 (via
@tailwindcss/vite) + DaisyUI v5 theming - React Router v6 — Role-based routing
- Zustand — Global state (auth + wallet)
- React Hook Form + Zod — Form validation
- Recharts — Live charts (price history, earnings, analytics)
- Heroicons — Icon system
- date-fns — Date formatting
- Axios — HTTP client with interceptors
- 3 User Roles: Consumer, Prosumer, Utility (Admin)
- Atomic Wallet Operations: MongoDB sessions ensure balance never goes negative
- Dynamic Pricing Engine: ToD (Time of Day) multipliers + supply/demand ratio, recalculates every 30s
- Smart Meter Simulator: Gaussian solar curve + household consumption pattern, emits every 5s via Socket.io
- Custom Blockchain: Every settled trade mines a block (PoW difficulty=2), stores hash as ledger reference
- Idempotency: Keys on trades, wallet transactions, withdrawals prevent double-processing
- 11 Notification Types: Real-time via Socket.io + MongoDB persistence
sunswap/
├── backend/
│ ├── src/
│ │ ├── blockchain/ledger.js # SHA-256 PoW blockchain
│ │ ├── config/db.js # MongoDB connection
│ │ ├── middleware/
│ │ │ ├── auth.js # JWT + role guards
│ │ │ └── errorHandler.js # Global error handling
│ │ ├── models/ # 14 Mongoose schemas
│ │ │ ├── User.js
│ │ │ ├── Wallet.js
│ │ │ ├── Listing.js
│ │ │ ├── Trade.js
│ │ │ ├── Block.js # Blockchain blocks
│ │ │ └── ...
│ │ ├── routes/ # REST API routes
│ │ │ ├── auth.js
│ │ │ ├── wallet.js
│ │ │ ├── listings.js # Marketplace + buy flow
│ │ │ ├── ledger.js
│ │ │ ├── pricing.js
│ │ │ ├── notifications.js
│ │ │ ├── utility.js # Admin routes
│ │ │ └── prosumer.js
│ │ ├── services/
│ │ │ ├── pricingEngine.js # Dynamic pricing (30s cycle)
│ │ │ ├── meterSimulator.js # Live meter (5s emit)
│ │ │ ├── notificationService.js # Socket + DB notifications
│ │ │ └── walletService.js # Atomic debit/credit
│ │ ├── utils/seed.js # Demo data seeder
│ │ └── server.js # Express + Socket.io entry
│ ├── .env
│ └── package.json
│
├── frontend/
│ ├── src/
│ │ ├── api/client.ts # Axios config
│ │ ├── components/
│ │ │ ├── layout/AppLayout.tsx # Sidebar + topbar
│ │ │ └── WalletPage.tsx # Shared wallet UI
│ │ ├── context/SocketContext.tsx # Socket.io React context
│ │ ├── screens/
│ │ │ ├── auth/ # Login, Register
│ │ │ ├── consumer/ # Dashboard, Marketplace, Wallet
│ │ │ ├── prosumer/ # Dashboard, Listings, Earnings, Setup
│ │ │ ├── utility/ # Admin Dashboard, Users, Offers, Ledger
│ │ │ └── Profile.tsx
│ │ ├── store/authStore.ts # Zustand (user + wallet)
│ │ ├── utils/
│ │ ├── App.tsx # Router + role-based routes
│ │ └── main.tsx
│ ├── index.html
│ ├── vite.config.ts
│ ├── tailwind.config.js # DaisyUI theme
│ └── package.json
│
└── README.md
- Node.js v20+
- MongoDB v7+ running on
mongodb://127.0.0.1:27017 - npm or yarn
cd sunswap/backend
# Install dependencies
npm install
# Create .env file (already exists, verify values)
# PORT=5000
# MONGO_URI=mongodb://127.0.0.1:27017/sunswap
# JWT_SECRET=sunswap_super_secret_jwt_key_2024_hackout
# JWT_EXPIRES_IN=7d
# NODE_ENV=development
# CLIENT_URL=http://localhost:5173
# Seed database with demo accounts + data
npm run seed
# Start backend server (Socket.io + Express on port 5000)
npm startBackend will start on http://localhost:5000
The seed script creates:
- 1 Utility admin account
- 3 Prosumers with solar setups (5 kW, 3.5 kW, 8 kW)
- 4 Consumers
- Sample listings, trades, notifications, offers, blockchain blocks
cd sunswap/frontend
# Install dependencies
npm install
# Start Vite dev server (port 5173)
npm run devFrontend will start on http://localhost:5173
All passwords: Demo@1234 (except admin)
| Password | Role | Solar Capacity | |
|---|---|---|---|
admin@bescom.in |
Admin@1234 |
Utility (Admin) | — |
arjun@demo.in |
Demo@1234 |
Prosumer | 5.0 kW |
priya@demo.in |
Demo@1234 |
Prosumer | 3.5 kW |
rajesh@demo.in |
Demo@1234 |
Prosumer | 8.0 kW |
sneha@demo.in |
Demo@1234 |
Consumer | — |
vikram@demo.in |
Demo@1234 |
Consumer | — |
anita@demo.in |
Demo@1234 |
Consumer | — |
deepak@demo.in |
Demo@1234 |
Consumer | — |
Color Palette (Deep Charcoal Energy Control Room Aesthetic)
- Base:
#0d1117(bg),#161b22,#21262d,#30363d(surfaces) - Primary (Solar Amber):
#f59e0b,#d97706— generation, earnings - Secondary (Electric Teal):
#2dd4bf,#14b8a6— live activity, prosumer - Info (Indigo):
#6366f1— utility/admin - Success:
#3fb950— completed, verified - Warning:
#d29922— flagged, alerts - Error:
#f85149— failures, disputes
Typography
- Sans: Inter (body), system-ui fallback
- Mono: JetBrains Mono, Fira Code (ledger hashes, meter readings)
- JWT tokens in HTTP-only cookies (7-day expiry)
- Passwords hashed with bcryptjs (10 rounds)
- Role-based middleware:
protect,requireRole,requireConsumerOrProsumer - 401 interceptor in frontend → auto-logout
// Using MongoDB sessions + transactions
const session = await mongoose.startSession();
await session.startTransaction();
try {
// 1. Check balance >= amount
// 2. Decrement wallet.balance
// 3. Create WalletTransaction record
// 4. Commit
await session.commitTransaction();
} catch (err) {
await session.abortTransaction();
throw err;
}Balance can never go negative — debit fails before credit occurs.
- Algorithm: SHA-256 (via crypto-js)
- Proof-of-Work: Difficulty = 2 (hash must start with
00) - Structure:
index | timestamp | transactions[] | previousHash | hash | nonce - Persistence: MongoDB (
Blockmodel) - Immutability: Every block references previous hash; chain validation API
- Trade Integration: Every settled trade mines a block, stores hash as
ledgerRef
Baseline = ₹6.00/kWh
Floor = ₹4.00, Ceiling = ₹9.00
Ratio = demand / supply
Raw = Baseline + (Ratio - 1) × 2
Clamped = clamp(Raw, Floor, Ceiling)
Final = Clamped × ToD_Multiplier
ToD Multipliers:
- Morning Peak (6–10 AM): ×1.15
- Evening Peak (6–10 PM): ×1.20
- Night (10 PM–6 AM): ×0.80Recalculates every 30 seconds, broadcasts via Socket.io.
- Solar Production: Gaussian curve centered at 1 PM (peak), σ=7h, zero at night
- Household Consumption: Bimodal peaks at 8 AM + 8 PM, base 0.4 kW
- Surplus: max(0, production - consumption)
- Frequency: Emits every 5 seconds via Socket.io to user rooms
POST /api/auth/register— Create account (gets 100 free credits)POST /api/auth/login— Login (sets JWT cookie)POST /api/auth/logout— Logout (clears cookie)GET /api/auth/me— Get current user + walletPATCH /api/auth/profile— Update profile
GET /api/wallet— Get wallet detailsPOST /api/wallet/topup— Add credits (idempotency key supported)GET /api/wallet/transactions— Paginated transaction historyPOST /api/wallet/withdraw— Request withdrawal to bank
GET /api/listings— Browse active listings (filter by zone, sort)POST /api/listings— Create listing (prosumer only)PATCH /api/listings/:id— Edit listingDELETE /api/listings/:id— Cancel listingPOST /api/listings/:id/buy— Purchase energy (atomic settlement + blockchain)GET /api/listings/my— Prosumer's own listings
GET /api/pricing/current— Live grid priceGET /api/pricing/history— Price snapshots (last N)GET /api/pricing/meter— User's meter readings
GET /api/ledger— Paginated blocksGET /api/ledger/:index— Block detailGET /api/ledger/validate— Validate entire chain integrity
GET /api/notifications— User's notifications (paginated)PATCH /api/notifications/:id/read— Mark as readPATCH /api/notifications/read-all— Mark all as read
GET /api/prosumer/solar-setup— Get solar system detailsPOST /api/prosumer/solar-setup— Setup/update solar systemGET /api/prosumer/earnings— Total + daily breakdown (30 days)GET /api/prosumer/roi— ROI calculation
GET /api/utility/overview— Aggregate stats (users, trades, volume)GET /api/utility/trades— All trades (paginated)GET /api/utility/users— User list (filter by role/status, search)PATCH /api/utility/users/:id/status— Update user status (active/flagged/frozen/disabled)GET /api/utility/offers— All cashback offersPOST /api/utility/offers— Create offer (notifies eligible users)PATCH /api/utility/offers/:id— Update offerGET /api/utility/disputes— All disputesPOST /api/utility/disputes— Open dispute (any user)POST /api/utility/disputes/:id/note— Add admin noteGET /api/utility/analytics— 7-day trade volume, user growth, top zonesGET /api/utility/audit— Audit logGET /api/utility/withdrawals— All withdrawal requestsPATCH /api/utility/withdrawals/:id— Approve/reject withdrawal
- ✅ Live grid price + meter (Socket.io real-time)
- ✅ Browse marketplace (filter by zone, sort by price)
- ✅ Buy energy from prosumers (atomic settlement)
- ✅ Wallet topup + transaction history
- ✅ Recent purchases feed
- ✅ Eco impact stats (clean energy ratio)
- ✅ Solar setup onboarding (capacity, zone, cost, installation date)
- ✅ Live solar generation + household consumption chart
- ✅ Surplus meter (exportable energy)
- ✅ Create/manage energy listings (price, quantity, expiry)
- ✅ Earnings dashboard (total credits, daily breakdown, ROI)
- ✅ Wallet with withdrawal to bank
- ✅ Trade history
- ✅ Grid overview (total users, trades, volume, kWh)
- ✅ Live trade feed (Socket.io real-time)
- ✅ 7-day analytics (trade volume chart, user growth, top zones)
- ✅ User management (search, filter, flag/freeze accounts)
- ✅ Offers & cashback campaigns (create, edit, target audience/zone)
- ✅ Blockchain ledger viewer (validate chain integrity, block explorer)
- ✅ Dispute management
- ✅ Audit log
- ✅ Withdrawal request approval
npm start # Start server (port 5000)
npm run dev # Start with nodemon (auto-reload)
npm run seed # Seed database with demo datanpm run dev # Vite dev server (port 5173)
npm run build # Production build
npm run preview # Preview production buildBackend .env (already configured):
PORT=5000
MONGO_URI=mongodb://127.0.0.1:27017/sunswap
JWT_SECRET=sunswap_super_secret_jwt_key_2024_hackout
JWT_EXPIRES_IN=7d
NODE_ENV=development
CLIENT_URL=http://localhost:5173users,wallets,wallettransactionssolarsetups,listings,trades,meterreadingspricesnapshots,blocks(blockchain)offers,notifications,disputesauditlogs,withdrawalrequests
- Backend: REST API + Socket.io server
- Frontend: React + TypeScript + Tailwind + DaisyUI
- Auth: JWT cookie auth + role-based routing
- Wallet: Atomic operations, topup, withdrawal
- Marketplace: Browse, create listings, buy energy
- Pricing Engine: Dynamic pricing (30s cycle, ToD multipliers)
- Smart Meter: Gaussian solar + bimodal consumption (5s emit)
- Blockchain: SHA-256 PoW ledger, chain validation
- Notifications: 11 types, Socket.io + DB
- Consumer Dashboard: Live price, meter, purchases
- Prosumer Dashboard: Solar setup, listings, earnings, ROI
- Utility Dashboard: Grid overview, live trade feed, analytics
- Admin Tools: User management, offers, disputes, ledger viewer
- Seed Data: 8 demo accounts, listings, trades, blockchain blocks
- Responsive: Mobile-friendly, DaisyUI components
- Design System: Charcoal + amber + teal theme
- README: Complete documentation
- Replace custom blockchain with Ethereum/Polygon smart contracts
- Real hardware smart meter integration (IoT)
- Mobile apps (React Native)
- Advanced analytics (ML price prediction, demand forecasting)
- Multi-DISCOM support (inter-zone trading)
- Carbon credit tracking
- Peer-to-peer chat (buyer-seller communication)
- PDF invoice generation
- Email notifications
- Two-factor authentication (2FA)
Hackathon Project — September 2026
Team: Solo Developer (Claude Code Assistant)
Duration: 30 hours
Status: Production-ready MVP
MIT License — Free to use, modify, and distribute.
For issues or questions, please contact the hackathon team or open an issue in the repository.
Sun Swap — Powering India's Clean Energy Future, One Trade at a Time ⚡☀️