import {z} from 'zod' export type GetApiV1RatesMarketBenchmarkArgs = {fromAsset?: string | undefined, toAsset?: string | undefined, amount?: string | undefined, pairs?: string | undefined}; export type GetApiV1RatesMarketBenchmarkOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiV1RatesMarketBenchmarkResponse = z.object({data: z.union([z.object({fromAsset: z.string().optional(), toAsset: z.string().optional(), bestRate: z.string().nullable().optional()}), z.array(z.object({fromAsset: z.string().optional(), toAsset: z.string().optional(), bestRate: z.string().nullable().optional()}))]).optional(), message: z.string().optional(), statusCode: z.number().optional()}); 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 Market Benchmark * * GET /v1/rates/market-benchmark */ export const getApiV1RatesMarketBenchmark = async (args: GetApiV1RatesMarketBenchmarkArgs, options?: GetApiV1RatesMarketBenchmarkOptions) => { const {baseUrl = "https://api.blockradar.co", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.fromAsset != null) query.append("fromAsset", String(args.fromAsset)) if (args.toAsset != null) query.append("toAsset", String(args.toAsset)) if (args.amount != null) query.append("amount", String(args.amount)) if (args.pairs != null) query.append("pairs", String(args.pairs)) if (apiKey !== undefined) headers.set("x-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/rates/market-benchmark${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(getApiV1RatesMarketBenchmarkResponse, await res.json()) };