import {z} from 'zod' export type GetApiPairArgs = {baseToken: string, quoteToken: string}; export type GetApiPairOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const pair = z.object({id: z.string().optional(), baseTokenSymbol: z.string().optional(), baseTokenAddress: z.string().optional(), baseTokenDecimals: z.number().int().optional(), quoteTokenSymbol: z.string().optional(), quoteTokenAddress: z.string().optional(), quoteTokenDecimals: z.number().int().optional(), listed: z.boolean().optional(), active: z.boolean().optional(), rank: z.number().int().optional(), makeFee: z.string().optional(), takeFee: z.string().optional(), createdAt: z.string().optional(), updatedAt: z.string().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 }; /** * Retrieve the pair information corresponding to a baseToken and a quoteToken * * GET /pair */ export const getApiPair = async (args: GetApiPairArgs, options?: GetApiPairOptions) => { const {baseUrl = "https://dex.tomochain.com/api", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.baseToken != null) query.append("baseToken", String(args.baseToken)) if (args.quoteToken != null) query.append("quoteToken", String(args.quoteToken)) const url = `${baseUrl.replace(/\/+$/, '')}/pair${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(pair, await res.json()) };