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

148 lines
4.1 KiB
TypeScript

/**
* Chainlink Price Feed Oracle
* Uses Chainlink price feeds on Celo for crypto/forex prices
* https://docs.chain.link/data-feeds/price-feeds/addresses?network=celo
*/
import { createPublicClient, http, parseAbi } from 'viem'
import { celo } from 'viem/chains'
// Chainlink Price Feed ABI (only what we need)
const PRICE_FEED_ABI = parseAbi([
'function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)',
'function decimals() external view returns (uint8)',
])
// Chainlink price feed addresses on Celo Mainnet
export const CHAINLINK_FEEDS = {
'BTC/USD': '0x898E82a89c21469df34A8A9a36D1873f74Be3A1D' as `0x${string}`,
'ETH/USD': '0x1D6FBa9e67f8cEB0c04AAF0412DA3c18EC0f0b5' as `0x${string}`,
'CELO/USD': '0xa9f30e6EdFf0bB8C2fB6c474D57d9B45F8323e34' as `0x${string}`,
// Add more as available on Celo
}
export interface ChainlinkConfig {
feedAddress: string
targetPrice?: number
comparisonType?: 'above' | 'below' | 'between'
minPrice?: number
maxPrice?: number
}
export interface ChainlinkPriceData {
price: number
decimals: number
updatedAt: number
roundId: bigint
}
// Create public client for reading price feeds
const publicClient = createPublicClient({
chain: celo,
transport: http(process.env.NEXT_PUBLIC_CELO_RPC_URL || 'https://forno.celo.org'),
})
/**
* Get latest price from Chainlink feed
*/
export async function getChainlinkPrice(
feedAddress: string
): Promise<ChainlinkPriceData | null> {
try {
const address = feedAddress as `0x${string}`
// Get decimals
const decimals = await publicClient.readContract({
address,
abi: PRICE_FEED_ABI,
functionName: 'decimals',
})
// Get latest round data
const [roundId, answer, , updatedAt] = await publicClient.readContract({
address,
abi: PRICE_FEED_ABI,
functionName: 'latestRoundData',
})
// Convert answer to human-readable price
const price = Number(answer) / Math.pow(10, decimals)
return {
price,
decimals,
updatedAt: Number(updatedAt),
roundId,
}
} catch (error) {
console.error(`Failed to get Chainlink price from ${feedAddress}:`, error)
return null
}
}
/**
* Verify poll result using Chainlink price feed
*/
export async function verifyChainlinkPoll(
config: ChainlinkConfig,
pollEndTime: number
): Promise<{ correct: boolean; optionIndex: number; proof: any }> {
try {
const priceData = await getChainlinkPrice(config.feedAddress)
if (!priceData) {
throw new Error('Failed to fetch price from Chainlink')
}
// Check if price data is recent (within 1 hour of poll end)
const timeDiff = Math.abs(priceData.updatedAt * 1000 - pollEndTime)
if (timeDiff > 3600000) {
console.warn('Chainlink price data is stale')
}
let correctOptionIndex = -1
// Determine correct option based on comparison type
if (config.comparisonType === 'above' && config.targetPrice) {
correctOptionIndex = priceData.price > config.targetPrice ? 0 : 1
} else if (config.comparisonType === 'below' && config.targetPrice) {
correctOptionIndex = priceData.price < config.targetPrice ? 0 : 1
} else if (
config.comparisonType === 'between' &&
config.minPrice &&
config.maxPrice
) {
if (priceData.price >= config.minPrice && priceData.price <= config.maxPrice) {
correctOptionIndex = 0
} else if (priceData.price < config.minPrice) {
correctOptionIndex = 1
} else {
correctOptionIndex = 2
}
}
return {
correct: correctOptionIndex >= 0,
optionIndex: correctOptionIndex,
proof: {
source: 'chainlink',
feedAddress: config.feedAddress,
price: priceData.price,
decimals: priceData.decimals,
updatedAt: priceData.updatedAt,
roundId: priceData.roundId.toString(),
},
}
} catch (error) {
console.error('Chainlink verification failed:', error)
throw error
}
}
/**
* Get all available Chainlink feeds
*/
export function getAvailableFeeds(): Record<string, string> {
return CHAINLINK_FEEDS
}