|
| 1 | +import { SOL_MINT, USDC_MINT } from './constants.js' |
| 2 | +import { resolveFetch } from './connection.js' |
| 3 | +import type { PythPrice, SolanaAgentToolOptions, TokenPrice } from './types.js' |
| 4 | + |
| 5 | +function aliasMint(id: string): string { |
| 6 | + const token = id.trim() |
| 7 | + if (/^sol$/i.test(token)) return SOL_MINT |
| 8 | + if (/^usdc$/i.test(token)) return USDC_MINT |
| 9 | + return token |
| 10 | +} |
| 11 | + |
| 12 | +/** Fetch a read-only USD token price from Jupiter Price API V3. */ |
| 13 | +export async function fetchTokenPrice( |
| 14 | + id: string, |
| 15 | + opts: SolanaAgentToolOptions = {}, |
| 16 | +): Promise<TokenPrice> { |
| 17 | + const mint = aliasMint(id) |
| 18 | + const base = opts.jupiterPriceBaseUrl ?? 'https://api.jup.ag/price/v3' |
| 19 | + const url = new URL(base) |
| 20 | + url.searchParams.set('ids', mint) |
| 21 | + const headers: Record<string, string> = {} |
| 22 | + const apiKey = opts.jupiterApiKey ?? process.env.JUPITER_API_KEY |
| 23 | + if (apiKey) headers['x-api-key'] = apiKey |
| 24 | + const res = await resolveFetch(opts)(url, { headers }) |
| 25 | + if (!res.ok) throw new Error(`Jupiter price ${res.status}: ${(await res.text()).slice(0, 160)}`) |
| 26 | + const body = await res.json() as Record<string, unknown> |
| 27 | + const item = body[mint] |
| 28 | + if (!item || typeof item !== 'object') throw new Error(`Jupiter price missing for ${mint}`) |
| 29 | + const o = item as Record<string, unknown> |
| 30 | + const usdPrice = Number(o.usdPrice) |
| 31 | + if (!Number.isFinite(usdPrice)) throw new Error(`Jupiter price for ${mint} has no numeric usdPrice`) |
| 32 | + return { |
| 33 | + id: mint, |
| 34 | + usdPrice, |
| 35 | + ...(typeof o.decimals === 'number' ? { decimals: o.decimals } : {}), |
| 36 | + ...(typeof o.blockId === 'number' ? { blockId: o.blockId } : {}), |
| 37 | + ...(typeof o.liquidity === 'number' ? { liquidity: o.liquidity } : {}), |
| 38 | + ...(typeof o.priceChange24h === 'number' ? { priceChange24h: o.priceChange24h } : {}), |
| 39 | + ...(typeof o.createdAt === 'string' ? { createdAt: o.createdAt } : {}), |
| 40 | + provider: 'jupiter', |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +/** Fetch a read-only latest price update from Pyth Hermes. */ |
| 45 | +export async function fetchPythPrice( |
| 46 | + priceFeedId: string, |
| 47 | + opts: SolanaAgentToolOptions = {}, |
| 48 | +): Promise<PythPrice> { |
| 49 | + const id = priceFeedId.trim().replace(/^0x/i, '') |
| 50 | + if (!/^[0-9a-fA-F]{64}$/.test(id)) throw new Error('Pyth priceFeedId must be a 32-byte hex string') |
| 51 | + const base = opts.pythHermesBaseUrl ?? 'https://hermes.pyth.network/v2/updates/price/latest' |
| 52 | + const url = new URL(base) |
| 53 | + url.searchParams.append('ids[]', id) |
| 54 | + const res = await resolveFetch(opts)(url) |
| 55 | + if (!res.ok) throw new Error(`Pyth Hermes ${res.status}: ${(await res.text()).slice(0, 160)}`) |
| 56 | + const body = await res.json() as { parsed?: Array<{ id?: string; price?: Record<string, unknown> }> } |
| 57 | + const parsed = body.parsed?.find((p) => p.id?.replace(/^0x/i, '').toLowerCase() === id.toLowerCase()) |
| 58 | + const price = parsed?.price |
| 59 | + if (!price) throw new Error(`Pyth price missing for ${id}`) |
| 60 | + const rawPrice = String(price.price ?? '') |
| 61 | + const exponent = Number(price.expo) |
| 62 | + const confidenceRaw = String(price.conf ?? '') |
| 63 | + const publishTime = Number(price.publish_time) |
| 64 | + const scaled = Number(rawPrice) * 10 ** exponent |
| 65 | + const confidence = Number(confidenceRaw) * 10 ** exponent |
| 66 | + if (!Number.isFinite(scaled) || !Number.isFinite(confidence) || !Number.isFinite(publishTime)) { |
| 67 | + throw new Error(`Pyth price for ${id} is malformed`) |
| 68 | + } |
| 69 | + return { |
| 70 | + id, |
| 71 | + price: scaled, |
| 72 | + rawPrice, |
| 73 | + confidence, |
| 74 | + exponent, |
| 75 | + publishTime, |
| 76 | + provider: 'pyth-hermes', |
| 77 | + } |
| 78 | +} |
0 commit comments