import {z} from 'zod' export type GetApiMarketTokenSeriesArgs = {timeframe: '1D' | '1W' | '1M' | '1Y' | 'ALL', token: string}; export type GetApiMarketTokenSeriesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const marketOhlcvPointResponseDto = z.object({time: z.union([z.string(), z.number()]), open: z.number(), high: z.number(), low: z.number(), close: z.number(), volume: z.number().optional()}); export const marketTokenSeriesResponseDto = z.object({ohlcv: z.array(marketOhlcvPointResponseDto), currentPrice: z.number().nullable(), change24h: z.number().nullable(), volume24h: z.number().nullable(), source: z.enum(["inhouse", "coingecko", "chainmeter", "none"])}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Normalized USD OHLCV + current price for a token at a timeframe * * GET /market/token-series */ export const getApiMarketTokenSeries = async (args: GetApiMarketTokenSeriesArgs, options?: GetApiMarketTokenSeriesOptions) => { const {baseUrl = "https://swap-backend.stage.defi.ovh.gala.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.timeframe != null) query.append("timeframe", String(args.timeframe)) if (args.token != null) query.append("token", String(args.token)) const url = `${baseUrl.replace(/\/+$/, '')}/market/token-series${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(marketTokenSeriesResponseDto, await res.json()) };