celo-poll/scripts/test-apis.ts
2025-12-08 16:31:30 +03:00

317 lines
11 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* API Testing Script
* Tests all oracle integrations to verify they work
*
* Usage: npx tsx scripts/test-apis.ts
*/
import { getChainlinkPrice, CHAINLINK_FEEDS } from '../lib/oracle/chainlink'
import { getCurveTokenPrice, getCurveSupportedChains } from '../lib/oracle/curve'
import { getDexScreenerPair, searchDexScreenerPairs } from '../lib/oracle/dexscreener'
import { getESPNScoreboard, getESPNGame, ESPN_SPORTS } from '../lib/oracle/espn'
import { fetchExternalAPI, testAPIConfiguration } from '../lib/oracle/external-api'
console.log('๐Ÿงช Testing PollCelo Oracle APIs...\n')
async function testChainlink() {
console.log('โ”'.repeat(80))
console.log('1๏ธโƒฃ CHAINLINK PRICE FEEDS')
console.log('โ”'.repeat(80))
try {
// Test BTC/USD
console.log('\n๐Ÿ“Š Testing BTC/USD feed...')
const btcPrice = await getChainlinkPrice(CHAINLINK_FEEDS['BTC/USD'])
if (btcPrice) {
console.log(`โœ… BTC/USD: $${btcPrice.price.toLocaleString()}`)
console.log(` Decimals: ${btcPrice.decimals}`)
console.log(` Updated: ${new Date(btcPrice.updatedAt * 1000).toLocaleString()}`)
} else {
console.log('โŒ Failed to get BTC price')
}
// Test ETH/USD
console.log('\n๐Ÿ“Š Testing ETH/USD feed...')
const ethPrice = await getChainlinkPrice(CHAINLINK_FEEDS['ETH/USD'])
if (ethPrice) {
console.log(`โœ… ETH/USD: $${ethPrice.price.toLocaleString()}`)
console.log(` Decimals: ${ethPrice.decimals}`)
console.log(` Updated: ${new Date(ethPrice.updatedAt * 1000).toLocaleString()}`)
} else {
console.log('โŒ Failed to get ETH price')
}
// Test CELO/USD
console.log('\n๐Ÿ“Š Testing CELO/USD feed...')
const celoPrice = await getChainlinkPrice(CHAINLINK_FEEDS['CELO/USD'])
if (celoPrice) {
console.log(`โœ… CELO/USD: $${celoPrice.price.toFixed(4)}`)
console.log(` Decimals: ${celoPrice.decimals}`)
console.log(` Updated: ${new Date(celoPrice.updatedAt * 1000).toLocaleString()}`)
} else {
console.log('โŒ Failed to get CELO price')
}
console.log('\nโœ… Chainlink tests passed!')
return true
} catch (error: any) {
console.error('\nโŒ Chainlink test failed:', error.message)
return false
}
}
async function testCurve() {
console.log('\nโ”'.repeat(80))
console.log('2๏ธโƒฃ CURVE FINANCE API')
console.log('โ”'.repeat(80))
try {
// Test supported chains
console.log('\n๐Ÿ“Š Fetching supported chains...')
const chains = await getCurveSupportedChains()
if (chains.length > 0) {
console.log(`โœ… Found ${chains.length} supported chains`)
console.log(` Chains: ${chains.slice(0, 5).join(', ')}${chains.length > 5 ? '...' : ''}`)
} else {
console.log('โš ๏ธ No chains returned (API might be down)')
}
// Test token price on Celo
console.log('\n๐Ÿ“Š Testing cUSD price on Celo...')
const cUSDAddress = '0x765DE816845861e75A25fCA122bb6898B8B1282a'
const price = await getCurveTokenPrice('celo', cUSDAddress)
if (price) {
console.log(`โœ… cUSD price: $${price.price.toFixed(4)}`)
console.log(` Source: ${price.source}`)
console.log(` Timestamp: ${new Date(price.timestamp).toLocaleString()}`)
} else {
console.log('โš ๏ธ Price not available (might not be indexed by Curve)')
}
console.log('\nโœ… Curve tests completed!')
return true
} catch (error: any) {
console.error('\nโŒ Curve test failed:', error.message)
return false
}
}
async function testDexScreener() {
console.log('\nโ”'.repeat(80))
console.log('3๏ธโƒฃ DEXSCREENER API')
console.log('โ”'.repeat(80))
try {
// Test popular pair (ETH/USDC on Uniswap V3)
console.log('\n๐Ÿ“Š Testing ETH/USDC pair on Uniswap V3...')
const ethUsdcPair = '0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640'
const pair = await getDexScreenerPair(ethUsdcPair)
if (pair) {
console.log(`โœ… Pair: ${pair.baseToken.symbol}/${pair.quoteToken.symbol}`)
console.log(` Price: $${parseFloat(pair.priceUsd).toFixed(2)}`)
console.log(` Volume 24h: $${pair.volume24h.toLocaleString()}`)
console.log(` Liquidity: $${pair.liquidity.usd.toLocaleString()}`)
console.log(` Price Change 24h: ${pair.priceChange.h24.toFixed(2)}%`)
console.log(` Chain: ${pair.chainId}`)
console.log(` DEX: ${pair.dexId}`)
} else {
console.log('โŒ Failed to get pair data')
}
// Test search by token
console.log('\n๐Ÿ“Š Searching for USDC pairs...')
const usdcAddress = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'
const pairs = await searchDexScreenerPairs(usdcAddress)
if (pairs.length > 0) {
console.log(`โœ… Found ${pairs.length} pairs with USDC`)
console.log(` Top 3 pairs:`)
pairs.slice(0, 3).forEach((p, i) => {
console.log(` ${i + 1}. ${p.baseToken.symbol}/${p.quoteToken.symbol} on ${p.dexId}`)
})
} else {
console.log('โš ๏ธ No pairs found')
}
console.log('\nโœ… DexScreener tests passed!')
return true
} catch (error: any) {
console.error('\nโŒ DexScreener test failed:', error.message)
return false
}
}
async function testESPN() {
console.log('\nโ”'.repeat(80))
console.log('4๏ธโƒฃ ESPN SPORTS API')
console.log('โ”'.repeat(80))
try {
// Test NFL scoreboard
console.log('\n๐Ÿ“Š Testing NFL scoreboard...')
const nflGames = await getESPNScoreboard('football/nfl')
if (nflGames.length > 0) {
console.log(`โœ… Found ${nflGames.length} NFL games`)
console.log(` Recent games:`)
nflGames.slice(0, 3).forEach((game, i) => {
const comp = game.competitions[0]
const home = comp.competitors.find(c => c.homeAway === 'home')
const away = comp.competitors.find(c => c.homeAway === 'away')
console.log(` ${i + 1}. ${away?.team.displayName} @ ${home?.team.displayName}`)
console.log(` Score: ${away?.score} - ${home?.score}`)
console.log(` Status: ${game.status.type.description}`)
})
} else {
console.log('โš ๏ธ No games found (might be off-season)')
}
// Test NBA scoreboard
console.log('\n๐Ÿ“Š Testing NBA scoreboard...')
const nbaGames = await getESPNScoreboard('basketball/nba')
if (nbaGames.length > 0) {
console.log(`โœ… Found ${nbaGames.length} NBA games`)
console.log(` Recent games:`)
nbaGames.slice(0, 3).forEach((game, i) => {
const comp = game.competitions[0]
const home = comp.competitors.find(c => c.homeAway === 'home')
const away = comp.competitors.find(c => c.homeAway === 'away')
console.log(` ${i + 1}. ${away?.team.displayName} @ ${home?.team.displayName}`)
console.log(` Score: ${away?.score} - ${home?.score}`)
})
} else {
console.log('โš ๏ธ No games found')
}
// Test Soccer (EPL)
console.log('\n๐Ÿ“Š Testing Soccer (EPL) scoreboard...')
const soccerGames = await getESPNScoreboard('soccer', undefined, 'eng.1')
if (soccerGames.length > 0) {
console.log(`โœ… Found ${soccerGames.length} EPL games`)
console.log(` Recent matches:`)
soccerGames.slice(0, 3).forEach((game, i) => {
const comp = game.competitions[0]
const home = comp.competitors.find(c => c.homeAway === 'home')
const away = comp.competitors.find(c => c.homeAway === 'away')
console.log(` ${i + 1}. ${home?.team.displayName} vs ${away?.team.displayName}`)
console.log(` Score: ${home?.score} - ${away?.score}`)
})
} else {
console.log('โš ๏ธ No games found')
}
console.log('\nโœ… ESPN tests completed!')
return true
} catch (error: any) {
console.error('\nโŒ ESPN test failed:', error.message)
return false
}
}
async function testExternalAPIs() {
console.log('\nโ”'.repeat(80))
console.log('5๏ธโƒฃ EXTERNAL APIs')
console.log('โ”'.repeat(80))
try {
// Test CoinGecko (no key required)
console.log('\n๐Ÿ“Š Testing CoinGecko API...')
const coinGeckoConfig = {
apiEndpoint: 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd',
jsonPath: 'bitcoin.usd',
apiMethod: 'GET' as const,
}
const coinGeckoData = await fetchExternalAPI(coinGeckoConfig)
console.log(`โœ… CoinGecko response:`)
console.log(` Bitcoin: $${coinGeckoData.bitcoin.usd.toLocaleString()}`)
console.log(` Ethereum: $${coinGeckoData.ethereum.usd.toLocaleString()}`)
// Test Exchange Rate API (no key required)
console.log('\n๐Ÿ“Š Testing Exchange Rate API (USD/TRY)...')
const forexConfig = {
apiEndpoint: 'https://api.exchangerate.host/latest?base=USD&symbols=TRY',
jsonPath: 'rates.TRY',
apiMethod: 'GET' as const,
}
const forexData = await fetchExternalAPI(forexConfig)
console.log(`โœ… Exchange rate:`)
console.log(` 1 USD = ${forexData.rates.TRY.toFixed(2)} TRY`)
// Test weather API (requires key, will fail gracefully)
console.log('\n๐Ÿ“Š Testing Weather API (public endpoint)...')
const weatherConfig = {
apiEndpoint: 'https://wttr.in/Istanbul?format=j1',
jsonPath: 'current_condition.0.temp_C',
apiMethod: 'GET' as const,
}
try {
const weatherData = await fetchExternalAPI(weatherConfig)
console.log(`โœ… Weather in Istanbul:`)
console.log(` Temperature: ${weatherData.current_condition[0].temp_C}ยฐC`)
} catch (error) {
console.log('โš ๏ธ Weather API test skipped (requires different endpoint)')
}
console.log('\nโœ… External API tests completed!')
return true
} catch (error: any) {
console.error('\nโŒ External API test failed:', error.message)
return false
}
}
async function runAllTests() {
console.log('๐Ÿš€ Starting comprehensive API tests...\n')
const results = {
chainlink: false,
curve: false,
dexscreener: false,
espn: false,
external: false,
}
results.chainlink = await testChainlink()
results.curve = await testCurve()
results.dexscreener = await testDexScreener()
results.espn = await testESPN()
results.external = await testExternalAPIs()
// Summary
console.log('\nโ”'.repeat(80))
console.log('๐Ÿ“Š TEST SUMMARY')
console.log('โ”'.repeat(80))
console.log(`\n1. Chainlink: ${results.chainlink ? 'โœ… PASSED' : 'โŒ FAILED'}`)
console.log(`2. Curve: ${results.curve ? 'โœ… PASSED' : 'โŒ FAILED'}`)
console.log(`3. DexScreener: ${results.dexscreener ? 'โœ… PASSED' : 'โŒ FAILED'}`)
console.log(`4. ESPN: ${results.espn ? 'โœ… PASSED' : 'โŒ FAILED'}`)
console.log(`5. External APIs: ${results.external ? 'โœ… PASSED' : 'โŒ FAILED'}`)
const passed = Object.values(results).filter(r => r).length
const total = Object.keys(results).length
console.log(`\n${passed}/${total} tests passed`)
if (passed === total) {
console.log('\n๐ŸŽ‰ All APIs are working correctly!')
} else {
console.log('\nโš ๏ธ Some APIs failed. Check the logs above for details.')
}
console.log('\n' + 'โ”'.repeat(80))
}
// Run tests
runAllTests().catch(console.error)