
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
opentrustprotocol-oracle
Advanced tools
Performance Oracle & Analytics Engine for OpenTrust Protocol - Real-world outcome tracking and performance measurement
The OpenTrust Protocol Oracle is the revolutionary second pillar of the OpenTrust Protocol ecosystem, bridging the gap between OTP predictions and real-world outcomes. This creates the foundation for the Circle of Trust - a continuous learning loop that improves decision-making over time.
The Performance Oracle system introduces groundbreaking capabilities:
┌─────────────────────────────────────────────────────────────────┐
│ 🔮 OPENTRUST PROTOCOL ORACLE v4.0.3 - PHASE 6 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 🌐 PRODUCTION API LAYER │
│ ├─ 🔗 REST API Server (Express.js) │
│ ├─ 🔌 WebSocket Server (Real-time Updates) │
│ ├─ 🔐 JWT Authentication & Authorization │
│ ├─ ⚡ Rate Limiting & Security │
│ └─ 📚 Swagger/OpenAPI Documentation │
│ │
│ 📊 ENHANCED ORACLE SYSTEM │
│ ├─ 🎯 Enhanced Oracle (Analytics Integration) │
│ ├─ 💰 Trading Oracle (Financial Outcomes) │
│ ├─ 🏥 Medical Oracle (Healthcare Outcomes) │
│ └─ 📊 Performance Dashboard (Multi-Oracle Monitoring) │
│ │
│ 🗄️ ADVANCED STORAGE LAYER │
│ ├─ 💾 Memory Storage (Development & Testing) │
│ ├─ 🗃️ PostgreSQL Storage (Production) │
│ ├─ 📊 Storage Analytics & Statistics │
│ └─ 🔄 Data Synchronization & Backup │
│ │
│ 📈 ANALYTICS & METRICS ENGINE │
│ ├─ 🎯 Calibration Analysis (Bucket-based) │
│ ├─ 🔮 VoI (Value of Indeterminacy) with Pearson Correlation │
│ ├─ 📈 Performance Grading (A+ to D) │
│ ├─ 🔍 Mapper Performance Evaluation │
│ ├─ 🚨 Real-time Monitoring & Alerts │
│ └─ 📊 Comprehensive Reporting │
│ │
│ 🐳 DEPLOYMENT & INFRASTRUCTURE │
│ ├─ 🐳 Docker & Docker Compose │
│ ├─ 🏗️ Production-Ready Configuration │
│ ├─ 📊 Health Monitoring & Metrics │
│ └─ 🔧 Environment Configuration │
│ │
└─────────────────────────────────────────────────────────────────┘
npm install opentrustprotocol-oracle opentrustprotocol
import {
createTradingOracle,
createMedicalOracle,
SimpleOracle
} from 'opentrustprotocol-oracle';
// Create simple oracles for development
const tradingOracle = createTradingOracle('my-trading-oracle');
const medicalOracle = createMedicalOracle('my-medical-oracle');
import {
OracleServer,
EnhancedOracle,
PerformanceDashboard,
PostgreSQLStorage
} from 'opentrustprotocol-oracle';
// Create production server with all features
const server = new OracleServer({
api: {
port: 3000,
jwtSecret: 'your-secret-key'
},
postgres: {
host: 'localhost',
port: 5432,
database: 'oracle_db',
username: 'oracle_user',
password: 'oracle_password'
}
});
await server.start();
// Use the REST API from any application
const response = await fetch('http://localhost:3000/api/oracles', {
method: 'POST',
headers: {
'Authorization': 'Bearer your-jwt-token',
'Content-Type': 'application/json'
},
body: JSON.stringify({
oracleId: 'my-oracle',
version: '4.0.0',
description: 'My Custom Oracle'
})
});
import { TradingOracle, TradingContext } from 'opentrustprotocol-oracle';
import { NeutrosophicJudgment } from 'opentrustprotocol';
// Create trading oracle
const oracle = new TradingOracle({
oracleId: 'crypto-trading-oracle',
version: '1.0.0',
description: 'Cryptocurrency Trading Oracle'
}, storage);
// Record a successful trade
const originalDecision: NeutrosophicJudgment = {
judgment_id: 'trade-decision-001',
t: 0.8, // 80% confidence in success
i: 0.1, // 10% uncertainty
f: 0.1, // 10% chance of failure
provenance_chain: [/* ... */]
};
const tradeContext: TradingContext = {
pair: 'BTC/USDT',
direction: 'long',
entryPrice: 50000,
exitPrice: 55000,
positionSize: 1000,
marketConditions: {
volatility: 0.05,
volume: 1000000,
trend: 'bullish'
},
risk: {
positionSize: 1000,
stopLoss: 48000,
takeProfit: 60000
}
};
await oracle.recordSuccessfulTrade(
originalDecision,
tradeContext,
500, // $500 profit
marketSnapshot
);
// Get performance metrics
const performance = await oracle.getTradingPerformance();
console.log(`Win Rate: ${(performance.trading.winRate * 100).toFixed(1)}%`);
console.log(`Total Profit: $${performance.trading.totalProfit.toFixed(2)}`);
console.log(`Sharpe Ratio: ${performance.trading.sharpeRatio.toFixed(3)}`);
import { MedicalOracle, MedicalContext } from 'opentrustprotocol-oracle';
// Create medical oracle
const oracle = new MedicalOracle({
oracleId: 'medical-treatment-oracle',
version: '1.0.0',
description: 'Medical Treatment Oracle'
}, storage);
// Record successful treatment
const medicalContext: MedicalContext = {
patientId: 'patient-001',
condition: 'hypertension',
treatment: 'medication',
followUpDays: 30,
protocol: {
dosage: '10mg daily',
frequency: 'once daily',
duration: '30 days'
}
};
await oracle.recordSuccessfulTreatment(
originalDecision,
medicalContext,
14, // 14 days to recovery
0.9 // 90% improvement score
);
// Get safety alerts
const alerts = oracle.getSafetyAlerts();
if (alerts.length > 0) {
console.log('⚠️ Safety Alert:', alerts[0].message);
}
import { OTPAnalyticsEngine } from 'opentrustprotocol-oracle';
const analytics = new OTPAnalyticsEngine();
// Analyze calibration with bucket-based analysis
const calibration = await analytics.calculateCalibration(judgmentPairs);
console.log(`Calibration Score: ${(calibration.overall_calibration_score * 100).toFixed(1)}%`);
console.log(`Brier Score: ${calibration.brier_score.toFixed(3)}`);
console.log(`Bucket Analysis:`, calibration.bucket_analysis);
// Analyze VoI (Value of Indeterminacy) with Pearson correlation
const voi = await analytics.calculateVoI(judgmentPairs);
console.log(`VoI Correlation: ${voi.indeterminacy_correlation.toFixed(3)}`);
console.log(`Average VoI Contribution: ${voi.average_voi_contribution.toFixed(3)}`);
console.log(`Optimal Indeterminacy Range: ${voi.optimal_indeterminacy_range.min}-${voi.optimal_indeterminacy_range.max}`);
// Evaluate mapper performance
const mapperPerformance = await analytics.evaluateMapperPerformance(judgmentPairs);
console.log(`Mapper Performance:`, mapperPerformance);
The Oracle now includes a comprehensive Machine Learning engine for predictive analytics:
import { MLPredictiveEngine } from 'opentrustprotocol-oracle';
const mlEngine = new MLPredictiveEngine();
// Train models with historical data
await mlEngine.trainModels(judgmentPairs);
// Generate predictions
const prediction = await mlEngine.generatePrediction(
oracleId,
judgment,
'success_probability',
context
);
// Analyze trends
const trends = await mlEngine.analyzeTrends(judgmentPairs, oracleId);
// Generate alerts
const alerts = await mlEngine.generateAlerts(judgmentPairs, oracleId);
// Get calibration metrics via REST API
const calibrationResponse = await fetch('http://localhost:3000/api/metrics/calibration?oracleId=my-oracle', {
headers: { 'Authorization': 'Bearer your-jwt-token' }
});
const calibration = await calibrationResponse.json();
// Get VoI metrics
const voiResponse = await fetch('http://localhost:3000/api/metrics/voi?oracleId=my-oracle', {
headers: { 'Authorization': 'Bearer your-jwt-token' }
});
const voi = await voiResponse.json();
// Get mapper-specific performance
const mapperResponse = await fetch('http://localhost:3000/api/metrics/mapper/my-mapper-id', {
headers: { 'Authorization': 'Bearer your-jwt-token' }
});
const mapperPerformance = await mapperResponse.json();
// Train ML models
const trainResponse = await fetch('http://localhost:3000/api/ml/train', {
method: 'POST',
headers: {
'Authorization': 'Bearer your-jwt-token',
'Content-Type': 'application/json'
},
body: JSON.stringify({
oracleId: 'my-oracle',
timeRange: { start: '2024-01-01', end: '2024-12-31' }
})
});
const trainResult = await trainResponse.json();
// Generate ML prediction
const predictionResponse = await fetch('http://localhost:3000/api/ml/predict', {
method: 'POST',
headers: {
'Authorization': 'Bearer your-jwt-token',
'Content-Type': 'application/json'
},
body: JSON.stringify({
oracleId: 'my-oracle',
judgment: { T: 0.8, I: 0.1, F: 0.1 },
predictionType: 'success_probability',
context: { pair: 'BTC/USDT' }
})
});
const prediction = await predictionResponse.json();
// Get trend analysis
const trendsResponse = await fetch('http://localhost:3000/api/ml/trends/my-oracle?timeRange=2024-01-01,2024-12-31', {
headers: { 'Authorization': 'Bearer your-jwt-token' }
});
const trends = await trendsResponse.json();
// Get predictive alerts
const alertsResponse = await fetch('http://localhost:3000/api/ml/alerts/my-oracle', {
headers: { 'Authorization': 'Bearer your-jwt-token' }
});
const alerts = await alertsResponse.json();
The system provides automatic performance grading:
import { PerformanceOracle } from 'opentrustprotocol-oracle';
const oracle = new PerformanceOracle({
oracleId: 'custom-oracle',
version: '1.0.0'
}, storage, {
minConfidenceThreshold: 0.3,
maxOutcomeAge: 7 * 24 * 60 * 60 * 1000, // 7 days
requiredFields: ['judgment_id', 'T', 'I', 'F', 'outcome_type'],
customValidator: (outcome) => {
// Custom validation logic
return outcome.metadata && outcome.metadata.customField;
}
});
import { MemoryStorage } from 'opentrustprotocol-oracle';
const storage = new MemoryStorage();
// Get storage statistics
const stats = storage.getStorageStatistics();
console.log(`Total Pairs: ${stats.totalPairs}`);
console.log(`Memory Usage: ${(stats.memoryUsage / 1024 / 1024).toFixed(2)} MB`);
// Cleanup old data
const cleanedCount = await storage.cleanup(30 * 24 * 60 * 60 * 1000); // 30 days
console.log(`Cleaned up ${cleanedCount} old pairs`);
# Clone the repository
git clone https://github.com/draxork/opentrustprotocol-oracle.git
cd opentrustprotocol-oracle
# Start the complete system
docker-compose up -d
# View logs
docker-compose logs -f
# Stop the system
docker-compose down
# Build production image
docker build -t opentrustprotocol-oracle:4.0.0 .
# Run with production configuration
docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
# Required environment variables
export API_PORT=3000
export JWT_SECRET=your-secure-jwt-secret
export POSTGRES_HOST=localhost
export POSTGRES_PORT=5432
export POSTGRES_DB=oracle_db
export POSTGRES_USER=oracle_user
export POSTGRES_PASSWORD=oracle_password
All API endpoints require JWT authentication:
# Get authentication token
curl -X POST http://localhost:3000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "password"}'
# Use token in subsequent requests
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
http://localhost:3000/api/oracles
POST /api/oracles - Create new oracleGET /api/oracles - List all oraclesGET /api/oracles/:id - Get oracle detailsGET /api/oracles/:id/status - Get oracle statusPOST /api/oracles/:id/outcomes - Record outcomeGET /api/oracles/:id/outcomes - Get oracle outcomesGET /api/oracles/:id/metrics - Get performance metricsGET /api/dashboard/metrics - Get dashboard metricsGET /api/dashboard/trends - Get performance trendsPOST /api/dashboard/report - Generate performance reportGET /api/metrics/calibration - Get calibration metrics with bucket analysisGET /api/metrics/voi - Get Value of Indeterminacy metrics with correlationGET /api/metrics/mapper/:mapperId - Get performance metrics for specific mapperGET /api/metrics/performance/:oracleId - Get comprehensive performance analysisGET /api/metrics/mappers - Get performance for all mappersGET /api/storage/stats - Get storage statisticsGET /api/storage/pairs - Get judgment pairsGET /api/storage/pairs/:id - Get specific pairVisit http://localhost:3000/api-docs for interactive API documentation.
# Run tests
npm test
# Run tests with coverage
npm run test -- --coverage
# Run specific test file
npm test -- oracle.test.ts
OracleServerComplete production server with REST API and WebSocket support.
Methods:
start(): Start the serverstop(): Stop the server gracefullygetStatus(): Get server statusEnhancedOracleAdvanced oracle with integrated analytics engine.
Methods:
recordOutcome(decision, outcome, context?): Record an outcomegetRealTimeMetrics(): Get real-time performance metricsgetOracleStatus(): Get oracle statusgetPerformanceAnalysis(): Get detailed performance analysisexportData(): Export oracle dataPerformanceDashboardMulti-oracle monitoring and analytics dashboard.
Methods:
registerOracle(oracle): Register an oracle for monitoringstartMonitoring(interval): Start real-time monitoringgetCurrentMetrics(): Get current dashboard metricsgetPerformanceTrends(): Get performance trendsgenerateReport(): Generate comprehensive reportTradingOracleSpecialized oracle for financial trading outcomes.
Methods:
recordTradingOutcome(originalJudgment, tradeContext, marketSnapshot?): Record trading outcomerecordSuccessfulTrade(originalJudgment, tradeContext, profitLoss, marketSnapshot?): Record successful traderecordFailedTrade(originalJudgment, tradeContext, lossAmount, marketSnapshot?): Record failed tradegetTradingPerformance(pair?): Get trading performance metricsMedicalOracleSpecialized oracle for healthcare outcomes.
Methods:
recordTreatmentOutcome(originalJudgment, medicalContext, outcomeDetails): Record treatment outcomerecordSuccessfulTreatment(originalJudgment, medicalContext, recoveryTime, improvementScore?): Record successful treatmentrecordFailedTreatment(originalJudgment, medicalContext, failureReason, complications?): Record failed treatmentgetSafetyAlerts(): Get safety alertsPostgreSQLStorageProduction-ready database storage with full persistence.
Methods:
initialize(): Initialize database connectionsavePair(pair): Save judgment pair to databasegetPair(judgmentId): Retrieve judgment pairgetPairsByOracle(oracleId): Get all pairs for an oraclegetStorageStats(): Get storage statisticscleanup(olderThanMs): Clean up old dataMemoryStorageHigh-performance in-memory storage for development.
Methods:
storePair(pair): Store judgment pair in memorygetPair(judgmentId): Retrieve judgment pairgetPairsByOracle(oracleId): Get all pairs for an oraclegetStorageStats(): Get storage statisticscleanup(olderThanMs): Clean up old dataOTPAnalyticsEngineAnalytics engine for performance analysis.
Methods:
calculateCalibration(pairs): Calculate calibration metricscalculateVoI(pairs): Calculate VoI metricsanalyzePerformance(oracleId, pairs): Comprehensive performance analysiscalculateSuccessRate(pairs): Calculate success ratecalculatePerformanceGrade(rate, calibration, voi): Calculate performance gradeTradingContextinterface TradingContext {
pair: string;
direction: 'long' | 'short';
entryPrice: number;
exitPrice?: number;
positionSize: number;
marketConditions: {
volatility: number;
volume: number;
trend: 'bullish' | 'bearish' | 'sideways';
};
risk: {
stopLoss?: number;
takeProfit?: number;
positionSize: number;
};
}
MedicalContextinterface MedicalContext {
patientId: string;
condition: string;
treatment: string;
followUpDays: number;
medicalHistory?: string[];
protocol: {
dosage?: string;
frequency?: string;
duration?: string;
};
}
We welcome contributions! Please see our Contributing Guide for details.
# Clone the repository
git clone https://github.com/draxork/opentrustprotocol-oracle.git
# Install dependencies
npm install
# Build the project
npm run build
# Run tests
npm test
# Run linting
npm run lint
This project is licensed under the MIT License - see the LICENSE file for details.
🔮 The future of decision-making is here. Join the Circle of Trust with OpenTrust Protocol Oracle.
FAQs
Performance Oracle & Analytics Engine for OpenTrust Protocol - Real-world outcome tracking and performance measurement
The npm package opentrustprotocol-oracle receives a total of 0 weekly downloads. As such, opentrustprotocol-oracle popularity was classified as not popular.
We found that opentrustprotocol-oracle demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.