import {z} from 'zod' export type GetApiCmcV1TickerOptions = {baseUrl: string, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const coinMarketCapTicker = z.object({base_id: z.string(), quote_id: z.string(), base_name: z.string(), base_symbol: z.string(), quote_name: z.string(), quote_symbol: z.string(), last_price: z.number(), base_volume: z.number(), quote_volume: z.number(), isFrozen: z.union([z.literal(0), z.literal(1)])}); export const coinMarketCapTickerResponse = z.record(z.string(), coinMarketCapTicker); 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 }; /** * CoinMarketCap ticker (v1) * * GET /cmc/v1/ticker */ export const getApiCmcV1Ticker = async (options: GetApiCmcV1TickerOptions) => { const {baseUrl, fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (apiKey !== undefined) headers.set("X-API-Key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/cmc/v1/ticker${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(coinMarketCapTickerResponse, await res.json()) };