import {z} from 'zod' export type OrderSide = 0 | 1; export type GetApiV1PositionArgs = {order?: ('asc' | 'desc') | undefined, limit?: number | undefined, cursor?: string | undefined, subaccountId: string, productIds?: Array | undefined, open?: boolean | undefined, orderBy?: ('size' | 'createdAt' | 'updatedAt' | 'realizedPnl') | undefined, createdAfter?: number | undefined, createdBefore?: number | undefined, side?: OrderSide | undefined, isLiquidated?: boolean | undefined}; export type GetApiV1PositionOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const orderSide = z.union([z.literal(0), z.literal(1)]); export const positionDto = z.object({cost: z.string(), createdAt: z.number().int(), feesAccruedUsd: z.string(), fundingAccruedUsd: z.string(), fundingUsd: z.string(), id: z.string(), isLiquidated: z.boolean(), liquidationPrice: z.string().optional(), productId: z.string(), realizedPnl: z.string(), side: orderSide, size: z.string(), totalDecreaseNotional: z.string(), totalDecreaseQuantity: z.string(), totalIncreaseNotional: z.string(), totalIncreaseQuantity: z.string(), unrealizedPnl: z.string().optional(), updatedAt: z.number().int(), wasDeleveraged: z.boolean()}); export const pageOfPositionDtos = z.object({data: z.array(positionDto), 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 positions for a given subaccount * * GET /v1/position */ export const getApiV1Position = async (args: GetApiV1PositionArgs, options?: GetApiV1PositionOptions) => { 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.subaccountId != null) query.append("subaccountId", String(args.subaccountId)) for (const item of args.productIds ?? []) query.append("productIds", String(item)) if (args.open != null) query.append("open", String(args.open)) if (args.orderBy != null) query.append("orderBy", String(args.orderBy)) if (args.createdAfter != null) query.append("createdAfter", String(args.createdAfter)) if (args.createdBefore != null) query.append("createdBefore", String(args.createdBefore)) if (args.side != null) query.append("side", String(args.side)) if (args.isLiquidated != null) query.append("isLiquidated", String(args.isLiquidated)) const url = `${baseUrl.replace(/\/+$/, '')}/v1/position${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(pageOfPositionDtos, await res.json()) };