A robust weather data oracle service that fetches real-world weather information and updates the RadiShield WeatherOracle smart contract on the Flare network. The bot serves as the critical bridge between external weather APIs and the blockchain-based insurance system.
The Weather Oracle Bot is a Node.js application deployed on Railway that:
- Fetches weather data from multiple reliable sources
- Validates and processes weather information
- Updates the WeatherOracle smart contract on Flare Coston2 testnet
- Provides HTTP endpoints for health monitoring and manual triggers
- Ensures data freshness and prevents unnecessary blockchain transactions
- Platform: Railway App
- URL: https://radishield-production.up.railway.app
- Network: Flare Coston2 Testnet (Chain ID: 114)
- Status: Active and monitoring weather data requests
- Health Check:
/health- Service status and uptime - Status Endpoint:
/status- Detailed bot information - Weather Endpoint:
/weather/:lat/:lon- Manual weather data updates
Main orchestrator that coordinates all components:
- Manages weather data fetching with fallback mechanisms
- Handles blockchain interactions
- Validates data integrity
- Provides comprehensive error handling
Blockchain interaction layer:
- Connects to Flare Coston2 testnet
- Manages wallet and transaction signing
- Updates WeatherOracle smart contract
- Handles gas estimation and transaction confirmation
OpenMeteoClient (openMeteoClient.js)
- Primary weather data source (free, no API key required)
- Provides 30-day historical rainfall data
- Fetches current temperature readings
- High reliability and comprehensive coverage
WeatherApiClient (weatherApiClient.js)
- Fallback weather service (requires API key)
- Limited to 7-day history on free tier
- Provides current weather conditions
- Used when Open-Meteo is unavailable
Data validation and sanitization:
- Validates temperature ranges (-100°C to 100°C)
- Checks rainfall data (0-10,000mm for 30-day, 0-1,000mm for 24-hour)
- Ensures logical consistency (24h ≤ 30-day rainfall)
- Validates GPS coordinates and data freshness
Express.js web server providing:
- Health monitoring endpoints for Railway
- Manual weather data update triggers
- Service status reporting
- Graceful shutdown handling
# Weather API Configuration (Optional - Fallback only)
WEATHER_API_KEY=your_weatherapi_key_here
# Blockchain Configuration (Required)
RPC_URL=https://coston2-api.flare.network/ext/C/rpc
PRIVATE_KEY=your_oracle_wallet_private_key
WEATHER_ORACLE_ADDRESS=0x223cb9DFE5d4427cF50d1f33C3a3BaAc3DbE72be
# Environment
NODE_ENV=production
- Oracle Wallet: Must be authorized in the WeatherOracle contract
- C2FLR Balance: Sufficient for transaction fees
- Network Access: Ability to connect to Flare Coston2 RPC
- Weather APIs: Open-Meteo (primary, free) + WeatherAPI (fallback, optional)
- Primary Source: Open-Meteo Historical API (free, reliable)
- Fallback Source: WeatherAPI.com (requires key, limited free tier)
- Automatic Failover: Seamlessly switches between sources
- Data Validation: Comprehensive validation before blockchain updates
- Smart Contract: WeatherOracle on Flare Coston2
- Gas Optimization: Estimates gas with 20% buffer
- Transaction Monitoring: Waits for confirmation and logs results
- Error Handling: Detailed error messages for common issues
- 30-Day Rainfall: Historical precipitation totals
- 24-Hour Rainfall: Recent daily precipitation
- Temperature: Current temperature readings
- Coordinate Scaling: Converts GPS coordinates for Solidity compatibility
- Health Checks: Periodic blockchain and API connectivity tests
- Data Freshness: Prevents unnecessary updates if data is recent
- Comprehensive Logging: Detailed operation logs with emojis for clarity
- Graceful Shutdown: Proper cleanup on termination signals
Returns service health status for Railway monitoring:
{
"status": "healthy",
"timestamp": "2024-01-01T00:00:00.000Z",
"uptime": 3600,
"initialized": true,
"lastUpdate": "2024-01-01T00:00:00.000Z",
"error": null
}Detailed bot status information:
{
"service": "Weather Oracle Bot",
"version": "1.0.0",
"status": "running",
"initialized": true,
"lastUpdate": "2024-01-01T00:00:00.000Z",
"uptime": 3600
}Manually trigger weather data update for specific coordinates:
curl https://radishield-production.up.railway.app/weather/40.7128/-74.006Response:
{
"success": true,
"updated": true,
"blockchain": {
"txHash": "0x...",
"blockNumber": 12345,
"gasUsed": "150000"
},
"weatherData": {
"rainfall30d": 45.2,
"rainfall24h": 2.1,
"temperature": 22.5,
"source": "open-meteo"
}
}- Geographic Coverage: Global (Open-Meteo), 1M+ locations (WeatherAPI)
- Historical Data: 30-day rainfall history, current temperature
- Update Frequency: On-demand via smart contract events
- Data Freshness: 1-hour minimum between updates
- Temperature: -100°C to 100°C (with warnings for extremes)
- 30-Day Rainfall: 0mm to 10,000mm
- 24-Hour Rainfall: 0mm to 1,000mm
- Logical Consistency: 24h rainfall ≤ 30-day rainfall
- Coordinate Validation: Standard GPS ranges
- Precision: 2 decimal places for weather values
- Scaling: GPS coordinates scaled by 10,000 for Solidity
- Temperature Scaling: Multiplied by 100 for decimal precision
- Timestamp: Unix timestamp in seconds
# Clone and install dependencies
cd weather_bot
npm install
# Configure environment
cp .env.example .env
# Edit .env with your configuration
# Test the bot
npm test
# Run development server
npm run dev# Run full integration test
npm test
# Test specific coordinates
node -e "
const Bot = require('./index');
const bot = new Bot();
bot.updateWeatherOnChain(40.7128, -74.006);
"The bot is configured for automatic deployment on Railway:
- Build: Uses Nixpacks builder
- Start Command:
npm start - Health Checks:
/healthendpoint - Restart Policy: On failure with 10 max retries
- Environment: Production configuration
Error: Insufficient funds for transaction
Solution: Add C2FLR to oracle wallet
Error: Oracle not authorized
Solution: Call authorizeOracle() in WeatherOracle contract
Error: All weather APIs failed
Solution: Check API keys and network connectivity
Error: Invalid GPS coordinates
Solution: Ensure lat (-90 to 90) and lon (-180 to 180)
- Railway Health Checks: Automatic via
/healthendpoint - Blockchain Connectivity: Tested every 5 minutes
- API Availability: Tested on each request with fallback
- Transaction Status: Full confirmation tracking
- Response Time: Weather data fetch and blockchain update
- Success Rate: Percentage of successful updates
- Gas Usage: Average transaction costs
- API Usage: Request counts and error rates
- Wallet Balance: Monitor C2FLR balance for transactions
- API Quotas: Track usage limits (WeatherAPI free tier)
- Log Monitoring: Review error patterns and performance
- Contract Updates: Handle WeatherOracle contract upgrades
- Contract Address:
0x223cb9DFE5d4427cF50d1f33C3a3BaAc3DbE72be - Network: Flare Coston2 Testnet
- Function:
updateWeatherData(lat, lon, weatherData) - Events: Listens for
WeatherDataRequestedevents
- Policy Creation: Farmer creates insurance policy with GPS coordinates
- Weather Request: RadiShield contract requests weather data
- Bot Processing: Weather bot fetches and validates data
- Blockchain Update: Bot updates WeatherOracle contract
- Payout Evaluation: RadiShield checks weather triggers
Weather APIs → Weather Bot → WeatherOracle Contract → RadiShield Contract → Insurance Payouts
- Private Key: Stored securely in Railway environment variables
- Permissions: Oracle wallet only authorized for weather updates
- Balance Monitoring: Alerts for low C2FLR balance
- Multi-Source Validation: Primary and fallback weather sources
- Range Validation: Strict bounds checking on all weather data
- Logical Validation: Consistency checks between related values
- Timestamp Validation: Ensures data freshness
- HTTPS Only: All API communications encrypted
- Rate Limiting: Built-in request throttling
- Error Handling: No sensitive data in error messages
- Graceful Degradation: Continues operation with single API source
- Railway Logs: Comprehensive logging with emoji indicators
- Transaction Tracking: Full blockchain transaction details
- API Response Logging: Weather data fetch results
- Error Classification: Detailed error categorization
- Data Caching: Prevents unnecessary API calls
- Gas Optimization: Efficient transaction parameters
- Connection Pooling: Reuses blockchain connections
- Timeout Handling: Prevents hanging requests
This project is licensed under the MIT License.