import {z} from 'zod' export type GetApiV1TradesArgs = {page_size?: number | undefined, cursor?: string | undefined, order_by?: string | undefined, direction?: string | undefined, min_timestamp?: string | undefined, max_timestamp?: string | undefined}; export type GetApiV1TradesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const trade = z.object({transaction_id: z.number(), status: z.string().min(1), a: z.object({order_id: z.number(), token_type: z.string().min(1), sold: z.string().min(1)}), b: z.object({order_id: z.number(), token_type: z.string().min(1), token_id: z.string().min(1), token_address: z.string().min(1), sold: z.string().min(1)}), timestamp: z.string().min(1)}); export const tradeList = z.object({cursor: z.string().optional(), remaining: z.number().int().optional(), result: z.array(trade).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 a list of trades * * GET /v1/trades */ export const getApiV1Trades = async (args: GetApiV1TradesArgs, options?: GetApiV1TradesOptions) => { const {baseUrl = "https://api.x.immutable.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page_size != null) query.append("page_size", String(args.page_size)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.order_by != null) query.append("order_by", String(args.order_by)) if (args.direction != null) query.append("direction", String(args.direction)) if (args.min_timestamp != null) query.append("min_timestamp", String(args.min_timestamp)) if (args.max_timestamp != null) query.append("max_timestamp", String(args.max_timestamp)) const url = `${baseUrl.replace(/\/+$/, '')}/v1/trades${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(tradeList, await res.json()) };