celo-poll/lib/oracle/external-api.ts
2025-12-08 16:31:30 +03:00

212 lines
5.8 KiB
TypeScript

/**
* External API Oracle
* Generic oracle for fetching data from any REST API
* Supports sports scores, weather, forex rates, etc.
*/
import axios from 'axios'
export interface ExternalAPIConfig {
apiEndpoint: string
apiMethod?: 'GET' | 'POST'
apiHeaders?: Record<string, string>
apiBody?: Record<string, any>
jsonPath: string // e.g., "data.score.home" or "main.temp"
comparisonType?: 'equals' | 'above' | 'below' | 'between' | 'greater_than_field'
targetValue?: string | number
compareWith?: string // JSON path to compare with
minValue?: number
maxValue?: number
}
/**
* Extract value from nested JSON using dot notation
* e.g., "data.score.home" -> obj.data.score.home
*/
function getNestedValue(obj: any, path: string): any {
return path.split('.').reduce((current, key) => current?.[key], obj)
}
/**
* Fetch data from external API
*/
export async function fetchExternalAPI(
config: ExternalAPIConfig
): Promise<any> {
try {
const response = await axios({
method: config.apiMethod || 'GET',
url: config.apiEndpoint,
headers: config.apiHeaders || {},
data: config.apiBody,
timeout: 10000, // 10 second timeout
})
return response.data
} catch (error) {
console.error(`Failed to fetch from ${config.apiEndpoint}:`, error)
throw error
}
}
/**
* Verify poll result using external API
*/
export async function verifyExternalAPIPoll(
config: ExternalAPIConfig,
pollEndTime: number
): Promise<{ correct: boolean; optionIndex: number; proof: any }> {
try {
// Fetch data from API
const apiData = await fetchExternalAPI(config)
// Extract value using JSON path
const value = getNestedValue(apiData, config.jsonPath)
if (value === undefined) {
throw new Error(`Could not find value at path: ${config.jsonPath}`)
}
let correctOptionIndex = -1
// Determine correct option based on comparison type
switch (config.comparisonType) {
case 'equals':
correctOptionIndex = value.toString() === config.targetValue?.toString() ? 0 : 1
break
case 'above':
if (config.targetValue !== undefined) {
correctOptionIndex = Number(value) > Number(config.targetValue) ? 0 : 1
}
break
case 'below':
if (config.targetValue !== undefined) {
correctOptionIndex = Number(value) < Number(config.targetValue) ? 0 : 1
}
break
case 'between':
if (config.minValue !== undefined && config.maxValue !== undefined) {
const numValue = Number(value)
if (numValue >= config.minValue && numValue <= config.maxValue) {
correctOptionIndex = 0
} else if (numValue < config.minValue) {
correctOptionIndex = 1
} else {
correctOptionIndex = 2
}
}
break
case 'greater_than_field':
// Compare two fields (e.g., home score vs away score)
if (config.compareWith) {
const compareValue = getNestedValue(apiData, config.compareWith)
if (Number(value) > Number(compareValue)) {
correctOptionIndex = 0 // First option wins
} else if (Number(value) < Number(compareValue)) {
correctOptionIndex = 1 // Second option wins
} else {
correctOptionIndex = 2 // Draw/tie
}
}
break
default:
throw new Error(`Unknown comparison type: ${config.comparisonType}`)
}
return {
correct: correctOptionIndex >= 0,
optionIndex: correctOptionIndex,
proof: {
source: 'external_api',
endpoint: config.apiEndpoint,
value,
jsonPath: config.jsonPath,
comparisonType: config.comparisonType,
timestamp: Date.now(),
rawResponse: apiData, // Include full response for transparency
},
}
} catch (error) {
console.error('External API verification failed:', error)
throw error
}
}
/**
* Common API configurations
*/
export const COMMON_APIS = {
// Turkish Central Bank forex rates
TCMB_FOREX: {
apiEndpoint: 'https://api.exchangerate.host/latest?base=USD&symbols=TRY',
jsonPath: 'rates.TRY',
apiMethod: 'GET' as const,
},
// OpenWeatherMap
OPENWEATHER: (city: string, apiKey: string) => ({
apiEndpoint: `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`,
jsonPath: 'main.temp',
apiMethod: 'GET' as const,
}),
// CoinGecko prices (no API key needed)
COINGECKO_PRICE: (coinId: string) => ({
apiEndpoint: `https://api.coingecko.com/api/v3/simple/price?ids=${coinId}&vs_currencies=usd`,
jsonPath: `${coinId}.usd`,
apiMethod: 'GET' as const,
}),
// Alternative forex API for USD/TRY
FOREX_HOST_USD_TRY: {
apiEndpoint: 'https://api.exchangerate.host/latest?base=USD&symbols=TRY',
jsonPath: 'rates.TRY',
apiMethod: 'GET' as const,
},
// Sports API (would need actual sports data provider)
SPORTS_SCORE: (gameId: string, apiKey: string) => ({
apiEndpoint: `https://api.sportsdata.io/v3/soccer/scores/json/game/${gameId}`,
jsonPath: 'HomeScore',
compareWith: 'AwayScore',
comparisonType: 'greater_than_field' as const,
apiHeaders: {
'Ocp-Apim-Subscription-Key': apiKey,
},
}),
}
/**
* Test API configuration before creating poll
*/
export async function testAPIConfiguration(
config: ExternalAPIConfig
): Promise<{ success: boolean; value?: any; error?: string }> {
try {
const data = await fetchExternalAPI(config)
const value = getNestedValue(data, config.jsonPath)
if (value === undefined) {
return {
success: false,
error: `Could not find value at path: ${config.jsonPath}`,
}
}
return {
success: true,
value,
}
} catch (error: any) {
return {
success: false,
error: error.message || 'Failed to fetch from API',
}
}
}