GreenCoin Platform Documentation
Port: 3000
Features: CORS, Rate Limiting, Error Handling
Host: localhost:3306
Database: greencoin
Port: 5173
UI: Radix UI + Tailwind CSS
Port: 8080
Features: Notifications, Maps, Mobile
Port: 5175
Mobile: Android APK Support
Types: System, Farm, Credit, Verification
- Additional Revenue Stream: Earn $15-50 per ton of CO₂ sequestered annually
- Premium Pricing: Access to verified carbon credit markets with transparent pricing
- Long-term Contracts: Multi-year agreements provide income stability
- Performance Bonuses: Extra rewards for exceeding sequestration targets
- Soil Health Improvement: Increased organic matter and water retention
- Biodiversity Enhancement: Support for beneficial insects and wildlife
- Water Quality Protection: Reduced runoff and nutrient leaching
- Climate Resilience: Better adaptation to weather extremes
- Farm size: Minimum 0.5 hectares, maximum 1,000 hectares
- Location: Currently available in Kenya, Uganda, Tanzania, and Ghana
- Land tenure: Valid ownership or long-term lease agreement (minimum 5 years)
- Practice adoption: Commitment to implement eligible climate-smart practices
- Baseline data: Willingness to participate in initial soil sampling and surveys
🔬 Soil Sampling Protocol
- Collect soil cores from representative plots using systematic grid sampling
- Sample depths: 0-15cm, 15-30cm, and 30-45cm for comprehensive analysis
- Laboratory analysis includes Soil Organic Carbon (SOC), bulk density, and pH
- Sampling frequency: Baseline + annual monitoring for 5 years
- Quality control: 10% duplicate samples and certified reference materials
🌳 Biomass Measurement
- Tree diameter at breast height (DBH) and total height measurements
- Species-specific allometric equations for accurate carbon estimates
- Above-ground and below-ground biomass calculations
- Canopy cover assessment using densiometer or mobile apps
📋 Activity Documentation
- Detailed logs of tillage operations, fertilizer applications, and crop rotations
- GPS-tagged photos of field conditions and practice implementation
- Weather data integration from local meteorological stations
- Mobile app for real-time data collection and farmer reporting
| Tool/Method | Purpose | Accuracy | Cost |
|---|---|---|---|
| COMET-Farm | USDA-developed model for soil carbon and GHG emissions | ±15-20% | Free |
| Cool Farm Tool | Global web calculator for farm-level carbon footprints | ±20-25% | Free |
| EX-ACT | FAO carbon balance estimator for land use projects | ±25-30% | Free |
| ALU Tool | Land use change and GHG emission analysis | ±20% | Licensed |
| Satellite Analytics | NDVI, soil moisture, and vegetation monitoring | ±10-15% | Moderate |
🛰️ Remote Sensing Integration
- Sentinel-2: 10m resolution for crop monitoring and land use verification
- Landsat 8/9: Long-term historical analysis and change detection
- Planet Labs: Daily 3m imagery for detailed practice verification
- Soil moisture data: SMAP satellite integration for drought monitoring
- Tier 1 Farms (>100 hectares): Direct measurement with annual soil sampling
- Tier 2 Farms (10-100 hectares): Modeling with periodic verification sampling
- Tier 3 Farms (<10 hectares): Pure modeling approach with satellite monitoring
- Quality Assurance: 5% random verification sampling across all tiers
Potential: 0.5-1.5 tons CO₂/ha/year
Payment: $25-40 per ton
Potential: 0.3-1.0 tons CO₂/ha/year
Payment: $20-35 per ton
Potential: 2.0-8.0 tons CO₂/ha/year
Payment: $30-50 per ton
Potential: 0.2-0.8 tons CO₂/ha/year
Payment: $15-30 per ton
Potential: 0.4-1.2 tons CO₂/ha/year
Payment: $20-35 per ton
Potential: 0.1-0.5 tons CO₂/ha/year
Payment: $15-25 per ton
- VCS (Verified Carbon Standard): Primary methodology for project validation
- Gold Standard: Enhanced requirements for sustainable development co-benefits
- ISO 14064: International standard for GHG quantification and reporting
- IPCC Guidelines: 2006 IPCC Guidelines for National GHG Inventories
| Carbon Pool | Measurement Method | Frequency | Uncertainty |
|---|---|---|---|
| Soil Organic Carbon | Laboratory analysis (Walkley-Black method) | Annual | ±5-10% |
| Above-ground Biomass | Allometric equations, drone imagery | Bi-annual | ±10-15% |
| Below-ground Biomass | Root:shoot ratios, soil coring | Annual | ±15-25% |
| Deadwood | Direct measurement, decay models | Annual | ±20-30% |
| Litter | Quadrat sampling, dry weight | Seasonal | ±15-20% |
// Carbon sequestration calculation example
function calculateCarbonSequestration(farmData) {
const {
soilCarbonChange, // tons C/ha/year
biomassGrowth, // tons C/ha/year
practiceEfficiency, // 0.0 - 1.0
leakageDiscount, // 0.0 - 0.2
buffer // 0.1 - 0.3 (risk buffer)
} = farmData;
// Total carbon sequestration
const totalSequestration = (soilCarbonChange + biomassGrowth) * practiceEfficiency;
// Apply leakage discount
const adjustedSequestration = totalSequestration * (1 - leakageDiscount);
// Apply conservative buffer
const finalSequestration = adjustedSequestration * (1 - buffer);
// Convert to CO2 equivalent (multiply by 44/12)
const co2Equivalent = finalSequestration * 3.67;
return {
totalSequestration,
co2Equivalent,
creditsGenerated: Math.floor(co2Equivalent * 100) / 100 // Round to 2 decimals
};
}
| VVB Partner | Specialization | Accreditation | Coverage |
|---|---|---|---|
| SCS Global Services | Agriculture & Forestry | VCS, Gold Standard, ISO 14065 | Global |
| Bureau Veritas | Land Use & Agriculture | VCS, CDM, ISO 14065 | Africa, Europe |
| SGS | Environmental Services | VCS, Gold Standard | Global |
| Control Union | Sustainable Agriculture | VCS, Fairtrade, Organic | Developing Countries |
The MRV service is structured as a modular backend service with the following components:
- Carbon Calculator: Calculates CO₂ sequestration using IPCC methodologies
- Satellite Integration: Connects to Sentinel-2, Landsat, and Planet Labs APIs
- Field Data Processor: Validates and processes soil sampling data
- Verification Workflow: Manages multi-stage verification pipeline
- Report Generator: Creates MRV reports in PDF/JSON formats
// backend/src/services/mrvService.ts
import { PrismaClient, Project, Farm } from '@prisma/client';
import axios from 'axios';
const prisma = new PrismaClient();
interface CarbonCalculationInput {
farmId: number;
projectId: number;
startDate: Date;
endDate: Date;
methodology: 'field-sampling' | 'modeling' | 'hybrid';
practices: string[];
}
interface CarbonCalculationResult {
totalCO2Sequestered: number;
totalCO2Avoided: number;
netCO2Impact: number;
creditsEligible: number;
confidenceScore: number;
breakdown: {
soilCarbon: number;
biomassCarbon: number;
emissionReductions: number;
buffer: number;
};
practiceContributions: Array<{
practice: string;
area: number;
co2Contribution: number;
confidence: number;
}>;
}
class MRVService {
/**
* Calculate carbon sequestration for a farm project
*/
async calculateCarbonSequestration(
input: CarbonCalculationInput
): Promise {
// Fetch farm and project data
const farm = await prisma.farm.findUnique({
where: { id: input.farmId },
include: { user: true, activities: true }
});
const project = await prisma.project.findUnique({
where: { id: input.projectId },
include: { verifications: true }
});
if (!farm || !project) {
throw new Error('Farm or Project not found');
}
// Calculate based on methodology
let result: CarbonCalculationResult;
switch (input.methodology) {
case 'field-sampling':
result = await this.calculateFromFieldData(farm, project, input);
break;
case 'modeling':
result = await this.calculateFromModeling(farm, project, input);
break;
case 'hybrid':
result = await this.calculateHybridApproach(farm, project, input);
break;
default:
throw new Error('Invalid methodology');
}
// Store calculation in database
await this.storeCarbonCalculation(input.projectId, result);
return result;
}
/**
* Field-based carbon calculation using soil samples
*/
private async calculateFromFieldData(
farm: any,
project: any,
input: CarbonCalculationInput
): Promise {
// Fetch soil sampling data
const soilSamples = await prisma.farmActivity.findMany({
where: {
farmId: farm.id,
activityType: 'soil_sampling',
date: {
gte: input.startDate,
lte: input.endDate
}
}
});
if (soilSamples.length === 0) {
throw new Error('No soil sampling data available');
}
// Calculate soil organic carbon change
const socChange = this.calculateSOCChange(soilSamples, farm.size);
// Calculate biomass carbon
const biomassCarbon = this.calculateBiomassCarbon(farm, input.practices);
// Calculate emission reductions
const emissionReductions = this.calculateEmissionReductions(
input.practices,
farm.size
);
// Apply IPCC Tier 2 methodology
const totalSequestration = socChange + biomassCarbon;
const totalAvoided = emissionReductions;
// Apply conservative buffers (20% for uncertainty)
const buffer = totalSequestration * 0.20;
const creditsEligible = (totalSequestration - buffer) + totalAvoided;
// Convert to CO2 equivalent (C to CO2 = multiply by 44/12)
const co2Equivalent = creditsEligible * 3.67;
return {
totalCO2Sequestered: totalSequestration * 3.67,
totalCO2Avoided: totalAvoided * 3.67,
netCO2Impact: (totalSequestration + totalAvoided) * 3.67,
creditsEligible: co2Equivalent,
confidenceScore: 0.92, // High confidence with field data
breakdown: {
soilCarbon: socChange * 3.67,
biomassCarbon: biomassCarbon * 3.67,
emissionReductions: totalAvoided * 3.67,
buffer: buffer * 3.67
},
practiceContributions: await this.calculatePracticeContributions(
input.practices,
farm.size
)
};
}
/**
* Model-based calculation using satellite data
*/
private async calculateFromModeling(
farm: any,
project: any,
input: CarbonCalculationInput
): Promise {
// Get satellite NDVI data
const ndviData = await this.fetchSatelliteNDVI(
farm.location,
input.startDate,
input.endDate
);
// Apply COMET-Farm model
const cometResults = await this.runCOMETModel({
location: farm.location,
size: farm.size,
practices: input.practices,
climateData: await this.fetchClimateData(farm.location),
ndvi: ndviData
});
// Apply 30% uncertainty buffer for modeling
const buffer = cometResults.totalSequestration * 0.30;
const creditsEligible = (cometResults.totalSequestration - buffer);
return {
totalCO2Sequestered: cometResults.totalSequestration,
totalCO2Avoided: cometResults.emissionReductions,
netCO2Impact: cometResults.totalSequestration + cometResults.emissionReductions,
creditsEligible: creditsEligible * 3.67,
confidenceScore: 0.75, // Lower confidence with modeling
breakdown: {
soilCarbon: cometResults.soilCarbon,
biomassCarbon: cometResults.biomassCarbon,
emissionReductions: cometResults.emissionReductions,
buffer: buffer * 3.67
},
practiceContributions: cometResults.practiceBreakdown
};
}
/**
* Hybrid approach combining field data and modeling
*/
private async calculateHybridApproach(
farm: any,
project: any,
input: CarbonCalculationInput
): Promise {
// Get both field and model results
const fieldResult = await this.calculateFromFieldData(farm, project, input);
const modelResult = await this.calculateFromModeling(farm, project, input);
// Weighted average (70% field data, 30% modeling)
const totalSequestration =
(fieldResult.totalCO2Sequestered * 0.7) +
(modelResult.totalCO2Sequestered * 0.3);
const totalAvoided =
(fieldResult.totalCO2Avoided * 0.7) +
(modelResult.totalCO2Avoided * 0.3);
// Apply 15% buffer for hybrid approach
const buffer = totalSequestration * 0.15;
return {
totalCO2Sequestered: totalSequestration,
totalCO2Avoided: totalAvoided,
netCO2Impact: totalSequestration + totalAvoided,
creditsEligible: (totalSequestration - buffer) + totalAvoided,
confidenceScore: 0.85, // Good confidence with hybrid
breakdown: {
soilCarbon: (fieldResult.breakdown.soilCarbon * 0.7) +
(modelResult.breakdown.soilCarbon * 0.3),
biomassCarbon: (fieldResult.breakdown.biomassCarbon * 0.7) +
(modelResult.breakdown.biomassCarbon * 0.3),
emissionReductions: totalAvoided,
buffer: buffer
},
practiceContributions: this.mergePracticeContributions(
fieldResult.practiceContributions,
modelResult.practiceContributions
)
};
}
/**
* Calculate Soil Organic Carbon (SOC) change
*/
private calculateSOCChange(soilSamples: any[], farmSize: number): number {
// IPCC Tier 2 methodology
const avgSOC = soilSamples.reduce((sum, sample) => {
return sum + (sample.metadata?.organicCarbon || 0);
}, 0) / soilSamples.length;
// Baseline SOC (assume 2% for degraded soil)
const baselineSOC = 2.0;
// SOC change per hectare (tons C/ha/year)
const socChangePerHa = (avgSOC - baselineSOC) / 100 * 1.5; // 1.5 tons/ha soil mass
return socChangePerHa * farmSize;
}
/**
* Calculate biomass carbon sequestration
*/
private calculateBiomassCarbon(farm: any, practices: string[]): number {
let biomassCarbonPerHa = 0;
// Agroforestry contribution
if (practices.includes('agroforestry')) {
biomassCarbonPerHa += 5.0; // 5 tons C/ha/year
}
// Cover cropping contribution
if (practices.includes('cover-cropping')) {
biomassCarbonPerHa += 1.2; // 1.2 tons C/ha/year
}
// No-till residue retention
if (practices.includes('no-till')) {
biomassCarbonPerHa += 0.8; // 0.8 tons C/ha/year
}
return biomassCarbonPerHa * farm.size;
}
/**
* Calculate emission reductions from practices
*/
private calculateEmissionReductions(
practices: string[],
farmSize: number
): number {
let reductionsPerHa = 0;
// Reduced tillage - lower fuel use
if (practices.includes('no-till') || practices.includes('reduced-tillage')) {
reductionsPerHa += 0.3; // 0.3 tons CO2/ha/year
}
// Improved fertilizer management
if (practices.includes('precision-fertilization')) {
reductionsPerHa += 0.5; // 0.5 tons CO2/ha/year (N2O reduction)
}
// Efficient irrigation
if (practices.includes('drip-irrigation')) {
reductionsPerHa += 0.2; // 0.2 tons CO2/ha/year (energy savings)
}
return reductionsPerHa * farmSize;
}
/**
* Fetch satellite NDVI data from Sentinel-2
*/
private async fetchSatelliteNDVI(
location: string,
startDate: Date,
endDate: Date
): Promise {
const [lat, lng] = location.split(',').map(Number);
try {
// Example: Sentinel Hub API integration
const response = await axios.post(
'https://services.sentinel-hub.com/api/v1/process',
{
input: {
bounds: {
bbox: [lng - 0.01, lat - 0.01, lng + 0.01, lat + 0.01]
},
data: [{
type: 'sentinel-2-l2a',
dataFilter: {
timeRange: {
from: startDate.toISOString(),
to: endDate.toISOString()
}
}
}]
},
evalscript: `
//VERSION=3
function setup() {
return {
input: ["B04", "B08"],
output: { bands: 1 }
};
}
function evaluatePixel(sample) {
let ndvi = (sample.B08 - sample.B04) / (sample.B08 + sample.B04);
return [ndvi];
}
`
},
{
headers: {
'Authorization': `Bearer ${process.env.SENTINEL_API_KEY}`,
'Content-Type': 'application/json'
}
}
);
return response.data.ndvi || [];
} catch (error) {
console.error('Satellite data fetch error:', error);
return [0.6]; // Default NDVI for agricultural land
}
}
/**
* Run COMET-Farm carbon model
*/
private async runCOMETModel(params: any): Promise {
// COMET-Farm model implementation
// This is a simplified version - actual implementation would call COMET API
const baselineEmissions = 5.0; // tons CO2/ha/year
let sequestration = 0;
// Calculate based on practices
params.practices.forEach((practice: string) => {
switch (practice) {
case 'no-till':
sequestration += 0.8 * params.size;
break;
case 'cover-cropping':
sequestration += 1.2 * params.size;
break;
case 'agroforestry':
sequestration += 6.0 * params.size;
break;
case 'composting':
sequestration += 0.9 * params.size;
break;
}
});
return {
totalSequestration: sequestration,
soilCarbon: sequestration * 0.6,
biomassCarbon: sequestration * 0.4,
emissionReductions: baselineEmissions * 0.3 * params.size,
practiceBreakdown: params.practices.map((p: string) => ({
practice: p,
area: params.size,
co2Contribution: sequestration / params.practices.length,
confidence: 0.75
}))
};
}
/**
* Store carbon calculation results
*/
private async storeCarbonCalculation(
projectId: number,
result: CarbonCalculationResult
): Promise {
await prisma.credit.create({
data: {
projectId: projectId,
userId: (await prisma.project.findUnique({
where: { id: projectId }
}))!.userId,
amount: result.creditsEligible,
status: 'pending',
// Store detailed results in metadata JSON field
}
});
}
/**
* Calculate practice-level contributions
*/
private async calculatePracticeContributions(
practices: string[],
farmSize: number
): Promise> {
const contributions = practices.map(practice => {
let co2PerHa = 0;
let confidence = 0.85;
switch (practice) {
case 'no-till':
co2PerHa = 0.8 * 3.67;
confidence = 0.90;
break;
case 'cover-cropping':
co2PerHa = 1.2 * 3.67;
confidence = 0.85;
break;
case 'agroforestry':
co2PerHa = 6.0 * 3.67;
confidence = 0.80;
break;
case 'composting':
co2PerHa = 0.9 * 3.67;
confidence = 0.88;
break;
default:
co2PerHa = 0.5 * 3.67;
}
return {
practice,
area: farmSize,
co2Contribution: co2PerHa * farmSize,
confidence
};
});
return contributions;
}
/**
* Merge practice contributions from multiple methods
*/
private mergePracticeContributions(
fieldContributions: any[],
modelContributions: any[]
): any[] {
return fieldContributions.map((fc, index) => ({
practice: fc.practice,
area: fc.area,
co2Contribution: (fc.co2Contribution * 0.7) +
(modelContributions[index]?.co2Contribution || 0) * 0.3,
confidence: (fc.confidence * 0.7) +
(modelContributions[index]?.confidence || 0.7) * 0.3
}));
}
}
export const mrvService = new MRVService();
// backend/src/controllers/mrvController.ts
import { Request, Response } from 'express';
import { mrvService } from '../services/mrvService';
import { z } from 'zod';
// Validation schema
const carbonCalculationSchema = z.object({
farmId: z.number().int().positive(),
projectId: z.number().int().positive(),
startDate: z.string().datetime(),
endDate: z.string().datetime(),
methodology: z.enum(['field-sampling', 'modeling', 'hybrid']),
practices: z.array(z.string()).min(1)
});
/**
* POST /api/mrv/calculate
* Calculate carbon sequestration for a farm project
*/
export const calculateCarbon = async (req: Request, res: Response) => {
try {
// Validate request body
const validation = carbonCalculationSchema.safeParse(req.body);
if (!validation.success) {
return res.status(400).json({
success: false,
error: 'Validation failed',
details: validation.error.errors
});
}
const input = {
...validation.data,
startDate: new Date(validation.data.startDate),
endDate: new Date(validation.data.endDate)
};
// Calculate carbon sequestration
const result = await mrvService.calculateCarbonSequestration(input);
res.status(200).json({
success: true,
data: result,
timestamp: new Date().toISOString()
});
} catch (error: any) {
console.error('MRV calculation error:', error);
res.status(500).json({
success: false,
error: error.message || 'Failed to calculate carbon sequestration'
});
}
};
/**
* GET /api/mrv/report/:projectId
* Generate MRV report for a project
*/
export const generateReport = async (req: Request, res: Response) => {
try {
const projectId = parseInt(req.params.projectId);
// Fetch project with all related data
const project = await prisma.project.findUnique({
where: { id: projectId },
include: {
user: true,
credits: true,
verifications: true,
documents: true
}
});
if (!project) {
return res.status(404).json({
success: false,
error: 'Project not found'
});
}
// Generate comprehensive MRV report
const report = {
projectInfo: {
id: project.id,
name: project.name,
description: project.description,
status: project.status,
methodology: project.methodology,
confidenceScore: project.confidenceScore
},
farmer: {
name: `${project.user.firstName} ${project.user.lastName}`,
email: project.user.email
},
carbonCredits: {
total: project.credits.reduce((sum, c) => sum + c.amount, 0),
pending: project.credits.filter(c => c.status === 'pending').length,
earned: project.credits.filter(c => c.status === 'earned').length,
retired: project.credits.filter(c => c.status === 'retired').length
},
verificationStatus: {
current: project.verificationStatus,
progress: project.verificationProgress,
timeline: project.verifications.map(v => ({
type: v.type,
status: v.status,
timestamp: v.timestamp,
description: v.description
}))
},
documents: project.documents.map(d => ({
filename: d.filename,
uploadedAt: d.uploadedAt
})),
generatedAt: new Date().toISOString()
};
res.status(200).json({
success: true,
data: report
});
} catch (error: any) {
console.error('Report generation error:', error);
res.status(500).json({
success: false,
error: error.message || 'Failed to generate report'
});
}
};
// backend/src/routes/mrv.ts
import { Router } from 'express';
import { auth } from '../middleware/auth';
import { calculateCarbon, generateReport } from '../controllers/mrvController';
const router = Router();
// All routes require authentication
router.use(auth);
/**
* POST /api/mrv/calculate
* Calculate carbon sequestration for a farm project
*/
router.post('/calculate', calculateCarbon);
/**
* GET /api/mrv/report/:projectId
* Generate comprehensive MRV report
*/
router.get('/report/:projectId', generateReport);
/**
* GET /api/mrv/satellite/:farmId
* Fetch satellite data for farm monitoring
*/
router.get('/satellite/:farmId', async (req, res) => {
// Implementation for satellite data retrieval
res.json({ success: true, data: 'Satellite data endpoint' });
});
export default router;
// backend/src/index.ts (add to existing routes)
import mrvRouter from './routes/mrv';
// ... existing code ...
// Add MRV routes
app.use('/api/mrv', mrvRouter);
// Frontend: Calculate carbon sequestration
const calculateCarbonCredits = async (projectData) => {
const response = await fetch('http://localhost:3000/api/mrv/calculate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
farmId: 1,
projectId: 5,
startDate: '2024-01-01T00:00:00Z',
endDate: '2024-12-31T23:59:59Z',
methodology: 'hybrid',
practices: [
'no-till',
'cover-cropping',
'agroforestry',
'composting'
]
})
});
const result = await response.json();
if (result.success) {
console.log('Carbon Credits Eligible:', result.data.creditsEligible);
console.log('Confidence Score:', result.data.confidenceScore);
console.log('Breakdown:', result.data.breakdown);
}
};
// Generate MRV report
const getMRVReport = async (projectId) => {
const response = await fetch(
`http://localhost:3000/api/mrv/report/${projectId}`,
{
headers: {
'Authorization': `Bearer ${token}`
}
}
);
const report = await response.json();
return report.data;
};
# Add to backend/.env
SENTINEL_API_KEY=your_sentinel_hub_api_key
LANDSAT_API_KEY=your_landsat_api_key
PLANET_LABS_API_KEY=your_planet_labs_api_key
WEATHER_API_KEY=your_weather_api_key
# External API endpoints
SENTINEL_API_URL=https://services.sentinel-hub.com/api/v1
COMET_FARM_API_URL=https://comet-farm-api.example.com
WEATHER_API_URL=https://api.openweathermap.org/data/2.5
- Three calculation methodologies: field-sampling, modeling, and hybrid
- IPCC Tier 2 compliant carbon calculations
- Satellite data integration (Sentinel-2, Landsat)
- Automated buffer and uncertainty management
- Practice-level carbon contribution tracking
- Comprehensive MRV report generation
- TypeScript type safety with Prisma ORM
- Satellite API keys required for production use
- COMET-Farm model requires separate API access
- Field sampling data must follow IPCC protocols
- All calculations apply conservative 15-30% buffers
- Third-party verification required before credit issuance
// Farmer registration record
interface Farmer {
id: Text; // Unique farmer identifier
name: Text; // Full legal name
location: Text; // GPS coordinates (lat,lng)
farmSize: Float; // Area in hectares
practices: [Text]; // Array of adopted practices
registrationDate: Text; // ISO 8601 timestamp
verificationStatus: Text; // "pending" | "verified" | "rejected"
contactInfo: ContactInfo;
landTenure: LandTenureInfo;
baseline: BaselineData;
}
// Contact information
interface ContactInfo {
phoneNumber: Text;
email: ?Text; // Optional email
physicalAddress: Text;
preferredLanguage: Text; // "en" | "sw" | "fr" | etc.
emergencyContact: Text;
}
// Land tenure documentation
interface LandTenureInfo {
ownershipType: Text; // "owned" | "leased" | "communal"
documentNumber: Text; // Title deed or lease agreement number
expiryDate: ?Text; // For leased land
legalVerification: Bool; // Document verification status
}
// Baseline carbon measurements
interface BaselineData {
soilOrganicCarbon: Float; // Percentage or tons/ha
biomassCarbon: Float; // tons C/ha
measurementDate: Text;
samplingPoints: [GPSPoint];
labResults: [LabResult];
}
// Carbon estimate record
interface CarbonEstimate {
id: Text;
farmerId: Text;
period: Text; // "YYYY-MM-DD to YYYY-MM-DD"
methodology: Text; // "field-sampling" | "modeling" | "hybrid"
co2eSequestered: Float; // tons CO2 equivalent
co2eAvoided: Float; // tons CO2 equivalent from avoided emissions
practicesImplemented: [Practice];
confidence: Float; // 0.0 - 1.0 confidence score
verificationStatus: Text;
timestamp: Text;
calculationDetails: CalculationBreakdown;
}
// Practice implementation details
interface Practice {
type: Text; // "cover-cropping" | "no-till" | etc.
area: Float; // hectares covered
implementationDate: Text;
effectiveness: Float; // 0.0 - 1.0 implementation quality
evidence: [Evidence]; // Photos, GPS tracks, etc.
}
// Evidence documentation
interface Evidence {
type: Text; // "photo" | "gps-track" | "receipt" | etc.
url: Text; // IPFS hash or cloud storage URL
timestamp: Text;
gpsLocation: ?Text;
description: Text;
}
// Credit transaction record
interface CreditTransaction {
txId: Text; // Blockchain transaction ID
farmerId: Text;
amount: Float; // Number of credits
pricePerCredit: Float; // USD per credit
totalValue: Float; // Total payment in USD
walletAddress: Text; // ICP wallet address
status: Text; // "pending" | "completed" | "failed"
issuanceDate: Text;
vintageYear: Nat; // Year of carbon sequestration
methodology: Text;
serialNumbers: [Text]; // VCS registry serial numbers
}
// Marketplace listing
interface CreditListing {
listingId: Text;
sellerId: Text; // Farmer or aggregator ID
credits: [CreditBatch];
pricePerCredit: Float;
totalCredits: Float;
description: Text;
cobenefits: [Text]; // Additional sustainability benefits
location: Text; // Geographic origin
certifications: [Text]; // VCS, Gold Standard, etc.
listedDate: Text;
status: Text; // "active" | "sold" | "expired"
}
// Credit batch information
interface CreditBatch {
batchId: Text;
vintageYear: Nat;
methodology: Text;
quantity: Float;
verificationBody: Text;
projectId: Text;
additionalityProof: Text;
}
// API Response wrapper
type ApiResponse = {
success: Bool;
data: ?T;
error: ?ApiError;
timestamp: Text;
requestId: Text;
}
// Error types
type ApiError = {
code: Text; // "FARMER_NOT_FOUND" | "INVALID_GPS" | etc.
message: Text;
details: ?Text;
retryable: Bool;
}
// Validation result
type ValidationResult = {
isValid: Bool;
errors: [ValidationError];
warnings: [ValidationWarning];
}
type ValidationError = {
field: Text;
code: Text;
message: Text;
}
Our $CARBON token implements the ICRC-1 standard for maximum compatibility:
// CARBON token canister (Motoko)
import ICRC1 "mo:icrc1";
import Principal "mo:base/Principal";
import Time "mo:base/Time";
actor CarbonToken = {
// Token metadata
private let TOKEN_NAME = "Carbon Credit Token";
private let TOKEN_SYMBOL = "CARBON";
private let TOKEN_DECIMALS = 8;
private let TOKEN_FEE = 10_000; // 0.0001 CARBON
// Minting authority (restricted to verified projects)
private stable var minting_authority = Principal.fromText("rdmx6-jaaaa-aaaah-qcaiq-cai");
// Carbon credit metadata for each token
private stable var credit_metadata = Map.HashMap(0, Nat.equal, Hash.hash);
type CreditMetadata = {
vintageYear: Nat;
methodology: Text;
projectId: Text;
verificationBody: Text;
co2Equivalent: Float;
issuanceDate: Int;
};
// Mint carbon credits (restricted function)
public shared(msg) func mint_carbon_credits(
to: ICRC1.Account,
amount: Nat,
metadata: CreditMetadata
) : async ICRC1.TransferResult {
// Verify caller is authorized minting authority
if (msg.caller != minting_authority) {
return #Err(#Unauthorized { message = "Only minting authority can mint credits" });
};
// Store credit metadata
credit_metadata.put(amount, metadata);
// Mint tokens
await ICRC1.mint({
to = to;
amount = amount;
memo = ?Text.encodeUtf8("Carbon credit issuance: " # metadata.projectId);
created_at_time = ?Nat64.fromNat(Int.abs(Time.now()));
});
};
// Retire carbon credits (permanent removal from circulation)
public shared(msg) func retire_credits(
amount: Nat,
retirement_reason: Text
) : async ICRC1.TransferResult {
// Burn tokens to retirement address
let retirement_account = {
owner = Principal.fromText("aaaaa-aa"); // Burn address
subaccount = null
};
await ICRC1.transfer({
from_subaccount = null;
to = retirement_account;
amount = amount;
fee = ?TOKEN_FEE;
memo = ?Text.encodeUtf8("Credit retirement: " # retirement_reason);
created_at_time = ?Nat64.fromNat(Int.abs(Time.now()));
});
};
// Get credit metadata
public query func get_credit_metadata(token_id: Nat) : async ?CreditMetadata {
credit_metadata.get(token_id);
};
// Batch transfer for marketplace efficiency
public shared(msg) func batch_transfer(
transfers: [ICRC1.TransferArgs]
) : async [ICRC1.TransferResult] {
var results: [ICRC1.TransferResult] = [];
for (transfer_args in transfers.vals()) {
let result = await ICRC1.transfer(transfer_args);
results := Array.append(results, [result]);
};
results;
};
};
- Fractional Ownership: Credits divisible to 8 decimal places for small-scale trading
- Metadata Storage: On-chain storage of vintage year, methodology, and verification data
- Retirement Mechanism: Permanent removal of credits from circulation when used
- Batch Operations: Efficient batch transfers for marketplace and aggregator use
- Access Controls: Role-based permissions for minting, verification, and governance
- Audit Trail: Immutable transaction history for full transparency and compliance
- Node.js: Version 18.0+ (includes npm)
- MySQL: Version 8.0+ for database
- Git: For version control
- Code Editor: VS Code recommended with Prisma extension
# Clone repository
git clone https://github.com/DrewGalowayDev/Greencoin-Edition.git
cd Greencoin-Edition/backend
# Install dependencies
npm install
# Create environment file
cp .env.example .env
# Edit .env with your credentials
DATABASE_URL="mysql://user:password@localhost:3306/greencoin"
JWT_SECRET="your-super-secret-jwt-key"
SMTP_HOST="smtp.gmail.com"
SMTP_PORT=587
SMTP_USER="your-email@gmail.com"
SMTP_PASS="your-app-password"
FRONTEND_URL="http://localhost:5173"
PORT=3000
# Generate Prisma Client
npm run prisma:generate
# Run database migrations
npm run migrate
# Start development server
npm run dev
# Navigate to admin dashboard
cd ../Admin-Dashboard
# Install dependencies
npm install
# Start development server (port 5173)
npm run dev
# Build for production
npm run build
# Preview production build
npm run preview
# Navigate to farmers dashboard
cd ../Farmers-Dashboard
# Install dependencies
npm install
# Start development server (port 8080)
npm run dev
# Build for production
npm run build
# For mobile: Sync with Capacitor
npm run cap:sync
npm run android:dev # Open Android Studio
# Navigate to landing page
cd ../green-landing\ page
# Install dependencies
npm install
# Start development server (port 5175)
npm run dev
# Build Android APK
npm run android:build
# Create new migration
cd backend
npx prisma migrate dev --name your_migration_name
# View database in Prisma Studio
npm run studio
# Reset database (WARNING: deletes all data)
npx prisma migrate reset
# Deploy migrations to production
npm run prisma:migrate
Backend (.env):
DATABASE_URL="mysql://user:password@localhost:3306/greencoin"
JWT_SECRET="generate-with-openssl-rand-base64-32"
SMTP_HOST="smtp.gmail.com"
SMTP_PORT=587
SMTP_USER="notifications@greencoin.com"
SMTP_PASS="app-specific-password"
FRONTEND_URL="http://localhost:5173"
PORT=3000
NODE_ENV="development"
Frontend (.env.local):
VITE_API_URL="http://localhost:3000/api"
VITE_APP_NAME="GreenCoin"
VITE_SUPABASE_URL="your-supabase-url" # If using Supabase
VITE_SUPABASE_ANON_KEY="your-supabase-key"
# Backend deployment (e.g., DigitalOcean, AWS, Heroku)
# 1. Set environment variables on hosting platform
# 2. Build TypeScript
npm run build
# 3. Start production server
npm start
# Frontend deployment (e.g., Vercel, Netlify)
# Admin Dashboard
cd Admin-Dashboard
npm run build
# Upload dist/ folder to hosting
# Farmers Dashboard
cd Farmers-Dashboard
npm run build
# Upload dist/ folder to hosting
# Database (recommended: PlanetScale, AWS RDS)
# 1. Create production MySQL instance
# 2. Update DATABASE_URL in production
# 3. Run migrations
npx prisma migrate deploy
- Backend API: http://localhost:8081
- Admin Dashboard: http://localhost:8080
- Farmers Dashboard: http://localhost:8080
- Landing Page: http://localhost:8081
- Prisma Studio: http://localhost:5555
| Parameter | Type | Description | Required |
|---|---|---|---|
| name | string | Farmer's full legal name (2-100 characters) | Yes |
| location | string | GPS coordinates in "lat,lng" format (WGS84) | Yes |
| farmSize | number | Farm area in hectares (0.5 - 1000.0) | Yes |
| practices | array | List of climate-smart practices to implement | Yes |
| phoneNumber | string | Mobile phone number with country code | Yes |
| string | Email address for notifications (optional) | No | |
| language | string | Preferred language: "en", "sw", "fr", etc. | No |
| landTenure | object | Land ownership/lease documentation | Yes |
| Field | Type | Description | Required |
|---|---|---|---|
| ownershipType | string | "owned", "leased", or "communal" | Yes |
| documentNumber | string | Title deed or lease agreement reference | Yes |
| expiryDate | string | Lease expiry date (YYYY-MM-DD) if applicable | No |
{
"name": "Jane Wanjiku Doe",
"location": "-1.2921,36.8219",
"farmSize": 5.5,
"practices": ["no-till", "agroforestry", "cover-cropping"],
"phoneNumber": "+254712345678",
"email": "jane.doe@example.com",
"language": "en",
"landTenure": {
"ownershipType": "owned",
"documentNumber": "NAIROBI/BLOCK12/567",
"expiryDate": null
}
}
{
"status": "success",
"data": {
"farmerId": "FARM12345",
"registrationDate": "2025-07-25T10:30:00Z",
"verificationStatus": "pending",
"estimatedOnboardingTime": "4-6 weeks",
"nextSteps": [
"Document verification (2-3 days)",
"Field assessment scheduling",
"Baseline measurement appointment",
"Training session enrollment"
]
},
"message": "Farmer registration successful. Verification process initiated."
}
// 400 Bad Request - Validation Error
{
"status": "error",
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid request parameters",
"details": {
"farmSize": "Farm size must be between 0.5 and 1000 hectares",
"location": "GPS coordinates must be within supported regions"
}
}
}
// 409 Conflict - Duplicate Registration
{
"status": "error",
"error": {
"code": "FARMER_EXISTS",
"message": "Farmer already registered with this phone number",
"details": "Existing farmer ID: FARM67890"
}
}
// 422 Unprocessable Entity - Eligibility Issue
{
"status": "error",
"error": {
"code": "ELIGIBILITY_FAILED",
"message": "Farm does not meet program requirements",
"details": "Location outside supported regions. Currently available in Kenya, Uganda, Tanzania, and Ghana."
}
}
| Parameter | Type | Description | Required |
|---|---|---|---|
| farmerId | string | Registered farmer identifier | Yes |
| period | string | Estimation period (YYYY-MM-DD to YYYY-MM-DD) | Yes |
| methodology | string | "field-sampling", "modeling", or "hybrid" | No |
| practices | array | Specific practices to include in calculation | No |
| includeBaseline | boolean | Include baseline measurements in calculation | No |
{
"farmerId": "FARM12345",
"period": "2025-01-01 to 2025-12-31",
"methodology": "hybrid",
"practices": ["no-till", "agroforestry"],
"includeBaseline": true
}
{
"status": "success",
"data": {
"estimationId": "EST78901",
"farmerId": "FARM12345",
"period": "2025-01-01 to 2025-12-31",
"methodology": "hybrid",
"results": {
"totalCO2eSequestered": 12.3,
"totalCO2eAvoided": 4.7,
"netCO2eImpact": 17.0,
"creditsEligible": 15.3,
"confidenceScore": 0.85
},
"breakdown": {
"soilCarbonSequestration": 8.2,
"biomassCarbon": 4.1,
"emissionReductions": 4.7,
"buffer": 1.7,
"leakageDiscount": 0.0
},
"practiceContributions": [
{
"practice": "no-till",
"area": 3.0,
"co2eContribution": 6.8,
"confidence": 0.90
},
{
"practice": "agroforestry",
"area": 2.5,
"co2eContribution": 10.2,
"confidence": 0.80
}
],
"monetaryValue": {
"estimatedValue": 535.50,
"priceRange": {
"minimum": 459.00,
"maximum": 612.00
},
"currency": "USD"
},
"generatedAt": "2025-07-25T10:45:00Z",
"validUntil": "2025-08-25T10:45:00Z"
}
}
// 404 Not Found - Farmer not registered
{
"status": "error",
"error": {
"code": "FARMER_NOT_FOUND",
"message": "Farmer ID not found in system",
"retryable": false
}
}
// 400 Bad Request - Invalid period
{
"status": "error",
"error": {
"code": "INVALID_PERIOD",
"message": "Period must be within current or future years only",
"details": "Historical estimates require baseline data"
}
}
| Parameter | Type | Description | Required |
|---|---|---|---|
| farmerId | string | Verified farmer identifier | Yes |
| amount | number | Number of credits to issue (max 2 decimal places) | Yes |
| walletAddress | string | ICP principal ID or account identifier | Yes |
| vintageYear | number | Year of carbon sequestration (2020-2030) | Yes |
| methodology | string | Verification methodology used | Yes |
| projectId | string | Associated project identifier | No |
| verificationBody | string | Third-party verifier name | Yes |
{
"farmerId": "FARM12345",
"amount": 12.35,
"walletAddress": "abcd-efgh-ijkl-mnop-qrst-uvwx-yz12-3456",
"vintageYear": 2025,
"methodology": "VCS-VM0017",
"projectId": "KE-001-2025",
"verificationBody": "SCS Global Services"
}
{
"status": "success",
"data": {
"transactionId": "TXN67890",
"blockchainTxHash": "0x8f7e6d5c4b3a2918f7e6d5c4b3a2918f7e6d5c4b3a29",
"tokensMinted": 12.35,
"recipientWallet": "abcd-efgh-ijkl-mnop-qrst-uvwx-yz12-3456",
"serialNumbers": [
"KE-VCS-17-001-2025-001-12350000",
"KE-VCS-17-001-2025-002-12350000"
],
"metadata": {
"vintageYear": 2025,
"methodology": "VCS-VM0017",
"projectId": "KE-001-2025",
"verificationBody": "SCS Global Services",
"issuanceDate": "2025-07-25T11:00:00Z",
"co2Equivalent": 12.35
},
"fees": {
"platformFee": 0.31,
"networkFee": 0.0001,
"totalFees": 0.3101
},
"status": "confirmed",
"confirmations": 12,
"estimatedProcessingTime": "2-5 minutes"
},
"message": "Carbon credits successfully minted and transferred"
}
| Parameter | Type | Description | Required |
|---|---|---|---|
| transactionId | string | Transaction identifier from issuance response | Yes |
GET /v1/transactions/TXN67890
Authorization: Bearer your_api_key_here
{
"status": "success",
"data": {
"transactionId": "TXN67890",
"type": "credit_issuance",
"status": "completed",
"farmerId": "FARM12345",
"amount": 12.35,
"walletAddress": "abcd-efgh-ijkl-mnop-qrst-uvwx-yz12-3456",
"blockchainDetails": {
"txHash": "0x8f7e6d5c4b3a2918f7e6d5c4b3a2918f7e6d5c4b3a29",
"blockNumber": 1234567,
"confirmations": 48,
"gasUsed": 125000
},
"timeline": [
{
"status": "initiated",
"timestamp": "2025-07-25T11:00:00Z",
"description": "Transaction initiated by system"
},
{
"status": "validated",
"timestamp": "2025-07-25T11:00:15Z",
"description": "Request validation completed"
},
{
"status": "blockchain_submitted",
"timestamp": "2025-07-25T11:00:30Z",
"description": "Transaction submitted to blockchain"
},
{
"status": "confirmed",
"timestamp": "2025-07-25T11:02:45Z",
"description": "Transaction confirmed on blockchain"
},
{
"status": "completed",
"timestamp": "2025-07-25T11:05:00Z",
"description": "Tokens successfully transferred to recipient"
}
],
"metadata": {
"vintageYear": 2025,
"methodology": "VCS-VM0017",
"serialNumbers": ["KE-VCS-17-001-2025-001-12350000"],
"verificationBody": "SCS Global Services"
},
"createdAt": "2025-07-25T11:00:00Z",
"completedAt": "2025-07-25T11:05:00Z",
"processingTime": "5 minutes"
}
}
| Status | Description | Is Final |
|---|---|---|
| initiated | Transaction request received and queued | No |
| validating | Verifying request parameters and permissions | No |
| blockchain_submitted | Transaction submitted to blockchain network | No |
| pending | Waiting for blockchain confirmation | No |
| confirmed | Transaction confirmed but processing | No |
| completed | Successfully completed | Yes |
| failed | Transaction failed - see error details | Yes |
| Parameter | Type | Description | Required |
|---|---|---|---|
| sellerId | string | Farmer or aggregator identifier | Yes |
| credits | array | Array of credit batches to list | Yes |
| pricePerCredit | number | Price in USD per credit ($5.00 - $150.00) | Yes |
| description | string | Marketing description of the credits | No |
| cobenefits | array | Additional sustainability benefits | No |
| minimumPurchase | number | Minimum credits per transaction | No |
| listingDuration | number | Days listing remains active (1-365) | No |
| Field | Type | Description | Required |
|---|---|---|---|
| serialNumbers | array | VCS registry serial numbers | Yes |
| quantity | number | Number of credits in batch | Yes |
| vintageYear | number | Year of carbon sequestration | Yes |
| methodology | string | Verification methodology (e.g., VCS-VM0017) | Yes |
| projectLocation | string | Geographic origin of credits | Yes |
| additionalityProof | string | Evidence of additionality compliance | Yes |
{
"sellerId": "FARM12345",
"credits": [
{
"serialNumbers": ["KE-VCS-17-001-2025-001-12350000"],
"quantity": 25.75,
"vintageYear": 2025,
"methodology": "VCS-VM0017",
"projectLocation": "Kiambu County, Kenya",
"additionalityProof": "Baseline assessment demonstrates 40% increase in SOC"
}
],
"pricePerCredit": 28.50,
"description": "Premium agroforestry credits from smallholder coffee farms. Verified biodiversity co-benefits and water conservation.",
"cobenefits": [
"Biodiversity enhancement",
"Water quality improvement",
"Farmer income diversification",
"Soil erosion prevention"
],
"minimumPurchase": 1.0,
"listingDuration": 90
}
{
"status": "success",
"data": {
"listingId": "LIST78901",
"sellerId": "FARM12345",
"totalCredits": 25.75,
"pricePerCredit": 28.50,
"totalValue": 733.88,
"listingFee": 18.35,
"netProceeds": 715.53,
"status": "active",
"listedAt": "2025-07-25T12:00:00Z",
"expiresAt": "2025-10-23T12:00:00Z",
"marketplaceUrl": "https://marketplace.carbonplatform.io/listing/LIST78901",
"estimatedSaleTime": "7-14 days",
"marketAnalysis": {
"currentMarketPrice": 26.80,
"pricePosition": "premium",
"demandLevel": "high",
"competitorCount": 12
}
},
"message": "Credits successfully listed for sale"
}
| Parameter | Type | Description | Default |
|---|---|---|---|
| region | string | Filter by geographic region | all |
| methodology | string | Filter by verification methodology | all |
| vintageYear | number | Filter by vintage year | all |
| minPrice | number | Minimum price per credit | 0 |
| maxPrice | number | Maximum price per credit | unlimited |
| cobenefits | string | Filter by co-benefits (comma-separated) | all |
| page | number | Page number for pagination | 1 |
| limit | number | Results per page (max 100) | 20 |
| sortBy | string | "price", "vintage", "quantity", "listed_date" | price |
| sortOrder | string | "asc" or "desc" | asc |
GET /v1/marketplace/browse?region=Kenya&methodology=VCS-VM0017&minPrice=20&maxPrice=40&cobenefits=biodiversity&page=1&limit=10&sortBy=price&sortOrder=asc
{
"status": "success",
"data": {
"listings": [
{
"listingId": "LIST78901",
"sellerId": "FARM12345",
"sellerProfile": {
"name": "Jane Wanjiku Doe",
"location": "Kiambu County, Kenya",
"farmSize": 5.5,
"yearsInProgram": 3,
"totalCreditsSold": 156.25,
"rating": 4.8,
"certifications": ["Organic", "Fairtrade"]
},
"credits": {
"quantity": 25.75,
"vintageYear": 2025,
"methodology": "VCS-VM0017",
"verificationBody": "SCS Global Services",
"projectType": "Agroforestry",
"serialNumbers": ["KE-VCS-17-001-2025-001-12350000"]
},
"pricing": {
"pricePerCredit": 28.50,
"totalValue": 733.88,
"minimumPurchase": 1.0,
"bulkDiscounts": [
{ "minQuantity": 10, "discount": 5 },
{ "minQuantity": 25, "discount": 10 }
]
},
"cobenefits": [
{
"type": "Biodiversity enhancement",
"description": "Increased bird species count by 45%",
"evidence": "https://biodiversity-report.ipfs.io/QmX1..."
},
{
"type": "Water conservation",
"description": "35% reduction in irrigation water use",
"evidence": "https://water-study.ipfs.io/QmY2..."
}
],
"impact": {
"treesPlanted": 2400,
"soilCarbonIncrease": "2.3%",
"farmersSupported": 1,
"communityBeneficiaries": 450
},
"listedAt": "2025-07-25T12:00:00Z",
"expiresAt": "2025-10-23T12:00:00Z",
"status": "active"
}
],
"pagination": {
"currentPage": 1,
"totalPages": 5,
"totalResults": 47,
"resultsPerPage": 10,
"hasNextPage": true,
"hasPreviousPage": false
},
"marketSummary": {
"averagePrice": 31.25,
"priceRange": {
"min": 18.50,
"max": 65.00
},
"totalAvailableCredits": 12847.35,
"totalListings": 47,
"topRegions": [
{ "region": "Kenya", "count": 18 },
{ "region": "Uganda", "count": 15 },
{ "region": "Tanzania", "count": 14 }
]
}
}
}
| Parameter | Type | Description | Required |
|---|---|---|---|
| listingId | string | Target listing identifier | Yes |
| quantity | number | Number of credits to purchase | Yes |
| buyerWallet | string | ICP wallet address for credit delivery | Yes |
| paymentMethod | string | "crypto" or "fiat" | Yes |
| retirementIntent | boolean | Whether credits will be immediately retired | No |
| retirementReason | string | Purpose for retirement (if applicable) | No |
| buyerInfo | object | Buyer identification and contact details | Yes |
| Field | Type | Description | Required |
|---|---|---|---|
| name | string | Individual or organization name | Yes |
| string | Contact email address | Yes | |
| organization | string | Company or institution name | No |
| country | string | Country of residence/operations | Yes |
| intendedUse | string | Purpose for credit purchase | No |
{
"listingId": "LIST78901",
"quantity": 10.5,
"buyerWallet": "wxyz-1234-5678-9012-abcd-efgh-ijkl-mnop",
"paymentMethod": "crypto",
"retirementIntent": true,
"retirementReason": "Corporate carbon neutrality - Q3 2025 emissions offset",
"buyerInfo": {
"name": "Greencoin Solutions Ltd",
"email": "sustainability@greencoin.co.ke",
"organization": "Greencoin Solutions Ltd",
"country": "Kenya",
"intendedUse": "Corporate carbon offsetting"
}
}
{
"status": "success",
"data": {
"purchaseId": "PUR34567",
"listingId": "LIST78901",
"quantity": 10.5,
"pricePerCredit": 28.50,
"subtotal": 299.25,
"fees": {
"platformFee": 7.48,
"networkFee": 0.15,
"totalFees": 7.63
},
"totalAmount": 306.88,
"paymentInstructions": {
"method": "crypto",
"walletAddress": "carbon-escrow-wallet-123456",
"amount": 306.88,
"currency": "ICP",
"timeLimit": "15 minutes"
},
"escrowDetails": {
"escrowId": "ESC89012",
"holdPeriod": "72 hours",
"releaseConditions": "Payment confirmation and credit transfer"
},
"expectedDelivery": "2-4 hours after payment confirmation",
"transactionTimeline": [
{
"step": "Payment",
"status": "pending",
"description": "Awaiting payment to escrow wallet"
},
{
"step": "Verification",
"status": "pending",
"description": "Payment verification and fraud checks"
},
{
"step": "Transfer",
"status": "pending",
"description": "Credit transfer to buyer wallet"
},
{
"step": "Settlement",
"status": "pending",
"description": "Payment release to seller"
}
],
"supportContact": {
"email": "support@carbonplatform.io",
"phone": "+254-700-123456",
"hours": "24/7"
}
}
}
| Parameter | Type | Description | Default |
|---|---|---|---|
| timeframe | string | "7d", "30d", "90d", "1y", "all" | 30d |
| region | string | Specific region analysis | all |
| methodology | string | Methodology-specific metrics | all |
| metric | string | "prices", "volume", "demand", "supply" | all |
{
"status": "success",
"data": {
"timeframe": "30d",
"generatedAt": "2025-07-25T13:00:00Z",
"marketOverview": {
"totalTransactionValue": 2847293.50,
"totalCreditsTraded": 98547.25,
"averagePrice": 28.89,
"priceChange30d": 12.5,
"volumeChange30d": 8.3,
"activeListings": 347,
"completedTransactions": 1205
},
"priceAnalytics": {
"currentAveragePrice": 28.89,
"priceRange": {
"min": 15.20,
"max": 85.00,
"median": 26.50
},
"priceHistory": [
{ "date": "2025-06-25", "price": 25.73 },
{ "date": "2025-07-01", "price": 26.12 },
{ "date": "2025-07-08", "price": 27.45 },
{ "date": "2025-07-15", "price": 28.21 },
{ "date": "2025-07-22", "price": 28.89 }
],
"methodologyPricing": [
{ "methodology": "VCS-VM0017", "averagePrice": 32.45, "volume": 25648.30 },
{ "methodology": "VCS-VM0024", "averagePrice": 28.12, "volume": 18923.75 },
{ "methodology": "Gold Standard", "averagePrice": 41.75, "volume": 12547.80 }
]
},
"regionalAnalytics": [
{
"region": "Kenya",
"totalCredits": 45234.50,
"averagePrice": 29.75,
"priceChange": 11.2,
"topPractices": ["Agroforestry", "No-till", "Cover cropping"],
"farmersActive": 1247
},
{
"region": "Uganda",
"totalCredits": 32156.25,
"averagePrice": 27.85,
"priceChange": 15.8,
"topPractices": ["Agroforestry", "Improved fallow", "Composting"],
"farmersActive": 856
}
],
"demandIndicators": {
"buyerTypes": [
{ "type": "Corporations", "percentage": 45.2, "growth": 18.3 },
{ "type": "Governments", "percentage": 28.7, "growth": 12.1 },
{ "type": "Individuals", "percentage": 16.5, "growth": 31.4 },
{ "type": "NGOs", "percentage": 9.6, "growth": 8.7 }
],
"sectorDemand": [
{ "sector": "Technology", "percentage": 32.1 },
{ "sector": "Manufacturing", "percentage": 24.8 },
{ "sector": "Aviation", "percentage": 18.5 },
{ "sector": "Energy", "percentage": 14.2 },
{ "sector": "Other", "percentage": 10.4 }
]
},
"qualityMetrics": {
"averageRating": 4.6,
"verificationSuccess": 98.7,
"customerSatisfaction": 4.8,
"repeatPurchaseRate": 67.3
},
"marketPredictions": {
"nextMonthPriceEstimate": {
"low": 29.50,
"high": 32.75,
"confidence": 0.78
},
"supplyProjection": {
"expectedNewCredits": 15000,
"seasonalFactors": "Post-harvest verification cycle",
"growthRate": "22% annually"
}
}
}
}
Practices: Agroforestry, No-till, Cover cropping
Annual Credits: 18.5 tons CO₂e
Revenue Increase: 42% ($1,247 additional income)
Quote: "The carbon program transformed my farm. Not only am I earning more, but my soil is healthier and my crops are more resilient to droughts."
Practices: Rotational grazing, Silvopasture
Annual Credits: 2,156 tons CO₂e
Collective Revenue: $64,680 annually
Impact: Funded new storage facilities, solar irrigation systems, and member training programs.
Practices: Improved fallow, Composting
Annual Credits: 12.3 tons CO₂e
Revenue Increase: 35% ($689 additional income)
Achievement: First female farmer in her district to reach 20+ tons total credits sold.
Use our interactive calculator to estimate potential carbon sequestration and earnings from your farm:
Duration: 6 weeks
Difficulty: Beginner
Equipment needed: Basic hand tools
Duration: 8 weeks
Difficulty: Intermediate
Equipment needed: Measuring tools, nursery setup
Duration: 4 weeks
Difficulty: Beginner
Equipment needed: Seeds, basic tools
Duration: 3 weeks
Difficulty: Beginner
Equipment needed: Organic materials, thermometer
Duration: 2 weeks
Difficulty: Beginner
Equipment needed: Smartphone or basic phone
Duration: 3 weeks
Difficulty: Intermediate
Equipment needed: Soil auger, pH strips, jar
🌱 Beginner Pathway (3-4 months)
Perfect for farmers new to climate-smart agriculture:
- Using the Mobile App (Week 1-2)
- Cover Crop Management (Week 3-6)
- Composting for Carbon (Week 7-9)
- Setting Up No-Till Farming (Week 10-15)
🚀 Advanced Pathway (6-8 months)
For experienced farmers ready to maximize carbon potential:
- Soil Health Monitoring (Month 1)
- Agroforestry System Design (Month 2-3)
- Advanced Integration Techniques (Month 4-5)
- Business Planning & Marketing (Month 6)
WhatsApp: +254-706576238
SMS: Text "HELP" to 29429
Languages: English, Swahili, Kikuyu, Luo, French, Luhya
Response Time: Immediate for urgent issues
Technical Issues: tech@Greencoinedition.io
Payment Questions: payments@Greencoinedition.io
Verification: verify@Greencoinedition.io
Response Time: 4-6 hours during business days
Services: On-farm visits, training, problem-solving
Scheduling: Call hotline or use mobile app
Languages: Local languages + English/Swahili
Response Time: 1-3 days for visit scheduling
Specialists: Agronomists, carbon experts, tech support
Booking: Through mobile app or hotline
Duration: 15-45 minutes
Cost: Free for registered farmers
🇰🇪 Kenya Hub - kisii
Address: kwanza place, kisii Town
Phone: +254-706576238
Counties Served: Kakamega, Kiambu, Nakuru, kisii, Kericho, Nairobi, Migori, siaya
Staff: 15 field officers, 3 technical specialists
🇺🇬 Uganda Hub - Kampala
Address: Plot 123, Industrial Area, Kampala
Phone:#####
Districts Served: Central, Eastern, Western regions
Staff: 12 field officers, 2 technical specialists
🇹🇿 Tanzania Hub - Arusha
Farm Size (hectares)
Error Codes
Below are common error codes returned by the Carbon Credit Platform API, their meanings, and suggested actions.