|
| 1 | +/** |
| 2 | + * Code Mode bindings — maps codemode.* calls to Pyth API handlers. |
| 3 | + * get_latest_price receives server-injected token; model never sees it. |
| 4 | + */ |
| 5 | + |
| 6 | +import type { HistoryClient } from "../clients/history.js"; |
| 7 | +import type { RouterClient } from "../clients/router.js"; |
| 8 | +import type { Config } from "../config.js"; |
| 9 | +import { ASSET_TYPES, RESOLUTIONS } from "../constants.js"; |
| 10 | +import type { Logger } from "pino"; |
| 11 | +import { resolveChannel } from "../utils/channel.js"; |
| 12 | +import { addDisplayPrices } from "../utils/display-price.js"; |
| 13 | +import { |
| 14 | + alignTimestampToChannel, |
| 15 | + normalizeTimestampToMicroseconds, |
| 16 | +} from "../utils/timestamp.js"; |
| 17 | + |
| 18 | +export type BindingContext = { |
| 19 | + config: Config; |
| 20 | + historyClient: HistoryClient; |
| 21 | + routerClient: RouterClient; |
| 22 | + logger: Logger; |
| 23 | + /** Server-managed token for get_latest_price. Injected server-side only. */ |
| 24 | + serverToken: string | undefined; |
| 25 | +}; |
| 26 | + |
| 27 | +/** Copy out isolate-held values (handles ivm.Reference) */ |
| 28 | +function unwrapArg<T>(arg: unknown): T { |
| 29 | + if (arg == null) return arg as T; |
| 30 | + const ref = arg as { copy?: () => T }; |
| 31 | + if (typeof ref.copy === "function") return ref.copy() as T; |
| 32 | + return arg as T; |
| 33 | +} |
| 34 | + |
| 35 | +export function createBindings(ctx: BindingContext): Record< |
| 36 | + string, |
| 37 | + (arg: unknown) => Promise<unknown> |
| 38 | +> { |
| 39 | + const { config, historyClient, routerClient, logger, serverToken } = ctx; |
| 40 | + |
| 41 | + return { |
| 42 | + async get_symbols(arg: unknown) { |
| 43 | + const p = unwrapArg<{ |
| 44 | + query?: string; |
| 45 | + asset_type?: string; |
| 46 | + limit?: number; |
| 47 | + offset?: number; |
| 48 | + }>(arg); |
| 49 | + const asset_type = p?.asset_type; |
| 50 | + const limit = Math.min( |
| 51 | + 200, |
| 52 | + Math.max(1, p?.limit ?? 50), |
| 53 | + ); |
| 54 | + const offset = Math.max(0, p?.offset ?? 0); |
| 55 | + |
| 56 | + const { data: feeds } = await historyClient.getSymbols( |
| 57 | + undefined, |
| 58 | + asset_type && ASSET_TYPES.includes(asset_type) ? asset_type : undefined, |
| 59 | + ); |
| 60 | + |
| 61 | + let filtered = feeds; |
| 62 | + const q = (p?.query ?? "").trim().toLowerCase(); |
| 63 | + if (q) { |
| 64 | + filtered = feeds.filter( |
| 65 | + (f) => |
| 66 | + f.name.toLowerCase().includes(q) || |
| 67 | + f.symbol.toLowerCase().includes(q) || |
| 68 | + f.description.toLowerCase().includes(q), |
| 69 | + ); |
| 70 | + } |
| 71 | + |
| 72 | + const totalAvailable = filtered.length; |
| 73 | + const page = filtered.slice(offset, offset + limit); |
| 74 | + const hasMore = offset + limit < totalAvailable; |
| 75 | + |
| 76 | + return { |
| 77 | + count: page.length, |
| 78 | + feeds: page, |
| 79 | + has_more: hasMore, |
| 80 | + next_offset: hasMore ? offset + limit : null, |
| 81 | + offset, |
| 82 | + total_available: totalAvailable, |
| 83 | + }; |
| 84 | + }, |
| 85 | + |
| 86 | + async get_historical_price(arg: unknown) { |
| 87 | + const p = unwrapArg<{ |
| 88 | + channel?: string; |
| 89 | + price_feed_ids?: number[]; |
| 90 | + symbols?: string[]; |
| 91 | + timestamp: number; |
| 92 | + }>(arg); |
| 93 | + |
| 94 | + const effectiveSymbols = |
| 95 | + (p?.price_feed_ids?.length ?? 0) > 0 ? undefined : p?.symbols; |
| 96 | + if ( |
| 97 | + !(p?.price_feed_ids?.length ?? 0) && |
| 98 | + !(effectiveSymbols?.length ?? 0) |
| 99 | + ) { |
| 100 | + throw new Error( |
| 101 | + "At least one of 'price_feed_ids' or 'symbols' is required", |
| 102 | + ); |
| 103 | + } |
| 104 | + |
| 105 | + const channel = resolveChannel(p?.channel, config); |
| 106 | + let ids: number[] = p?.price_feed_ids ? [...p.price_feed_ids] : []; |
| 107 | + |
| 108 | + if ((effectiveSymbols?.length ?? 0) > 0) { |
| 109 | + const { data: allFeeds } = await historyClient.getSymbols(); |
| 110 | + for (const symbol of effectiveSymbols ?? []) { |
| 111 | + const feed = allFeeds.find((f) => f.symbol === symbol); |
| 112 | + if (!feed) |
| 113 | + throw new Error( |
| 114 | + `Feed not found: ${symbol}. Use get_symbols to discover available feeds.`, |
| 115 | + ); |
| 116 | + ids.push(feed.pyth_lazer_id); |
| 117 | + } |
| 118 | + } |
| 119 | + ids = [...new Set(ids)]; |
| 120 | + |
| 121 | + const timestampUs = alignTimestampToChannel( |
| 122 | + normalizeTimestampToMicroseconds(p!.timestamp), |
| 123 | + channel, |
| 124 | + ); |
| 125 | + const { data: prices } = await historyClient.getHistoricalPrice( |
| 126 | + channel, |
| 127 | + ids, |
| 128 | + timestampUs, |
| 129 | + ); |
| 130 | + return prices.map((price) => addDisplayPrices(price)); |
| 131 | + }, |
| 132 | + |
| 133 | + async get_candlestick_data(arg: unknown) { |
| 134 | + const p = unwrapArg<{ |
| 135 | + channel?: string; |
| 136 | + from: number; |
| 137 | + to: number; |
| 138 | + resolution: string; |
| 139 | + symbol: string; |
| 140 | + }>(arg); |
| 141 | + |
| 142 | + if (!p?.symbol) throw new Error("symbol is required"); |
| 143 | + if (p.from >= p.to) throw new Error("'from' must be before 'to'"); |
| 144 | + |
| 145 | + const resolution = p.resolution; |
| 146 | + if (!RESOLUTIONS.includes(resolution as (typeof RESOLUTIONS)[number])) { |
| 147 | + throw new Error( |
| 148 | + `Invalid resolution. Valid: ${RESOLUTIONS.join(", ")}`, |
| 149 | + ); |
| 150 | + } |
| 151 | + |
| 152 | + const channel = resolveChannel(p.channel, config); |
| 153 | + const { data } = await historyClient.getCandlestickData( |
| 154 | + channel, |
| 155 | + p.symbol, |
| 156 | + resolution, |
| 157 | + p.from, |
| 158 | + p.to, |
| 159 | + ); |
| 160 | + |
| 161 | + if (data.s === "no_data") |
| 162 | + throw new Error( |
| 163 | + "No candlestick data available for the requested range. Try a different time range or symbol.", |
| 164 | + ); |
| 165 | + if (data.s === "error") |
| 166 | + throw new Error(data.errmsg ?? "Unknown error from Pyth History API"); |
| 167 | + |
| 168 | + return data; |
| 169 | + }, |
| 170 | + |
| 171 | + async get_latest_price(arg: unknown) { |
| 172 | + const p = unwrapArg<{ |
| 173 | + channel?: string; |
| 174 | + price_feed_ids?: number[]; |
| 175 | + properties?: string[]; |
| 176 | + symbols?: string[]; |
| 177 | + }>(arg); |
| 178 | + |
| 179 | + if (!serverToken) { |
| 180 | + throw new Error( |
| 181 | + "Server is not configured with a Pyth Pro access token. get_latest_price is unavailable.", |
| 182 | + ); |
| 183 | + } |
| 184 | + |
| 185 | + const effectiveSymbols = |
| 186 | + (p?.price_feed_ids?.length ?? 0) > 0 ? undefined : p?.symbols; |
| 187 | + const effectiveCount = |
| 188 | + (effectiveSymbols?.length ?? 0) + (p?.price_feed_ids?.length ?? 0); |
| 189 | + |
| 190 | + if (effectiveCount === 0) { |
| 191 | + throw new Error( |
| 192 | + "At least one of 'symbols' or 'price_feed_ids' is required", |
| 193 | + ); |
| 194 | + } |
| 195 | + if (effectiveCount > 100) { |
| 196 | + throw new Error( |
| 197 | + "Combined total of symbols and price_feed_ids must not exceed 100", |
| 198 | + ); |
| 199 | + } |
| 200 | + |
| 201 | + const channel = resolveChannel(p?.channel, config); |
| 202 | + const { data: feeds } = await routerClient.getLatestPrice( |
| 203 | + serverToken, |
| 204 | + effectiveSymbols, |
| 205 | + p?.price_feed_ids, |
| 206 | + p?.properties, |
| 207 | + channel, |
| 208 | + ); |
| 209 | + return feeds.map((f) => addDisplayPrices(f)); |
| 210 | + }, |
| 211 | + }; |
| 212 | +} |
0 commit comments