import {z} from 'zod' export type GetApiV1DexPoolsArgs = {assets?: Array | undefined}; export type GetApiV1DexPoolsOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const apiAmmType = z.enum(["constant_product", "cubic_stable", "curve_fi_stable", "concentrated_v3", "tonstakers", "weighted_constant_product", "weighted_stable", "bidask", "moon_dlmm", "bidask_damm", "dedust_v2"]); export const apiJson = z.record(z.string(), z.unknown()); export const apiPoolReserves = z.array(z.number()); export const apiCoffeeDexTrimmedPool = z.object({address: z.string(), amm_type: apiAmmType, amm_settings: apiJson.optional(), tokens: z.array(z.string()), reserves: apiPoolReserves, unavailable_until: z.number().int().optional()}); export const getApiV1DexPoolsResponse = z.array(apiCoffeeDexTrimmedPool); 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 dex pools by filter * * GET /v1/dex/pools */ export const getApiV1DexPools = async (args: GetApiV1DexPoolsArgs, options?: GetApiV1DexPoolsOptions) => { const {baseUrl = "https://backend.swap.coffee", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") for (const item of args.assets ?? []) query.append("assets", String(item)) if (ApiKey !== undefined) headers.set("X-Api-Key", ApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/dex/pools${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(getApiV1DexPoolsResponse, await res.json()) };