import {z} from 'zod' export type GetApiV1TokensArgs = {chains?: string | undefined, tags?: string | undefined, chainTypes?: string | undefined, minPriceUSD?: number | undefined, 'x-lifi-api-key'?: string | undefined}; export type GetApiV1TokensOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const token = z.object({address: z.string(), decimals: z.number(), symbol: z.string(), chainId: z.number(), coinKey: z.string().optional(), name: z.string(), logoURI: z.string().optional(), priceUSD: z.string().optional()}); export const getApiV1TokensResponse = z.object({"1": z.array(token).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 }; /** * Fetch all known tokens * * GET /v1/tokens */ export const getApiV1Tokens = async (args: GetApiV1TokensArgs, options?: GetApiV1TokensOptions) => { const {baseUrl = "https://li.quest", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.chains != null) query.append("chains", String(args.chains)) if (args.tags != null) query.append("tags", String(args.tags)) if (args.chainTypes != null) query.append("chainTypes", String(args.chainTypes)) if (args.minPriceUSD != null) query.append("minPriceUSD", String(args.minPriceUSD)) if (args['x-lifi-api-key'] != null) headers.set("x-lifi-api-key", String(args['x-lifi-api-key'])) const url = `${baseUrl.replace(/\/+$/, '')}/v1/tokens${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(getApiV1TokensResponse, await res.json()) };