Dikshyan/CarbonLedger-CarbonCredits

TypeScript

0

59 commits

updated Oct 2, 2026

See the code

README

🌱 BlueChain β€” Blue Carbon MRV & Tokenized Decentralized Registry

React Django FastAPI Solidity IPFS TypeScript License: MIT

Developed for the Smart India Hackathon (SIH)
BlueChain is an end-to-end, blockchain-powered Blue Carbon Monitoring, Reporting, and Verification (MRV) platform. It combines satellite Earth observation (Sentinel-2 via Google Earth Engine), automated IPCC carbon sequestration modeling, an immutable verification workflow, and on-chain tokenization on Polygon to eliminate greenwashing and accelerate coastal restoration finance.


πŸ“‘ Table of Contents


🌊 Problem Statement & Solution

The Challenge

  • High Sequestration Potential: Coastal ecosystems (mangroves, tidal marshes, and seagrass beds) sequester carbon up to 10Γ— faster and store up to 5Γ— more carbon per hectare than terrestrial tropical rainforests.
  • Flawed Traditional MRV: Manual ecological field audits take 12 to 18 months, cost tens of thousands of dollars, lack transparency, and rely on static paper reports vulnerable to data manipulation, greenwashing, and double-counting.
  • Market Liquidity Bottleneck: Small restoration NGOs struggle to access global carbon markets, while enterprise buyers face severe transparency and authenticity risks.

The BlueChain Solution

  1. Automated Satellite MRV: Analyzes multi-spectral Sentinel-2 satellite imagery through Google Earth Engine (GEE) to calculate NDVI, classify mangrove canopy density, and compute biomass sequestration using IPCC Wetlands Supplement standards.
  2. Transparent 4-Stage Governance: Robust role-based verification lifecycle ensuring strict separation of powers between NGOs, Independent Verifiers, Platform Admins, and Buyers.
  3. Decentralized Audit Trail: Verified ecological reports and transaction receipts are pinned to IPFS (via Pinata) with cryptographic CID hashes permanently anchored to the Polygon blockchain.
  4. Tokenized Carbon Credit Marketplace: Direct on-chain minting of verified credits into ERC-20 tokens, enabling real-time purchasing, wallet-to-wallet transfers, and irrevocable retirement to prevent double-spending.

✨ Key Features

CapabilityDescription
πŸ›°οΈ AI Explorer & Geospatial MappingInteractive Leaflet-powered satellite map with polygon boundary drawing, real-time vegetation indices (NDVI, NDWI, EVI, MNDWI), and automatic carbon potential estimation.
πŸ›‘οΈ Role-Based Access Control (RBAC)Dedicated portal views and permissions for Admin, Government Official (Verifier), NGO Representative, and Company Buyer.
πŸ“‹ Full Lifecycle Project State MachineComplete review state transitions (Pending βž” Under Review βž” Correction Required βž” Verified or Rejected) with full verifier feedback integration.
πŸ”„ NGO Edit & Resubmit WorkflowWhen corrections are requested, NGOs review the verifier's feedback, update permitted project metadata, and resubmit directly back to the assigned verifier without losing assignment context.
πŸ”’ Tamper-Proof Protected FieldsCritical fields (status, assigned_verifier, verifier_notes, verified_at, active, created_by) are strictly protected at the API level against unauthorized direct modifications.
⛓️ Web3 Carbon Credit MintingVerified projects can be minted directly onto Polygon Amoy / local Hardhat EVM contracts by authorized verifiers or admins.
πŸ›’ Carbon Credit MarketplacePublic registry browsing, live credit pricing, MetaMask wallet integration, credit purchase execution, and permanent token retirement.
πŸ“Š Dynamic Analytical DashboardsRole-tailored dashboard statistics, real-time credit issuance summaries, project state breakdowns, and PDF MRV report downloads.

πŸ›οΈ System Architecture

flowchart TB
    subgraph Client["Frontend Client (React + Vite + TypeScript)"]
        UI["Web Portal (Dashboard, AI Explorer, Marketplace, Review Queue)"]
        MetaMask["MetaMask Wallet (Web3 Provider)"]
    end

    subgraph BackendGateway["Django REST API (Port 8000)"]
        Auth["JWT Auth & Role Guard"]
        ProjMgr["Project & Company Manager"]
        Workflow["Verification State Machine Engine"]
        TxMgr["Carbon Transaction Ledger"]
        PDF["MRV Report Generator"]
    end

    subgraph AIService["AI & Remote Sensing Engine (FastAPI - Port 8001)"]
        GEE["Google Earth Engine API"]
        Sentinel["Sentinel-2 Multispectral Ingestion"]
        NDVI["Spectral Indices (NDVI, NDWI, EVI)"]
        CarbonEst["IPCC Wetland Carbon Biomass Estimator"]
    end

    subgraph DecentralizedLayer["Decentralized Storage & Blockchain"]
        IPFS["Pinata IPFS Gateway (Metadata & Reports)"]
        HardhatNode["Hardhat Node / Polygon Network (Port 8545)"]
        Contract["CarbonLedger.sol (ERC-20 Token & Registry)"]
    end

    UI -->|REST API / JWT| Auth
    UI -->|Web3 RPC / Ethers.js| MetaMask
    MetaMask -->|Contract Calls| Contract
    
    Auth --> ProjMgr
    ProjMgr --> Workflow
    Workflow --> TxMgr
    TxMgr --> PDF

    UI -->|Geospatial Analysis| AIService
    AIService --> GEE
    GEE --> Sentinel
    Sentinel --> NDVI --> CarbonEst

    TxMgr -->|Pin Report CIDs| IPFS
    TxMgr -->|Sync Mint & Transfer Events| Contract
    Contract --> HardhatNode

πŸ”„ Project Verification Workflow

The verification pipeline enforces a strict state machine across all roles:

stateDiagram-v2
    [*] --> Pending: NGO Registers Project
    
    Pending --> UnderReview: Admin Assigns Verifier
    
    state UnderReview {
        [*] --> InReview
        InReview --> VerifierReview: Inspect Satellite MRV & Ground Data
    }
    
    UnderReview --> Verified: Verifier Approves (verified_at set, active=True)
    UnderReview --> CorrectionRequired: Verifier Requests Changes (Notes Required)
    UnderReview --> Rejected: Verifier Rejects (active=False, Notes Required)
    
    CorrectionRequired --> UnderReview: NGO Edits Metadata & Resubmits
    
    Verified --> Minted: Verifier/Admin Mints ERC-20 Credits
    Minted --> Marketplace: Credits Listed for Purchase
    Marketplace --> Retired: Buyer Retires Credits
    
    Rejected --> [*]
    Retired --> [*]

πŸ› οΈ Tech Stack

Frontend

  • Framework: React 19, Vite, TypeScript
  • Styling & UI: Tailwind CSS, Radix UI primitives, Lucide Icons, Framer Motion
  • Routing & State: Wouter, React Context API
  • Web3 & Maps: Ethers.js v6, Leaflet, Turf.js, Chart.js

Backend API

  • Framework: Django 5.x, Django REST Framework (DRF)
  • Authentication: djangorestframework-simplejwt (JWT Access & Refresh Tokens)
  • Database: SQLite (default / dev) / PostgreSQL / MongoDB
  • CORS & Middleware: django-cors-headers

AI & Satellite Remote Sensing

  • Framework: FastAPI, Uvicorn, Python 3.10+
  • Earth Observation: Google Earth Engine (earthengine-api), Copernicus Sentinel-2 Level-2A
  • Scientific Computing: NumPy, Pandas, Scikit-learn, GeoPandas, Shapely, Rasterio

Blockchain & Decentralized Storage

  • Smart Contracts: Solidity ^0.8.20, OpenZeppelin Contracts
  • Development Tooling: Hardhat, Ethers.js, Node.js
  • Network Targets: Local Hardhat EVM Node, Polygon Amoy Testnet, Polygon Mainnet
  • Decentralized Storage: Pinata IPFS (JSON metadata & MRV audit pinning)

πŸ“‚ Repository Structure

BlueChain/
β”œβ”€β”€ ai-service/                  # FastAPI Remote Sensing & Carbon Modeling Service
β”‚   β”œβ”€β”€ api/                     # REST API routers & schemas
β”‚   β”‚   └── routes.py            # Point & polygon analysis endpoints
β”‚   β”œβ”€β”€ carbon/                  # IPCC carbon density & biomass calculators
β”‚   β”œβ”€β”€ gee/                     # Google Earth Engine Sentinel-2 connectors
β”‚   β”œβ”€β”€ models/                  # Pydantic request & response models
β”‚   β”œβ”€β”€ ndvi/                    # Spectral index calculators (NDVI, NDWI, EVI, MNDWI)
β”‚   β”œβ”€β”€ app.py                   # FastAPI application initialization & GEE startup
β”‚   └── requirements.txt         # AI service Python dependencies
β”‚
β”œβ”€β”€ backend/                     # Django REST Framework Central API
β”‚   β”œβ”€β”€ api/                     # Main BlueChain application
β”‚   β”‚   β”œβ”€β”€ migrations/          # Database schema migrations
β”‚   β”‚   β”œβ”€β”€ models.py            # Company, User/Profile, CarbonTransaction, PricingConfig
β”‚   β”‚   β”œβ”€β”€ serializers.py       # DRF serializers & validation rules
β”‚   β”‚   β”œβ”€β”€ views.py             # ViewSets, review actions, resubmit, & minting views
β”‚   β”‚   β”œβ”€β”€ urls.py              # Sub-router API endpoint mapping
β”‚   β”‚   β”œβ”€β”€ permissions.py       # RBAC role permissions
β”‚   β”‚   └── pinata.py            # IPFS pinning client & fallback handler
β”‚   β”œβ”€β”€ clapi/                   # Django project configuration & settings
β”‚   β”‚   β”œβ”€β”€ settings.py          # App settings, DB config, JWT & CORS setup
β”‚   β”‚   └── urls.py              # Root URL router (/api/v1/)
β”‚   β”œβ”€β”€ manage.py                # Django CLI entrypoint
β”‚   └── requirements.txt         # Backend Python dependencies
β”‚
β”œβ”€β”€ blockchain/                  # Hardhat EVM & Smart Contract Environment
β”‚   β”œβ”€β”€ contracts/               # Solidity smart contracts
β”‚   β”‚   └── CarbonLedger.sol     # ERC-20 token, registry, & verification contract
β”‚   β”œβ”€β”€ scripts/                 # Deployment and transaction scripts
β”‚   β”‚   β”œβ”€β”€ deploy.js            # Contract deployment script
β”‚   β”‚   β”œβ”€β”€ mintCreditsAmoy.js   # Credit minting script
β”‚   β”‚   └── transferCreditsAmoy.js
β”‚   β”œβ”€β”€ hardhat.config.ts        # Hardhat configuration (Solidity compiler & networks)
β”‚   └── package.json             # Blockchain development dependencies
β”‚
β”œβ”€β”€ frontend/                    # React 19 + Vite Frontend Application
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/          # Reusable UI components
β”‚   β”‚   β”‚   β”œβ”€β”€ Header.tsx       # Navigation bar with role-based routing
β”‚   β”‚   β”‚   β”œβ”€β”€ ProtectedRoute.tsx # Route security & RBAC guard
β”‚   β”‚   β”‚   β”œβ”€β”€ StatusBadge.tsx  # Color-coded workflow badge component
β”‚   β”‚   β”‚   β”œβ”€β”€ NGOEditResubmitModal.tsx # NGO metadata correction modal
β”‚   β”‚   β”‚   β”œβ”€β”€ VerifierReviewModal.tsx  # Verifier approval/rejection modal
β”‚   β”‚   β”‚   └── ui/              # Radix UI library components
β”‚   β”‚   β”œβ”€β”€ contexts/            # React AuthContext (JWT session management)
β”‚   β”‚   β”œβ”€β”€ lib/                 # API client utilities (apiFetch, token handling)
β”‚   β”‚   β”œβ”€β”€ pages/               # Main application views
β”‚   β”‚   β”‚   β”œβ”€β”€ LandingPage.tsx  # Hero landing page
β”‚   β”‚   β”‚   β”œβ”€β”€ Dashboard.tsx    # Role-tailored dashboard
β”‚   β”‚   β”‚   β”œβ”€β”€ AdminDashboard.tsx # Admin verifier assignment & user management
β”‚   β”‚   β”‚   β”œβ”€β”€ VerifierDashboard.tsx # Independent verification queue
β”‚   β”‚   β”‚   β”œβ”€β”€ Marketplace.tsx  # Carbon credit marketplace & purchasing
β”‚   β”‚   β”‚   β”œβ”€β”€ AiExplorer.tsx   # Geospatial satellite map analysis
β”‚   β”‚   β”‚   β”œβ”€β”€ ProjectRegistration.tsx # NGO project onboarding
β”‚   β”‚   β”‚   β”œβ”€β”€ Profile.tsx      # User profile, wallet, & project list
β”‚   β”‚   β”‚   β”œβ”€β”€ Login.tsx        # Authentication entry
β”‚   β”‚   β”‚   └── Register.tsx     # Public registration page
β”‚   β”‚   β”œβ”€β”€ App.tsx              # Main application router
β”‚   β”‚   └── main.tsx             # React DOM entrypoint
β”‚   β”œβ”€β”€ package.json             # Frontend dependencies
β”‚   └── vite.config.ts           # Vite build & proxy settings
β”‚
β”œβ”€β”€ docs/                        # Architecture & API documentation
β”œβ”€β”€ .env.example                 # Environment variable templates
β”œβ”€β”€ pnpm-workspace.yaml          # PNPM monorepo workspace definition
└── README.md                    # Project documentation

πŸš€ Getting Started & Installation

Prerequisites

  • Node.js v18.0.0+ or v20.0.0+
  • pnpm v9.0.0+ (Run npm install -g pnpm)
  • Python 3.10+ or 3.12+
  • Git
  • MetaMask Browser Extension (for Web3 features)

1. Backend Setup (Django REST Framework)

# Navigate to the backend directory
cd backend

# Create and activate a Python virtual environment
python -m venv .venv

# On Windows (PowerShell):
.\.venv\Scripts\Activate.ps1
# On Linux/macOS:
source .venv/bin/activate

# Install required dependencies
pip install -r requirements.txt

# Run migrations to initialize SQLite/PostgreSQL
python manage.py migrate

# (Optional) Create a superuser for Django admin
python manage.py createsuperuser

# Start the Django development server (runs on port 8000)
python manage.py runserver 8000

2. AI Service Setup (FastAPI + Google Earth Engine)

# Open a new terminal and navigate to ai-service
cd ai-service

# Create and activate virtual environment
python -m venv .venv

# On Windows (PowerShell):
.\.venv\Scripts\Activate.ps1
# On Linux/macOS:
source .venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# (Optional) Authenticate with Google Earth Engine
earthengine authenticate

# Start the FastAPI AI service (runs on port 8001)
uvicorn app:app --host 127.0.0.1 --port 8001 --reload

Note: If Google Earth Engine credentials are not configured, the service automatically runs in high-fidelity IPCC fallback mode for local testing without breaking any frontend workflows.


3. Blockchain Setup (Hardhat & Smart Contracts)

# Open a new terminal and navigate to blockchain
cd blockchain

# Install blockchain dependencies
pnpm install

# Start a local Hardhat Ethereum node (runs on port 8545)
pnpm hardhat node

In a separate terminal, deploy the CarbonLedger.sol contract to the local network:

cd blockchain
pnpm hardhat run scripts/deploy.js --network localhost

Copy the deployed contract address and add it to your .env files.


4. Frontend Setup (React + Vite)

# Open a new terminal and navigate to frontend
cd frontend

# Install frontend dependencies
pnpm install

# Start the Vite development server (runs on http://localhost:5173)
pnpm dev

Open your browser and navigate to http://localhost:5173.


βš™οΈ Environment Configuration

Copy the example environment configurations to their respective directories:

Backend (backend/.env)

DEBUG=True
SECRET_KEY=your-django-secret-key-here
ALLOWED_HOSTS=localhost,127.0.0.1
WEB3_PROVIDER_URL=http://127.0.0.1:8545
CONTRACT_ADDRESS=0x5FbDB2315678afecb367f032d93F642f64180aa3
PINATA_API_KEY=your-pinata-api-key
PINATA_SECRET_API_KEY=your-pinata-secret-key
PINATA_JWT=your-pinata-jwt-token
AI_SERVICE_URL=http://127.0.0.1:8001

AI Service (ai-service/.env)

GEE_PROJECT_ID=carbonledger-503508
GOOGLE_APPLICATION_CREDENTIALS=./auth/gee-credentials.json
MAPBOX_ACCESS_TOKEN=your-mapbox-token

Frontend (frontend/.env)

VITE_API_URL=http://127.0.0.1:8000/api/v1
VITE_AI_SERVICE_URL=http://127.0.0.1:8001
VITE_BLOCKCHAIN_RPC=http://127.0.0.1:8545
VITE_CONTRACT_ADDRESS=0x5FbDB2315678afecb367f032d93F642f64180aa3

πŸ“‘ API Reference

All backend endpoints are prefixed with /api/v1/:

πŸ” Authentication & Session

  • POST /api/v1/register/ β€” Register a new account (NGO Representative or Company Buyer).
  • POST /api/token/ β€” Obtain JWT access and refresh tokens.
  • POST /api/token/refresh/ β€” Refresh expired JWT access token.
  • GET /api/v1/me/ β€” Retrieve the currently authenticated profile and assigned role.

🌿 Projects & MRV Registry

  • GET /api/v1/CarbonLedger/ β€” List projects (scoped by role for NGOs/Buyers; platform-wide for Admin/Verifier; verified only for public marketplace).
  • POST /api/v1/CarbonLedger/ β€” Register a new blue carbon project (NGO only; initial status Pending).
  • GET /api/v1/CarbonLedger/<id>/ β€” Retrieve detailed project metadata and verifier feedback notes.
  • PATCH /api/v1/CarbonLedger/<id>/ β€” Update permitted project metadata (protected fields blocked).
  • GET /api/v1/CarbonLedger/<id>/report/ β€” Download generated PDF MRV report.

πŸ›‘οΈ Administrative & Verifier Actions

  • GET /api/v1/admin/users/ β€” List and create platform users (Admin only).
  • POST /api/v1/admin/projects/<id>/assign-verifier/ β€” Assign a Government Official to a Pending project (transitions to Under Review).
  • POST /api/v1/projects/<id>/review/ β€” Submit verifier review (action: "approve" | "request_correction" | "reject", with mandatory notes).
  • POST /api/v1/projects/<id>/resubmit/ β€” NGO resubmission of a Correction Required project (transitions to Under Review).
  • POST /api/v1/company/<id>/mint/ β€” Mint on-chain carbon credits for a Verified project (assigned Verifier or Admin only).

πŸ›’ Marketplace & Ledger

  • GET /api/v1/pricing/ β€” Get or update carbon credit benchmark price configuration.
  • POST /api/v1/CarbonLedgerTransactions/ β€” Execute a credit purchase (transaction_type: "Recieve") or retirement.
  • GET /api/v1/dashboard-stats/ β€” Real-time analytical statistics aggregated by user role.

πŸ›°οΈ AI Remote Sensing Service (Port 8001)

  • GET /health β€” Service status and Earth Engine connection state.
  • POST /api/v1/analyze/point β€” Point coordinate satellite analysis (NDVI mean, canopy cover %, carbon tonnes).
  • POST /api/v1/analyze β€” GeoJSON polygon boundary analysis and spatial carbon heatmaps.

πŸ‘₯ Role-Based Access Control (RBAC) Matrix

Feature / ActionAdminGovernment Official (Verifier)NGO RepresentativeCompany BuyerPublic (Guest)
Browse Marketplaceβœ…βœ…βœ…βœ…βœ…
Use AI Explorerβœ…βœ…βœ…βœ…βœ…
Register New ProjectβŒβŒβœ…βŒβŒ
Edit Project Metadataβœ… (All)βŒβœ… (Own Only)❌❌
Assign Verifierβœ…βŒβŒβŒβŒ
Review Project (Approve / Reject / Correction)βœ…βœ… (Assigned Only)❌❌❌
Resubmit Project (Correction Required)βŒβŒβœ… (Own Only)❌❌
Direct Status Override (PATCH)❌ (Blocked)❌ (Blocked)❌ (Blocked)❌ (Blocked)❌ (Blocked)
Mint Carbon Creditsβœ…βœ… (Assigned Only)❌❌❌
Purchase Carbon CreditsβŒβŒβŒβœ…βŒ
Access /admin Dashboardβœ…βŒβŒβŒβŒ
Access /verifier Review QueueβŒβœ…βŒβŒβŒ

πŸ§ͺ Testing & Quality Assurance

The codebase includes comprehensive static analysis and automated verification suites:

1. Backend Validation

cd backend
# Check system models and dependencies
python manage.py check

# Verify database migrations integrity
python manage.py makemigrations --check
python manage.py migrate --plan

2. Frontend Validation

cd frontend
# TypeScript static type check (0 errors)
pnpm tsc --noEmit

# Production bundle build test
pnpm build

3. Smart Contract Verification

cd blockchain
# Compile Solidity contracts
pnpm hardhat compile

# Run Hardhat test suite
pnpm hardhat test

🀝 Contributing & Team

Developed with pride for the Smart India Hackathon (SIH).

Development Guidelines

  • Always branch from develop (git checkout -b feature/your-feature-name).
  • Strictly adhere to role security rules: never bypass backend permissions for convenience.
  • Ensure all TypeScript types pass (pnpm tsc --noEmit) before opening a pull request.
  • Never commit secret keys, private keys, or .env files to git.

πŸ“œ License

This project is licensed under the MIT License β€” see the LICENSE file for details.

Dikshyan/CarbonLedger-CarbonCredits

TypeScript

0

59 commits

updated Oct 2, 2026

See the code

README

🌱 BlueChain β€” Blue Carbon MRV & Tokenized Decentralized Registry

React Django FastAPI Solidity IPFS TypeScript License: MIT

Developed for the Smart India Hackathon (SIH)
BlueChain is an end-to-end, blockchain-powered Blue Carbon Monitoring, Reporting, and Verification (MRV) platform. It combines satellite Earth observation (Sentinel-2 via Google Earth Engine), automated IPCC carbon sequestration modeling, an immutable verification workflow, and on-chain tokenization on Polygon to eliminate greenwashing and accelerate coastal restoration finance.


πŸ“‘ Table of Contents


🌊 Problem Statement & Solution

The Challenge

  • High Sequestration Potential: Coastal ecosystems (mangroves, tidal marshes, and seagrass beds) sequester carbon up to 10Γ— faster and store up to 5Γ— more carbon per hectare than terrestrial tropical rainforests.
  • Flawed Traditional MRV: Manual ecological field audits take 12 to 18 months, cost tens of thousands of dollars, lack transparency, and rely on static paper reports vulnerable to data manipulation, greenwashing, and double-counting.
  • Market Liquidity Bottleneck: Small restoration NGOs struggle to access global carbon markets, while enterprise buyers face severe transparency and authenticity risks.

The BlueChain Solution

  1. Automated Satellite MRV: Analyzes multi-spectral Sentinel-2 satellite imagery through Google Earth Engine (GEE) to calculate NDVI, classify mangrove canopy density, and compute biomass sequestration using IPCC Wetlands Supplement standards.
  2. Transparent 4-Stage Governance: Robust role-based verification lifecycle ensuring strict separation of powers between NGOs, Independent Verifiers, Platform Admins, and Buyers.
  3. Decentralized Audit Trail: Verified ecological reports and transaction receipts are pinned to IPFS (via Pinata) with cryptographic CID hashes permanently anchored to the Polygon blockchain.
  4. Tokenized Carbon Credit Marketplace: Direct on-chain minting of verified credits into ERC-20 tokens, enabling real-time purchasing, wallet-to-wallet transfers, and irrevocable retirement to prevent double-spending.

✨ Key Features

CapabilityDescription
πŸ›°οΈ AI Explorer & Geospatial MappingInteractive Leaflet-powered satellite map with polygon boundary drawing, real-time vegetation indices (NDVI, NDWI, EVI, MNDWI), and automatic carbon potential estimation.
πŸ›‘οΈ Role-Based Access Control (RBAC)Dedicated portal views and permissions for Admin, Government Official (Verifier), NGO Representative, and Company Buyer.
πŸ“‹ Full Lifecycle Project State MachineComplete review state transitions (Pending βž” Under Review βž” Correction Required βž” Verified or Rejected) with full verifier feedback integration.
πŸ”„ NGO Edit & Resubmit WorkflowWhen corrections are requested, NGOs review the verifier's feedback, update permitted project metadata, and resubmit directly back to the assigned verifier without losing assignment context.
πŸ”’ Tamper-Proof Protected FieldsCritical fields (status, assigned_verifier, verifier_notes, verified_at, active, created_by) are strictly protected at the API level against unauthorized direct modifications.
⛓️ Web3 Carbon Credit MintingVerified projects can be minted directly onto Polygon Amoy / local Hardhat EVM contracts by authorized verifiers or admins.
πŸ›’ Carbon Credit MarketplacePublic registry browsing, live credit pricing, MetaMask wallet integration, credit purchase execution, and permanent token retirement.
πŸ“Š Dynamic Analytical DashboardsRole-tailored dashboard statistics, real-time credit issuance summaries, project state breakdowns, and PDF MRV report downloads.

πŸ›οΈ System Architecture

flowchart TB
    subgraph Client["Frontend Client (React + Vite + TypeScript)"]
        UI["Web Portal (Dashboard, AI Explorer, Marketplace, Review Queue)"]
        MetaMask["MetaMask Wallet (Web3 Provider)"]
    end

    subgraph BackendGateway["Django REST API (Port 8000)"]
        Auth["JWT Auth & Role Guard"]
        ProjMgr["Project & Company Manager"]
        Workflow["Verification State Machine Engine"]
        TxMgr["Carbon Transaction Ledger"]
        PDF["MRV Report Generator"]
    end

    subgraph AIService["AI & Remote Sensing Engine (FastAPI - Port 8001)"]
        GEE["Google Earth Engine API"]
        Sentinel["Sentinel-2 Multispectral Ingestion"]
        NDVI["Spectral Indices (NDVI, NDWI, EVI)"]
        CarbonEst["IPCC Wetland Carbon Biomass Estimator"]
    end

    subgraph DecentralizedLayer["Decentralized Storage & Blockchain"]
        IPFS["Pinata IPFS Gateway (Metadata & Reports)"]
        HardhatNode["Hardhat Node / Polygon Network (Port 8545)"]
        Contract["CarbonLedger.sol (ERC-20 Token & Registry)"]
    end

    UI -->|REST API / JWT| Auth
    UI -->|Web3 RPC / Ethers.js| MetaMask
    MetaMask -->|Contract Calls| Contract
    
    Auth --> ProjMgr
    ProjMgr --> Workflow
    Workflow --> TxMgr
    TxMgr --> PDF

    UI -->|Geospatial Analysis| AIService
    AIService --> GEE
    GEE --> Sentinel
    Sentinel --> NDVI --> CarbonEst

    TxMgr -->|Pin Report CIDs| IPFS
    TxMgr -->|Sync Mint & Transfer Events| Contract
    Contract --> HardhatNode

πŸ”„ Project Verification Workflow

The verification pipeline enforces a strict state machine across all roles:

stateDiagram-v2
    [*] --> Pending: NGO Registers Project
    
    Pending --> UnderReview: Admin Assigns Verifier
    
    state UnderReview {
        [*] --> InReview
        InReview --> VerifierReview: Inspect Satellite MRV & Ground Data
    }
    
    UnderReview --> Verified: Verifier Approves (verified_at set, active=True)
    UnderReview --> CorrectionRequired: Verifier Requests Changes (Notes Required)
    UnderReview --> Rejected: Verifier Rejects (active=False, Notes Required)
    
    CorrectionRequired --> UnderReview: NGO Edits Metadata & Resubmits
    
    Verified --> Minted: Verifier/Admin Mints ERC-20 Credits
    Minted --> Marketplace: Credits Listed for Purchase
    Marketplace --> Retired: Buyer Retires Credits
    
    Rejected --> [*]
    Retired --> [*]

πŸ› οΈ Tech Stack

Frontend

  • Framework: React 19, Vite, TypeScript
  • Styling & UI: Tailwind CSS, Radix UI primitives, Lucide Icons, Framer Motion
  • Routing & State: Wouter, React Context API
  • Web3 & Maps: Ethers.js v6, Leaflet, Turf.js, Chart.js

Backend API

  • Framework: Django 5.x, Django REST Framework (DRF)
  • Authentication: djangorestframework-simplejwt (JWT Access & Refresh Tokens)
  • Database: SQLite (default / dev) / PostgreSQL / MongoDB
  • CORS & Middleware: django-cors-headers

AI & Satellite Remote Sensing

  • Framework: FastAPI, Uvicorn, Python 3.10+
  • Earth Observation: Google Earth Engine (earthengine-api), Copernicus Sentinel-2 Level-2A
  • Scientific Computing: NumPy, Pandas, Scikit-learn, GeoPandas, Shapely, Rasterio

Blockchain & Decentralized Storage

  • Smart Contracts: Solidity ^0.8.20, OpenZeppelin Contracts
  • Development Tooling: Hardhat, Ethers.js, Node.js
  • Network Targets: Local Hardhat EVM Node, Polygon Amoy Testnet, Polygon Mainnet
  • Decentralized Storage: Pinata IPFS (JSON metadata & MRV audit pinning)

πŸ“‚ Repository Structure

BlueChain/
β”œβ”€β”€ ai-service/                  # FastAPI Remote Sensing & Carbon Modeling Service
β”‚   β”œβ”€β”€ api/                     # REST API routers & schemas
β”‚   β”‚   └── routes.py            # Point & polygon analysis endpoints
β”‚   β”œβ”€β”€ carbon/                  # IPCC carbon density & biomass calculators
β”‚   β”œβ”€β”€ gee/                     # Google Earth Engine Sentinel-2 connectors
β”‚   β”œβ”€β”€ models/                  # Pydantic request & response models
β”‚   β”œβ”€β”€ ndvi/                    # Spectral index calculators (NDVI, NDWI, EVI, MNDWI)
β”‚   β”œβ”€β”€ app.py                   # FastAPI application initialization & GEE startup
β”‚   └── requirements.txt         # AI service Python dependencies
β”‚
β”œβ”€β”€ backend/                     # Django REST Framework Central API
β”‚   β”œβ”€β”€ api/                     # Main BlueChain application
β”‚   β”‚   β”œβ”€β”€ migrations/          # Database schema migrations
β”‚   β”‚   β”œβ”€β”€ models.py            # Company, User/Profile, CarbonTransaction, PricingConfig
β”‚   β”‚   β”œβ”€β”€ serializers.py       # DRF serializers & validation rules
β”‚   β”‚   β”œβ”€β”€ views.py             # ViewSets, review actions, resubmit, & minting views
β”‚   β”‚   β”œβ”€β”€ urls.py              # Sub-router API endpoint mapping
β”‚   β”‚   β”œβ”€β”€ permissions.py       # RBAC role permissions
β”‚   β”‚   └── pinata.py            # IPFS pinning client & fallback handler
β”‚   β”œβ”€β”€ clapi/                   # Django project configuration & settings
β”‚   β”‚   β”œβ”€β”€ settings.py          # App settings, DB config, JWT & CORS setup
β”‚   β”‚   └── urls.py              # Root URL router (/api/v1/)
β”‚   β”œβ”€β”€ manage.py                # Django CLI entrypoint
β”‚   └── requirements.txt         # Backend Python dependencies
β”‚
β”œβ”€β”€ blockchain/                  # Hardhat EVM & Smart Contract Environment
β”‚   β”œβ”€β”€ contracts/               # Solidity smart contracts
β”‚   β”‚   └── CarbonLedger.sol     # ERC-20 token, registry, & verification contract
β”‚   β”œβ”€β”€ scripts/                 # Deployment and transaction scripts
β”‚   β”‚   β”œβ”€β”€ deploy.js            # Contract deployment script
β”‚   β”‚   β”œβ”€β”€ mintCreditsAmoy.js   # Credit minting script
β”‚   β”‚   └── transferCreditsAmoy.js
β”‚   β”œβ”€β”€ hardhat.config.ts        # Hardhat configuration (Solidity compiler & networks)
β”‚   └── package.json             # Blockchain development dependencies
β”‚
β”œβ”€β”€ frontend/                    # React 19 + Vite Frontend Application
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/          # Reusable UI components
β”‚   β”‚   β”‚   β”œβ”€β”€ Header.tsx       # Navigation bar with role-based routing
β”‚   β”‚   β”‚   β”œβ”€β”€ ProtectedRoute.tsx # Route security & RBAC guard
β”‚   β”‚   β”‚   β”œβ”€β”€ StatusBadge.tsx  # Color-coded workflow badge component
β”‚   β”‚   β”‚   β”œβ”€β”€ NGOEditResubmitModal.tsx # NGO metadata correction modal
β”‚   β”‚   β”‚   β”œβ”€β”€ VerifierReviewModal.tsx  # Verifier approval/rejection modal
β”‚   β”‚   β”‚   └── ui/              # Radix UI library components
β”‚   β”‚   β”œβ”€β”€ contexts/            # React AuthContext (JWT session management)
β”‚   β”‚   β”œβ”€β”€ lib/                 # API client utilities (apiFetch, token handling)
β”‚   β”‚   β”œβ”€β”€ pages/               # Main application views
β”‚   β”‚   β”‚   β”œβ”€β”€ LandingPage.tsx  # Hero landing page
β”‚   β”‚   β”‚   β”œβ”€β”€ Dashboard.tsx    # Role-tailored dashboard
β”‚   β”‚   β”‚   β”œβ”€β”€ AdminDashboard.tsx # Admin verifier assignment & user management
β”‚   β”‚   β”‚   β”œβ”€β”€ VerifierDashboard.tsx # Independent verification queue
β”‚   β”‚   β”‚   β”œβ”€β”€ Marketplace.tsx  # Carbon credit marketplace & purchasing
β”‚   β”‚   β”‚   β”œβ”€β”€ AiExplorer.tsx   # Geospatial satellite map analysis
β”‚   β”‚   β”‚   β”œβ”€β”€ ProjectRegistration.tsx # NGO project onboarding
β”‚   β”‚   β”‚   β”œβ”€β”€ Profile.tsx      # User profile, wallet, & project list
β”‚   β”‚   β”‚   β”œβ”€β”€ Login.tsx        # Authentication entry
β”‚   β”‚   β”‚   └── Register.tsx     # Public registration page
β”‚   β”‚   β”œβ”€β”€ App.tsx              # Main application router
β”‚   β”‚   └── main.tsx             # React DOM entrypoint
β”‚   β”œβ”€β”€ package.json             # Frontend dependencies
β”‚   └── vite.config.ts           # Vite build & proxy settings
β”‚
β”œβ”€β”€ docs/                        # Architecture & API documentation
β”œβ”€β”€ .env.example                 # Environment variable templates
β”œβ”€β”€ pnpm-workspace.yaml          # PNPM monorepo workspace definition
└── README.md                    # Project documentation

πŸš€ Getting Started & Installation

Prerequisites

  • Node.js v18.0.0+ or v20.0.0+
  • pnpm v9.0.0+ (Run npm install -g pnpm)
  • Python 3.10+ or 3.12+
  • Git
  • MetaMask Browser Extension (for Web3 features)

1. Backend Setup (Django REST Framework)

# Navigate to the backend directory
cd backend

# Create and activate a Python virtual environment
python -m venv .venv

# On Windows (PowerShell):
.\.venv\Scripts\Activate.ps1
# On Linux/macOS:
source .venv/bin/activate

# Install required dependencies
pip install -r requirements.txt

# Run migrations to initialize SQLite/PostgreSQL
python manage.py migrate

# (Optional) Create a superuser for Django admin
python manage.py createsuperuser

# Start the Django development server (runs on port 8000)
python manage.py runserver 8000

2. AI Service Setup (FastAPI + Google Earth Engine)

# Open a new terminal and navigate to ai-service
cd ai-service

# Create and activate virtual environment
python -m venv .venv

# On Windows (PowerShell):
.\.venv\Scripts\Activate.ps1
# On Linux/macOS:
source .venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# (Optional) Authenticate with Google Earth Engine
earthengine authenticate

# Start the FastAPI AI service (runs on port 8001)
uvicorn app:app --host 127.0.0.1 --port 8001 --reload

Note: If Google Earth Engine credentials are not configured, the service automatically runs in high-fidelity IPCC fallback mode for local testing without breaking any frontend workflows.


3. Blockchain Setup (Hardhat & Smart Contracts)

# Open a new terminal and navigate to blockchain
cd blockchain

# Install blockchain dependencies
pnpm install

# Start a local Hardhat Ethereum node (runs on port 8545)
pnpm hardhat node

In a separate terminal, deploy the CarbonLedger.sol contract to the local network:

cd blockchain
pnpm hardhat run scripts/deploy.js --network localhost

Copy the deployed contract address and add it to your .env files.


4. Frontend Setup (React + Vite)

# Open a new terminal and navigate to frontend
cd frontend

# Install frontend dependencies
pnpm install

# Start the Vite development server (runs on http://localhost:5173)
pnpm dev

Open your browser and navigate to http://localhost:5173.


βš™οΈ Environment Configuration

Copy the example environment configurations to their respective directories:

Backend (backend/.env)

DEBUG=True
SECRET_KEY=your-django-secret-key-here
ALLOWED_HOSTS=localhost,127.0.0.1
WEB3_PROVIDER_URL=http://127.0.0.1:8545
CONTRACT_ADDRESS=0x5FbDB2315678afecb367f032d93F642f64180aa3
PINATA_API_KEY=your-pinata-api-key
PINATA_SECRET_API_KEY=your-pinata-secret-key
PINATA_JWT=your-pinata-jwt-token
AI_SERVICE_URL=http://127.0.0.1:8001

AI Service (ai-service/.env)

GEE_PROJECT_ID=carbonledger-503508
GOOGLE_APPLICATION_CREDENTIALS=./auth/gee-credentials.json
MAPBOX_ACCESS_TOKEN=your-mapbox-token

Frontend (frontend/.env)

VITE_API_URL=http://127.0.0.1:8000/api/v1
VITE_AI_SERVICE_URL=http://127.0.0.1:8001
VITE_BLOCKCHAIN_RPC=http://127.0.0.1:8545
VITE_CONTRACT_ADDRESS=0x5FbDB2315678afecb367f032d93F642f64180aa3

πŸ“‘ API Reference

All backend endpoints are prefixed with /api/v1/:

πŸ” Authentication & Session

  • POST /api/v1/register/ β€” Register a new account (NGO Representative or Company Buyer).
  • POST /api/token/ β€” Obtain JWT access and refresh tokens.
  • POST /api/token/refresh/ β€” Refresh expired JWT access token.
  • GET /api/v1/me/ β€” Retrieve the currently authenticated profile and assigned role.

🌿 Projects & MRV Registry

  • GET /api/v1/CarbonLedger/ β€” List projects (scoped by role for NGOs/Buyers; platform-wide for Admin/Verifier; verified only for public marketplace).
  • POST /api/v1/CarbonLedger/ β€” Register a new blue carbon project (NGO only; initial status Pending).
  • GET /api/v1/CarbonLedger/<id>/ β€” Retrieve detailed project metadata and verifier feedback notes.
  • PATCH /api/v1/CarbonLedger/<id>/ β€” Update permitted project metadata (protected fields blocked).
  • GET /api/v1/CarbonLedger/<id>/report/ β€” Download generated PDF MRV report.

πŸ›‘οΈ Administrative & Verifier Actions

  • GET /api/v1/admin/users/ β€” List and create platform users (Admin only).
  • POST /api/v1/admin/projects/<id>/assign-verifier/ β€” Assign a Government Official to a Pending project (transitions to Under Review).
  • POST /api/v1/projects/<id>/review/ β€” Submit verifier review (action: "approve" | "request_correction" | "reject", with mandatory notes).
  • POST /api/v1/projects/<id>/resubmit/ β€” NGO resubmission of a Correction Required project (transitions to Under Review).
  • POST /api/v1/company/<id>/mint/ β€” Mint on-chain carbon credits for a Verified project (assigned Verifier or Admin only).

πŸ›’ Marketplace & Ledger

  • GET /api/v1/pricing/ β€” Get or update carbon credit benchmark price configuration.
  • POST /api/v1/CarbonLedgerTransactions/ β€” Execute a credit purchase (transaction_type: "Recieve") or retirement.
  • GET /api/v1/dashboard-stats/ β€” Real-time analytical statistics aggregated by user role.

πŸ›°οΈ AI Remote Sensing Service (Port 8001)

  • GET /health β€” Service status and Earth Engine connection state.
  • POST /api/v1/analyze/point β€” Point coordinate satellite analysis (NDVI mean, canopy cover %, carbon tonnes).
  • POST /api/v1/analyze β€” GeoJSON polygon boundary analysis and spatial carbon heatmaps.

πŸ‘₯ Role-Based Access Control (RBAC) Matrix

Feature / ActionAdminGovernment Official (Verifier)NGO RepresentativeCompany BuyerPublic (Guest)
Browse Marketplaceβœ…βœ…βœ…βœ…βœ…
Use AI Explorerβœ…βœ…βœ…βœ…βœ…
Register New ProjectβŒβŒβœ…βŒβŒ
Edit Project Metadataβœ… (All)βŒβœ… (Own Only)❌❌
Assign Verifierβœ…βŒβŒβŒβŒ
Review Project (Approve / Reject / Correction)βœ…βœ… (Assigned Only)❌❌❌
Resubmit Project (Correction Required)βŒβŒβœ… (Own Only)❌❌
Direct Status Override (PATCH)❌ (Blocked)❌ (Blocked)❌ (Blocked)❌ (Blocked)❌ (Blocked)
Mint Carbon Creditsβœ…βœ… (Assigned Only)❌❌❌
Purchase Carbon CreditsβŒβŒβŒβœ…βŒ
Access /admin Dashboardβœ…βŒβŒβŒβŒ
Access /verifier Review QueueβŒβœ…βŒβŒβŒ

πŸ§ͺ Testing & Quality Assurance

The codebase includes comprehensive static analysis and automated verification suites:

1. Backend Validation

cd backend
# Check system models and dependencies
python manage.py check

# Verify database migrations integrity
python manage.py makemigrations --check
python manage.py migrate --plan

2. Frontend Validation

cd frontend
# TypeScript static type check (0 errors)
pnpm tsc --noEmit

# Production bundle build test
pnpm build

3. Smart Contract Verification

cd blockchain
# Compile Solidity contracts
pnpm hardhat compile

# Run Hardhat test suite
pnpm hardhat test

🀝 Contributing & Team

Developed with pride for the Smart India Hackathon (SIH).

Development Guidelines

  • Always branch from develop (git checkout -b feature/your-feature-name).
  • Strictly adhere to role security rules: never bypass backend permissions for convenience.
  • Ensure all TypeScript types pass (pnpm tsc --noEmit) before opening a pull request.
  • Never commit secret keys, private keys, or .env files to git.

πŸ“œ License

This project is licensed under the MIT License β€” see the LICENSE file for details.