import {z} from 'zod' export type GetApiV1PositionFillArgs = {order?: ('asc' | 'desc') | undefined, limit?: number | undefined, cursor?: string | undefined, positionId: string, orderBy?: ('price' | 'filled' | 'createdAt') | undefined}; export type GetApiV1PositionFillOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const orderSide = z.union([z.literal(0), z.literal(1)]); export const positionFillDto = z.object({createdAt: z.number().int(), feeUsd: z.string(), filled: z.string(), price: z.string(), realizedPnl: z.string(), reduceOnly: z.boolean(), side: orderSide, type: z.enum(["MARKET", "LIMIT", "REALIZED_PNL", "LIQUIDATION", "REALIZED_FUNDING", "DELEVERAGE", "SETTLEMENT"])}); export const pageOfPositionFillDtos = z.object({data: z.array(positionFillDto), hasNext: z.boolean(), nextCursor: 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 }; /** * Returns a filtered list of fills for a given position * * GET /v1/position/fill */ export const getApiV1PositionFill = async (args: GetApiV1PositionFillArgs, options?: GetApiV1PositionFillOptions) => { const {baseUrl = "https://api.ethereal.trade", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.order != null) query.append("order", String(args.order)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.positionId != null) query.append("positionId", String(args.positionId)) if (args.orderBy != null) query.append("orderBy", String(args.orderBy)) const url = `${baseUrl.replace(/\/+$/, '')}/v1/position/fill${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(pageOfPositionFillDtos, await res.json()) };