A comprehensive decentralized insurance platform built on Sui blockchain that provides automatic crop protection based on real-time weather data and parametric triggers.
- Overview
- Features
- Architecture
- Installation
- Configuration
- Usage Guide
- API Documentation
- Smart Contracts
- Weather Integration
- Security
- Deployment
- Testing
- Monitoring
- Contributing
- Troubleshooting
- License
This platform revolutionizes agricultural insurance by leveraging blockchain technology and real-time weather data to provide:
- Automatic Claims Processing: No manual assessment required
- Real-time Weather Monitoring: Oracle-based data integration
- Transparent Payouts: Smart contract execution
- Global Coverage: Support for any geographical location
- Parametric Insurance: Payouts based on predefined weather thresholds
- For Farmers: Instant, transparent, and reliable crop protection
- For Insurers: Reduced operational costs and fraud prevention
- For the Ecosystem: Increased agricultural resilience and food security
- π€οΈ Real-time Weather Monitoring: Oracle-based weather data integration
- π± Smart Contract Integration: Direct Sui blockchain integration
- π Automatic Claims: Parametric insurance with automatic payouts
- π Global Coverage: Support for any geographical location
- πΌ User-friendly Interface: Clean, modern web application
- π Dashboard Analytics: Comprehensive monitoring and reporting
- π Secure Transactions: Blockchain-based security
- π― Parametric Triggers: Temperature, rainfall, humidity thresholds
- π Risk Assessment: AI-powered risk evaluation
- π Multi-Oracle Support: Redundant data sources for reliability
- π± Mobile Responsive: Works on all devices
- π Multi-language Support: International accessibility
- π Historical Data: Weather pattern analysis
- π Real-time Alerts: Instant notifications for critical conditions
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Frontend Layer β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Next.js 15 β TypeScript β Tailwind CSS β
β React 18 β Radix UI β Lucide Icons β
β Sui dApp Kit β Zustand β React Query β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Backend Layer β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Sui Move Contracts β Weather Oracles β API Gateway β
β Smart Contracts β Data Processing β Authenticationβ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Sui Blockchain β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Insurance Policies β Policy Caps β Claim Objects β
β Weather Data β Oracle Feeds β Transactions β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Weather APIs β Oracle Service β Smart Contract β User Wallet
β β β β
Real-time Data β Processing β Validation β Payout
- Node.js: Version 18.0.0 or higher
- pnpm: Version 8.0.0 or higher
- Sui CLI: Latest version
- Git: Version 2.30.0 or higher
- VS Code: Recommended IDE
- Sui Wallet: Browser extension
- SuiScan: Blockchain explorer access
- OpenWeatherMap: Weather data API
- Sui Network: Testnet/Mainnet access
git clone https://github.com/your-org/parametric-agricultural-insurance.git
cd parametric-agricultural-insurance# Install Node.js dependencies
pnpm install
# Install Sui CLI (if not already installed)
cargo install --locked --git https://github.com/MystenLabs/sui.git --tag main sui# Copy environment template
cp app/api/env.example app/api/.env
# Edit environment variables
nano app/api/.env# Configure Sui CLI
sui client new-address ed25519
sui client switch --env testnet
# Get testnet SUI tokens
sui client faucet# Make deployment script executable
chmod +x deploy-insurance.sh
# Deploy to testnet
./deploy-insurance.sh# Start the application
pnpm dev
# Application will be available at http://localhost:3000# Sui Network Configuration
SUI_NETWORK=testnet
SUI_RPC_URL=https://fullnode.testnet.sui.io:443
# Weather API Configuration
OPENWEATHER_API_KEY=your_api_key_here
WEATHER_CACHE_DURATION=300000
# Application Configuration
NEXT_PUBLIC_APP_NAME=Parametric Agricultural Insurance
NEXT_PUBLIC_APP_VERSION=1.0.0# Analytics
GOOGLE_ANALYTICS_ID=GA_MEASUREMENT_ID
MIXPANEL_TOKEN=your_mixpanel_token
# Monitoring
SENTRY_DSN=your_sentry_dsn
LOG_LEVEL=info
# Feature Flags
ENABLE_ANALYTICS=true
ENABLE_MONITORING=true
ENABLE_DEBUG_MODE=false// app/networkConfig.ts
export const testnetConfig = {
rpcUrl: 'https://fullnode.testnet.sui.io:443',
faucetUrl: 'https://faucet.testnet.sui.io/gas',
explorerUrl: 'https://suiscan.xyz/testnet',
packageId: '0x...', // Your deployed package ID
};export const mainnetConfig = {
rpcUrl: 'https://fullnode.mainnet.sui.io:443',
explorerUrl: 'https://suiscan.xyz/mainnet',
packageId: '0x...', // Your deployed package ID
};- Create Account: Sign up at OpenWeatherMap
- Get API Key: Generate your API key
- Configure Service: Update
app/services/real-weather-api.ts
const API_KEY = process.env.OPENWEATHER_API_KEY;
const BASE_URL = 'https://api.openweathermap.org/data/2.5';- WeatherAPI: Backup weather data source
- AccuWeather: Premium weather data
- Custom Oracle: Your own weather data source
- Connect Wallet: Install Sui wallet extension
- Fund Account: Ensure you have SUI tokens
- Access Platform: Navigate to the application
Coverage Amount: 1000 SUI
Monthly Premium: 100 SUI
Field Location: GPS coordinates
Maximum Temperature: 35Β°C
Minimum Temperature: 5Β°C
Maximum Rainfall: 50mm
Humidity Range: 30% - 80%
- Review all parameters
- Confirm weather conditions
- Sign transaction
- Policy created on blockchain
- Dashboard: View all policies
- Weather Data: Real-time conditions
- Claim Status: Automatic processing
- Transaction History: Blockchain records
import { suiInsuranceCleanService } from '@/services/sui-insurance-clean';
// Create insurance policy
const result = await suiInsuranceCleanService.createInsuranceObject(
coverageAmount,
premiumAmount,
riskType,
maxTemperature,
minTemperature,
maxRainfall,
minHumidity,
maxHumidity,
locationLat,
locationLng,
signAndExecute,
currentAccount
);import { unifiedWeatherService } from '@/services/unified-weather-service';
// Get current weather
const weather = await unifiedWeatherService.getCurrentWeather(lat, lng);
// Check conditions
const conditions = unifiedWeatherService.checkWeatherConditions(
weather,
thresholds
);class SuiInsuranceCleanService {
// Set contract package ID
setPackageId(packageId: string): void
// Create insurance object
createInsuranceObject(
coverageAmount: number,
premiumAmount: number,
riskType: number,
maxTemperature: number,
minTemperature: number,
maxRainfall: number,
minHumidity: number,
maxHumidity: number,
locationLat: number,
locationLng: number,
signAndExecute: any,
currentAccount: any
): Promise<{policyObject: InsurancePolicyObject, capObject: PolicyCapObject}>
// Check deployment status
isDeployed(): boolean
// Get package ID
getPackageId(): string | null
}class UnifiedWeatherService {
// Get current weather data
getCurrentWeather(lat: number, lng: number): Promise<WeatherData>
// Check weather conditions
checkWeatherConditions(
weatherData: WeatherData,
thresholds: WeatherThresholds
): {shouldClaim: boolean, reason: string, claimAmount: number}
// Get critical weather data
getCriticalWeatherData(lat: number, lng: number): WeatherData
// Get normal weather data
getNormalWeatherData(lat: number, lng: number): WeatherData
// Clear cache
clearCache(): void
}interface InsurancePolicyObject {
objectId: string;
policyId: string;
clientAddress: string;
coverageAmount: number;
premiumAmount: number;
riskType: number;
status: number;
createdAt: number;
maxTemperature: number;
minTemperature: number;
maxRainfall: number;
minHumidity: number;
maxHumidity: number;
locationLat: number;
locationLng: number;
claimAmount: number;
}interface WeatherData {
temperature: number;
rainfall: number;
humidity: number;
location: {
lat: number;
lng: number;
};
timestamp: number;
description?: string;
}module 0x0::insurance {
// Insurance Policy struct
struct InsurancePolicy has key, store {
id: UID,
policy_id: ID,
client_address: address,
coverage_amount: u64,
premium_amount: u64,
risk_type: u8,
status: u8,
created_at: u64,
max_temperature: u64,
min_temperature: u64,
max_rainfall: u64,
min_humidity: u64,
max_humidity: u64,
location_lat: u64,
location_lng: u64,
claim_amount: u64,
}
// Policy Cap struct
struct PolicyCap has key, store {
id: UID,
policy_id: ID,
}
}// Create new insurance policy
public fun create_policy_entry(
ctx: &mut TxContext,
coverage_amount: u64,
premium_amount: u64,
risk_type: u8,
max_temperature: u64,
min_temperature: u64,
max_rainfall: u64,
min_humidity: u64,
max_humidity: u64,
location_lat: u64,
location_lng: u64,
): (InsurancePolicy, PolicyCap)
// Check weather conditions and process claims
public fun check_weather_conditions_and_claim(
policy: &mut InsurancePolicy,
current_temperature: u64,
current_rainfall: u64,
current_humidity: u64,
ctx: &mut TxContext,
): u64#!/bin/bash
# deploy-insurance.sh
echo "π Deploying Insurance Contract to Sui..."
# Build the contract
sui move build
# Deploy to network
sui client publish --gas-budget 100000000
echo "β
Contract deployed successfully!"
echo "π¦ Package ID: [COPY THIS TO FRONTEND]"# Verify contract on SuiScan
sui client object <PACKAGE_ID>
# Check contract functions
sui client call <PACKAGE_ID>::insurance::create_policy_entry- Current Weather: Real-time conditions
- Forecast Data: 5-day predictions
- Historical Data: Past weather patterns
- Global Coverage: Worldwide data
interface WeatherDataPoint {
temperature: number; // Celsius
humidity: number; // Percentage
rainfall: number; // Millimeters
windSpeed: number; // m/s
pressure: number; // hPa
visibility: number; // km
uvIndex: number; // UV index
timestamp: number; // Unix timestamp
}Weather APIs β Data Processing β Oracle Service β Smart Contract
β β β β
Raw Data β Validation β Aggregation β Blockchain
- Cache Duration: 5 minutes
- Fallback Data: Consistent simulated data
- Error Handling: Graceful degradation
- Performance: Optimized for speed
const temperatureThresholds = {
critical_high: 40, // Β°C - Crop damage
high: 35, // Β°C - Stress conditions
optimal_high: 30, // Β°C - Good growing
optimal_low: 15, // Β°C - Good growing
low: 5, // Β°C - Stress conditions
critical_low: 0, // Β°C - Frost damage
};const rainfallThresholds = {
drought: 0, // mm - No rain
low: 5, // mm - Light rain
normal: 15, // mm - Normal rain
high: 30, // mm - Heavy rain
flood: 50, // mm - Flood conditions
};const humidityThresholds = {
very_low: 20, // % - Arid conditions
low: 40, // % - Dry conditions
normal: 60, // % - Optimal conditions
high: 80, // % - Humid conditions
very_high: 95, // % - Saturated conditions
};- Access Control: Owner-only functions
- Input Validation: Parameter checking
- Overflow Protection: Safe math operations
- Reentrancy Guards: Attack prevention
- Upgradeability: Controlled updates
- Code Review: Professional audit
- Testing: Comprehensive test suite
- Monitoring: Real-time security monitoring
- Updates: Regular security patches
- No Personal Data: Only coordinates stored
- Encrypted Storage: Sensitive data protection
- Access Control: Role-based permissions
- Data Minimization: Only necessary data collected
- HTTPS: Encrypted communication
- API Security: Rate limiting and authentication
- Wallet Security: Secure key management
- Transaction Security: Signed transactions
- Wallet Security: Use hardware wallets
- Private Keys: Never share private keys
- Network Verification: Always verify network
- Transaction Review: Check before signing
- Code Audits: Regular security reviews
- Dependency Updates: Keep dependencies current
- Error Handling: Comprehensive error management
- Logging: Detailed security logs
# Install Vercel CLI
npm i -g vercel
# Deploy to Vercel
vercel --prod
# Configure environment variables
vercel env add OPENWEATHER_API_KEY
vercel env add SUI_NETWORK# Build the application
pnpm build
# Deploy to Netlify
netlify deploy --prod --dir=outFROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]# Configure for testnet
sui client switch --env testnet
# Deploy contract
sui client publish --gas-budget 100000000
# Verify deployment
sui client object <PACKAGE_ID># Configure for mainnet
sui client switch --env mainnet
# Deploy contract
sui client publish --gas-budget 100000000
# Verify deployment
sui client object <PACKAGE_ID>NODE_ENV=production
SUI_NETWORK=mainnet
OPENWEATHER_API_KEY=your_production_key
LOG_LEVEL=error
ENABLE_ANALYTICS=trueNODE_ENV=staging
SUI_NETWORK=testnet
OPENWEATHER_API_KEY=your_staging_key
LOG_LEVEL=info
ENABLE_DEBUG_MODE=true# Run component tests
pnpm test
# Run with coverage
pnpm test:coverage
# Run specific test
pnpm test InsuranceContractCreator# Run Move tests
sui move test
# Run specific test
sui move test insurance::test_create_policy# Install Playwright
pnpm add -D @playwright/test
# Run E2E tests
pnpm test:e2e
# Run in headed mode
pnpm test:e2e --headed# Test weather API
pnpm test:api
# Test Sui integration
pnpm test:sui# Install Artillery
npm install -g artillery
# Run load tests
artillery run load-test.yml# Test with high load
artillery run stress-test.yml// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: Date.now(),
version: process.env.APP_VERSION,
uptime: process.uptime()
});
});- Response Time: API response times
- Throughput: Requests per second
- Error Rate: Error percentage
- Uptime: Service availability
// Monitor Sui transactions
const monitorTransactions = async () => {
const client = new SuiClient({ url: SUI_RPC_URL });
// Watch for new transactions
client.subscribeEvent({
filter: { Package: PACKAGE_ID },
onMessage: (event) => {
console.log('New transaction:', event);
}
});
};- Policy Creation: New insurance policies
- Claim Processing: Automatic payouts
- Weather Updates: Oracle data feeds
- Error Events: Contract failures
- Accuracy: Weather data accuracy
- Latency: Data update frequency
- Availability: Service uptime
- Coverage: Geographic coverage
// Check oracle health
const checkOracleHealth = async () => {
const health = await oracleService.getHealthStatus();
return {
status: health.status,
lastUpdate: health.lastUpdate,
dataQuality: health.dataQuality,
coverage: health.coverage
};
};# Fork the repository on GitHub
# Clone your fork
git clone https://github.com/your-username/parametric-agricultural-insurance.git
cd parametric-agricultural-insurance
# Add upstream remote
git remote add upstream https://github.com/original-org/parametric-agricultural-insurance.git# Create feature branch
git checkout -b feature/your-feature-name
# Make changes
# Test changes
pnpm test
# Commit changes
git commit -m "Add your feature"
# Push to fork
git push origin feature/your-feature-name
# Create pull request- Type Safety: Strict type checking
- Interface Design: Clear interfaces
- Error Handling: Comprehensive error management
- Documentation: JSDoc comments
- Component Structure: Functional components
- State Management: Hooks and context
- Performance: Memoization and optimization
- Accessibility: WCAG compliance
- Security: Secure coding practices
- Gas Optimization: Efficient operations
- Documentation: Clear function documentation
- Testing: Comprehensive test coverage
- Code Review: Self-review your code
- Testing: Ensure all tests pass
- Documentation: Update relevant docs
- Performance: Check for performance issues
## Description
Brief description of changes
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Testing
- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Manual testing completed
## Checklist
- [ ] Code follows style guidelines
- [ ] Self-review completed
- [ ] Documentation updated
- [ ] No breaking changes# Permission denied error
sudo chmod +x node_modules/.bin/next
# Node version issues
nvm use 18
# Package manager issues
rm -rf node_modules package-lock.json
pnpm install# Wallet not connecting
# Check network configuration
sui client active-env
# Switch to correct network
sui client switch --env testnet
# Reset wallet connection
# Clear browser cache and reconnect# API key not working
# Check environment variables
echo $OPENWEATHER_API_KEY
# Test API directly
curl "https://api.openweathermap.org/data/2.5/weather?lat=48.8566&lon=2.3522&appid=YOUR_API_KEY"# Contract not deployed
# Check package ID
sui client object <PACKAGE_ID>
# Redeploy contract
./deploy-insurance.sh
# Check gas balance
sui client gas// Enable debug mode
const DEBUG = process.env.NODE_ENV === 'development';
if (DEBUG) {
console.log('Debug information:', debugData);
}// Open browser console
// Check for errors
console.error('Error details:', error);
// Monitor network requests
// Check API responses
// Verify wallet connection# Check bundle size
pnpm build
pnpm analyze
# Optimize images
# Use next/image for optimization
# Implement lazy loading// Optimize Move functions
// Reduce storage operations
// Batch transactions
// Use efficient data structures- GitHub Issues: Bug reports and feature requests
- Discord: Real-time community support
- Stack Overflow: Technical questions
- Reddit: General discussions
- Enterprise Support: Commercial support
- Consulting: Custom implementations
- Training: Team training programs
- Auditing: Security audits
This project is licensed under the MIT License - see the LICENSE file for details.
- Commercial Use: β Allowed
- Modification: β Allowed
- Distribution: β Allowed
- Private Use: β Allowed
- Liability: β No warranty provided
- Warranty: β No warranty provided
- Sui SDK: Apache 2.0 License
- Next.js: MIT License
- React: MIT License
- Tailwind CSS: MIT License
- Sui Documentation: docs.sui.io
- Next.js Documentation: nextjs.org/docs
- React Documentation: react.dev
- SuiScan Explorer: suiscan.xyz
- Sui GitHub: github.com/MystenLabs/sui
- Sui Discord: discord.gg/sui
- OpenWeatherMap: openweathermap.org
- WeatherAPI: weatherapi.com
- AccuWeather: developer.accuweather.com
- VS Code: code.visualstudio.com
- Sui Wallet: chrome.google.com/webstore
- Sui CLI: docs.sui.io/build/sui-install
Built with β€οΈ for the agricultural community
- Sui Foundation: For blockchain infrastructure
- OpenWeatherMap: For weather data services
- Agricultural Community: For feedback and testing
- Open Source Contributors: For their valuable contributions
This project was inspired by the need to provide accessible, transparent, and reliable insurance solutions for farmers worldwide, leveraging the power of blockchain technology and real-time data.
Ready to revolutionize agricultural insurance? Start building today! π