import {z} from 'zod' export type GetApiTickersArgs = {quotes?: string | undefined}; export type GetApiTickersOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const quote = z.object({price: z.number().optional(), volume_24h: z.number().optional(), volume_24h_change_24h: z.number().optional(), market_cap: z.number().optional(), market_cap_change_24h: z.number().optional(), percent_change_1h: z.number().optional(), percent_change_12h: z.number().optional(), percent_change_24h: z.number().optional(), percent_change_7d: z.number().optional(), percent_change_30d: z.number().optional(), percent_change_1y: z.number().optional(), ath_price: z.number().optional(), ath_date: z.string().optional(), percent_from_price_ath: z.number().optional()}); export const quotes = z.record(z.string(), quote); export const tick = z.object({id: z.string().optional(), name: z.string().optional(), symbol: z.string().optional(), rank: z.number().optional(), circulating_supply: z.number().optional(), total_supply: z.number().optional(), max_supply: z.number().optional(), beta_value: z.number().optional(), first_data_at: z.string().optional(), last_updated: z.string().optional(), quotes: quotes.optional()}); export const getApiTickersResponse = z.array(tick); 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 }; /** * Get tickers for all active coins * * GET /tickers */ export const getApiTickers = async (args: GetApiTickersArgs, options?: GetApiTickersOptions) => { const {baseUrl = "https://api.coinpaprika.com/v1", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.quotes != null) query.append("quotes", String(args.quotes)) const url = `${baseUrl.replace(/\/+$/, '')}/tickers${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(getApiTickersResponse, await res.json()) };