CropChain is a comprehensive full-stack web application that enables transparent tracking of crop supply chains using blockchain technology. From farm to fork, every step in the supply chain is recorded immutably, providing complete traceability and building trust between all stakeholders.
The system is live and deployed across production services:
- Frontend Application (Vercel): cropchain.sonusid.in
- Backend API (AWS): cropapi.sonusid.in (Health Status: cropapi.sonusid.in/api/health)
- Smart Contract (Sepolia Testnet):
0x2c79F3f6b448270ADF667CA5d23d23feC4d15Fa4
- Complete Supply Chain Tracking: Track crops through all stages - Farmer β Mandi (Market) β Transport β Retailer
- Blockchain Integration: Immutable record keeping using Ethereum/Polygon smart contracts
- QR Code Generation: Unique QR codes for each batch enabling instant verification
- Multi-Role Support: Different interfaces for farmers, markets, transporters, and retailers
- Admin Dashboard: Comprehensive monitoring and analytics for supply chain managers
- AI-Powered Assistant: Intelligent chatbot for crop tracking support and stakeholder guidance
- Offline-First Architecture: Work without internet - data syncs automatically when online
- Beautiful, Modern UI: Apple-level design aesthetics with smooth animations
- Responsive Design: Optimized for mobile, tablet, and desktop devices
- Real-time Timeline: Visual supply chain journey with status indicators
- QR Code Scanner: Simulate scanning QR codes for batch tracking
- Search & Filter: Easy batch lookup and filtering capabilities
- Conversational AI: Natural language interface for system guidance and batch queries
- Offline Mode: Create batches and updates without internet connectivity
- Auto-Sync: Changes automatically sync to blockchain when connection restored
- Framework: Next.js with TypeScript
- Styling: Tailwind CSS with custom design system
- Routing: Next.js App/Pages Router
- Icons: Lucide React for consistent iconography
- State Management: React hooks and context
- Runtime: Node.js with Express framework
- Blockchain: Ethers.js for smart contract interaction
- QR Codes: QRCode library for batch QR generation
- Database: MongoDB for metadata storage
- Authentication: JWT-based auth system
- AI Integration: Gemini (@google/generative-ai) for intelligent assistance
- Runtime: Python 3.11 with Flask framework
- Model: Scikit-learn RandomForest Classifier
- Endpoints: Health and Crop Quality Prediction
- Security: API Key authentication and Rate Limiting
- Deployment: Gunicorn WSGI HTTP Server
- Platform: Ethereum/Polygon compatible
- Language: Solidity ^0.8.19
- Features: Batch creation, supply chain updates, access control
- Security: Role-based permissions and data validation
## Docker Setup
### Published Images (GHCR)
Validated Docker images are automatically published to the GitHub Container Registry (GHCR) upon merging to the `main` branch or creating a release tag.
Available images include:
- `ghcr.io/<repository-owner>/backend:latest` (or `:main`, `:sha-<commit>`)
- `ghcr.io/<repository-owner>/frontend:latest`
- `ghcr.io/<repository-owner>/ml-service:latest`
### Prerequisites
Make sure the following are installed on your system:
- Docker 24+
- Docker Compose plugin (`docker compose`)
---
## Quick Start
### 1. Clone the Repository
```bash
git clone https://github.com/Nitya-003/CropChain.git
cd CropChain
```Create a root .env file:
cp .env.example .envUpdate the .env file with the required values:
# Frontend public API endpoint
NEXT_PUBLIC_API_URL=http://localhost:3001
# Backend runtime
NODE_ENV=production
PORT=3001
MONGODB_URI=mongodb://db:27017/cropchain
FRONTEND_URL=http://localhost:3000
ALLOWED_ORIGINS=http://localhost:3000
# Blockchain configuration
INFURA_URL=https://polygon-mainnet.infura.io/v3/YOUR_PROJECT_ID
CONTRACT_ADDRESS=0xYOUR_CONTRACT_ADDRESS
PRIVATE_KEY=0xYOUR_PRIVATE_KEYNote:
NEXT_PUBLIC_*variables are exposed to the browser and evaluated during build time. If you modify them later, rebuild the frontend image using:docker compose build frontendor
docker compose up --build
Build and start all services:
docker compose up --buildThis starts:
- Frontend (Next.js)
- Backend (Node.js + Express)
- ML Service (Python + Flask)
- MongoDB Database
- Hardhat Blockchain Node
CropChain uses GitHub Actions to automate deployments to our AWS infrastructure.
When code is merged to the main branch and passes all CI tests, security scans, and SBOM generation, the Deploy to AWS Production workflow is triggered.
- Authentication: Securely authenticates with AWS via OpenID Connect (OIDC) or Repository Secrets (
AWS_ROLE_ARN). - Deployment: Uses the
deploy-aws.shscript to package the codebase and deploy via AWS CloudFormation and Systems Manager (SSM) to an EC2 instance. - Verification: Automatically performs a health check on the deployed backend API to ensure successful deployment.
| Service | URL |
|---|---|
| Frontend | http://localhost:3000 |
| Backend API | http://localhost:3001 |
| ML Service | http://localhost:5001 |
| Hardhat Node | http://localhost:8545 |
| MongoDB | mongodb://localhost:27017 |
To deploy smart contracts to the running Hardhat container:
docker compose exec hardhat npx hardhat run scripts/deploy.js --network localhostDocker Compose provides:
- Hot reloading for development
- Isolated and reproducible environments
- Internal container networking
- Persistent MongoDB storage
- Simplified multi-service orchestration
Stop all running containers:
docker compose downStop containers and remove volumes:
docker compose down -v- The root
Dockerfileuses a multi-stage build setup for optimized frontend and backend images. .dockerignoreexcludes unnecessary folders likenode_modules,dist,build, and.gitto reduce build size.- To inspect built image sizes, run:
docker images
- Node.js (v18.18+)
- npm or yarn
- MetaMask wallet
- Infura/Alchemy account (for blockchain)
- MongoDB (for production)
-
Clone the repository
git clone https://github.com/Siddh2024/CropChain.git cd CropChain -
Install dependencies
# Frontend npm install # Backend cd backend && npm install && cd ..
-
Environment Setup
# Copy environment files cp backend/.env.example backend/.env cp .env.example .env # Edit with your configuration nano backend/.env nano .env
-
Configure AI Chatbot (Optional)
# Add Gemini API key to backend/.env echo "GEMINI_API_KEY=your_gemini_api_key_here" >> backend/.env
-
Start Frontend Development Server
npm run dev
-
Start Backend Server (in separate terminal)
cd backend npm run dev -
Deploy Smart Contracts (optional, for blockchain integration)
# For local development npx hardhat node npx hardhat run scripts/deploy.js --network localhost # For Mumbai testnet npx hardhat run scripts/deploy.js --network mumbai
graph TD
subgraph Client_Layer [Frontend - React & TypeScript]
UI[User Interface]
QR[QR Scanner/Generator]
end
subgraph Logic_Layer [Backend - Node.js & Express]
API[Express API]
JWT[JWT Auth]
ETH[Ethers.js Instance]
end
subgraph ML_Layer [ML Service - Python & Flask]
MLAPI[Flask API]
RF[RandomForest Model]
end
subgraph Storage_Layer [Data & Blockchain]
DB[(MongoDB Metadata)]
BC{Smart Contracts - Solidity}
Network[Polygon / Mumbai Testnet]
end
UI --> API
API --> JWT
API --> DB
API --> ETH
API --> MLAPI
MLAPI --> RF
ETH --> BC
BC --> Network
sequenceDiagram
participant F as Farmer
participant M as Mandi (Market)
participant T as Transport
participant R as Retailer
participant B as Blockchain (CropChain)
F->>B: Create Batch (Harvest Info)
B-->>F: Generate Unique Batch ID & QR
F->>M: Handover Crops
M->>B: Update Stage (Price & Quality)
M->>T: Handover to Logistics
T->>B: Update Stage (Location & Transit)
T->>R: Deliver to Store
R->>B: Update Stage (Received/Stocked)
Note over R,B: Immutable History Available for Consumer
- Navigate to "Add Batch" page
- Fill in crop details (type, quantity, harvest date, etc.)
- Submit to create blockchain record and QR code
- Share QR code with supply chain partners
- Go to "Update Batch" page
- Search for batch using Batch ID
- Add your stage information (actor, location, notes)
- Submit update to blockchain
- Use "Track Batch" page
- Scan QR code or enter Batch ID
- View complete supply chain history
- Verify authenticity and quality information
- Access Admin Dashboard
- Monitor all batches and supply chain activity
- View analytics and statistics
- Manage system-wide operations
- Access: Click the floating chat button (bottom-right corner) on any page
- Quick Actions: Use suggested buttons for common tasks
- Natural Queries: Ask questions like:
- "Where is batch CROP-2024-001?"
- "How do I create a new batch?"
- "What does immutable record mean?"
- "Help me track my shipment"
- Context Awareness: The AI understands your current page and provides relevant help
- Function Calling: AI can search batches and provide real-time data
Backend (.env)
# Server
PORT=3001
NODE_ENV=development
# Blockchain
INFURA_URL=https://polygon-mumbai.infura.io/v3/YOUR_PROJECT_ID
CONTRACT_ADDRESS=0x...
PRIVATE_KEY=0x...
# Database
MONGODB_URI=mongodb://localhost:27017/cropchain
# Security
JWT_SECRET=your_secret_key
# AI Chatbot (Optional)
GEMINI_API_KEY=your_gemini_api_key_here
AI_MODEL=gemini-1.5-flash
AI_MAX_TOKENS=500
AI_TEMPERATURE=0.7
# ML Service API Key
ML_API_KEY=your_ml_api_key_hereFrontend (.env)
# API Configuration
NEXT_PUBLIC_API_URL=http://localhost:3001
# Development
NEXT_PUBLIC_DEV_MODE=trueSmart Contracts (hardhat.config.js)
networks: {
mumbai: {
url: process.env.INFURA_URL,
accounts: [process.env.PRIVATE_KEY]
}
}npx vitestcd backend
npm testnpx hardhat testWe provide an automated script to deploy the full stack to AWS using CloudFormation and Systems Manager (SSM). This script sets up an EC2 instance, configures Docker, and starts the services.
./deploy-aws.shPost-Deployment Verification: The deployment script includes automated health checks to verify that services have started correctly before completing. It polls the following endpoints with retry logic:
- Backend Health Check:
http://<EC2_IP>:3001/api/health - ML Service Health Check:
http://<EC2_IP>:5001/health
The deployment will automatically fail if the services do not become healthy within the timeout period.
npm run build
# Deploy dist/ folder to your hosting providercd backend
# Configure environment variables on your platform
git push heroku main# Mumbai Testnet
npx hardhat run scripts/deploy.js --network mumbai
# Polygon Mainnet
npx hardhat run scripts/deploy.js --network polygon- Access Control: Role-based permissions in smart contracts
- Data Validation: Input sanitization and validation
- Rate Limiting: API rate limiting to prevent abuse
- CORS Protection: Configured CORS policies
- Environment Variables: Sensitive data protected via env vars
- Smart Contract Auditing: Comprehensive testing and validation
Frontend
- React 18 + TypeScript
- Tailwind CSS
- Next.js App/Pages Router
- Lucide React Icons
- QRCode.js
- Framer Motion (animations)
Backend
- Node.js + Express
- Ethers.js
- MongoDB + Mongoose
- JWT Authentication
- QRCode Generation
- Gemini API Integration
- Axios HTTP Client
Machine Learning
- Python 3.11
- Flask (API framework)
- Scikit-learn (RandomForest Model)
- Gunicorn (WSGI server)
- NumPy & Joblib
Blockchain
- Solidity ^0.8.19
- Hardhat Development Environment
- Ethereum/Polygon Networks
- OpenZeppelin Libraries
DevOps
- ESLint + Prettier
- Husky Git Hooks
- GitHub Actions CI/CD
- Docker Support
CropChain includes an interactive progress tracker representing the end-to-end journey of a crop batch from registration to final retailer delivery.
Every crop batch flows sequentially through the following 6 stages:
- Registered: Initial creation of crop record.
- Growing: Active cultivation phase in fields.
- Harvested: Crops harvested and ready for processing.
- Quality Checked: Certified safe and qualified by inspectors.
- Transported: Loaded and shipped in cold-chain logistics.
- Delivered: Received at final retailer destinations.
- Transitions are strictly sequential (no skipping stages, no reverting backwards).
- Prevent duplicate updates and unauthorized role changes:
- Farmer: Authorized to update stages until
Harvested(Growing,Harvested). - Distributor (Transporter / Mandi): Authorized to update to
Transported. - Retailer: Authorized to update to
Delivered. - Admin: Full control over all transitions (including
Quality Checked).
- Farmer: Authorized to update stages until
- Get Crop Lifecycle Details:
GET /api/batches/:id/lifecycle- Returns
currentStage,stageHistory, andcompletionPercentage.
- Returns
- Update Lifecycle Stage:
PATCH /api/batches/:id/lifecycle- Body:
{ "stage": "Growing", "notes": "Growing smoothly" } - Validates role authorizations and transitions.
- Body:
The tracker renders dynamically as the CropLifecycleTracker component:
- Desktop: Interactive horizontal progress bar with customized SVG and framer-motion micro-animations.
- Mobile: Responsive vertical timeline cards with action details.
- Smart Features:
- Delay Alert Detection: Automatically warns if a batch remains in a stage longer than configurable expectations (e.g.
β Transport pending for 6 days). - Relative Timestamps: Displayed as "3 hours ago", "Yesterday", or "5 days ago".
- Tooltip cards: Displays complete metadata, blockchain transaction links, and timestamps on hover/focus.
- Delay Alert Detection: Automatically warns if a batch remains in a stage longer than configurable expectations (e.g.
CropChain uses a blockchain signing wallet to write supply chain records on-chain. The private key for this wallet must never be stored as a plaintext environment variable in production.
For local testing only, add your dev wallet key to .env:
PRIVATE_KEY=0x...your_local_dev_key...
β οΈ Never commit a real private key. Use a throwaway dev wallet with no real funds.
In production, the private key is fetched from AWS Secrets Manager at startup:
- Create a secret in AWS Secrets Manager:
- Secret name:
cropchain/blockchain-private-key - Secret value (JSON):
- Secret name:
{ "private_key": "0x...your_production_key..." }-
Grant your EC2 / ECS task role
secretsmanager:GetSecretValueon that ARN. -
Set these environment variables on your server (not
.env):
NODE_ENV=production AWS_SECRET_ARN=arn:aws:secretsmanager:REGION:ACCOUNT:secret:cropchain/blockchain-private-key AWS_REGION=us-east-1
- Do not set
PRIVATE_KEYβ the server will refuse to start if it is present.
The server performs a startup check and exits immediately if production is misconfigured, preventing accidental deploys with an exposed key.
- Basic supply chain tracking
- QR code generation and scanning
- Multi-role interfaces
- Admin dashboard
- AI-powered chatbot assistant
- Offline-first data logging with background sync
- Service Worker background sync
- Progressive Web App (PWA)
- IoT Sensor Integration
- Advanced analytics and reporting
- Mobile app development
- Multi-language support
- Enhanced AI capabilities (voice, image recognition)
- AI-powered quality prediction
- Carbon footprint tracking
- Marketplace integration
- Government compliance features
- Predictive supply chain analytics
- Offline image caching and compression
I welcome contributions!
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the Apache License 2.0 - see the LICENSE file for further details.
- OpenZeppelin for smart contract libraries
- Infura/Alchemy for blockchain infrastructure
- The amazing open-source community
- Agricultural experts who provided domain knowledge
Built with love for transparent agriculture and food safety
CropChain - Connecting farms to forks with blockchain transparency
- Improve heading hierarchy for better readability
- Ensure consistent spacing between sections
- Use proper Markdown formatting for code blocks and lists
- Align all installation and usage steps properly
- Introduction
- Features
- Tech Stack
- Installation
- Usage
- Project Structure
- Contribution Guidelines
- License
- Add badges (optional): build, license, contributors
- Add screenshots for better UI understanding
- Standardize code blocks for commands
Improve onboarding experience for new contributors and users by making README more structured, readable, and professional.