import {z} from 'zod' export type Order = {salt: string | number, maker: string, signer: string, taker?: string | undefined, tokenId: string, makerAmount: number, takerAmount: number, expiration?: string | undefined, nonce?: number | undefined, price?: number | undefined, feeRateBps: number, side: number, signature: string, signatureType: number}; export type CreateOrderDto = {order: Order, ownerId: number, orderType: 'FAK' | 'FOK' | 'GTC', marketSlug: string, postOnly?: boolean | undefined, clientOrderId?: string | undefined, onBehalfOf?: number | undefined, timestamp?: number | undefined, recvWindow?: number | undefined, stpPolicy?: ('cancel_both' | 'cancel_maker' | 'cancel_taker') | undefined}; export type CreateApiOrdersArgs = {body: CreateOrderDto}; export type CreateApiOrdersOptions = {baseUrl?: string | undefined, HmacAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const createdOrderDto = z.object({id: z.string(), salt: z.string(), maker: z.string(), signer: z.string(), taker: z.string().nullable().optional(), tokenId: z.string(), makerAmount: z.string(), takerAmount: z.string(), expiration: z.string().nullable().optional(), signatureType: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)]), nonce: z.string().nullable().optional(), feeRateBps: z.number().int().nullable().optional(), signature: z.string(), orderType: z.enum(["GTC", "FAK", "FOK"]), price: z.string().nullable().optional(), side: z.union([z.literal(0), z.literal(1)]), marketId: z.string(), ownerId: z.number().int(), createdAt: z.string(), updatedAt: z.string().optional(), market: z.object({id: z.number().int().optional(), slug: z.string().optional(), title: z.string().optional(), status: z.enum(["FUNDED", "RESOLVED", "LOCKED", "DRAFT", "FUNDED_FLAGGED"]).optional(), yesPositionId: z.string().nullable().optional(), noPositionId: z.string().nullable().optional(), group: z.object({id: z.number().int().optional(), slug: z.string().optional(), title: z.string().optional()}).nullable().optional()}), owner: z.object({id: z.number().int().optional(), account: z.string().optional(), displayName: z.string().nullable().optional(), username: z.string().nullable().optional(), imageURI: z.string().nullable().optional()}).nullable().optional()}); export const makerMatch = z.object({}); export const orderExecutionTotalsRawDto = z.object({contractsGross: z.string(), contractsFee: z.string(), contractsNet: z.string(), usdGross: z.string(), usdFee: z.string(), usdNet: z.string()}); export const orderExecutionDto = z.object({matched: z.boolean(), settlementStatus: z.enum(["UNMATCHED", "MATCHED", "MINED", "CONFIRMED", "RETRYING", "FAILED", "DELAYED", "CANCELED"]), reason: z.literal("STP_TAKER_REJECTED").nullable().optional(), eligibleAt: z.string().nullable().optional(), tradeEventId: z.string().optional(), txHash: z.string().nullable().optional(), clientOrderId: z.string().optional(), stpMakerCancels: z.array(z.string()).optional(), feeRateBps: z.number(), effectiveFeeBps: z.number(), totalsRaw: orderExecutionTotalsRawDto}); export const orderResponseDto = z.object({order: createdOrderDto, makerMatches: z.array(makerMatch).optional(), execution: orderExecutionDto}); 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 }; /** * Create Order * * POST /orders */ export const createApiOrders = async (args: CreateApiOrdersArgs, options?: CreateApiOrdersOptions) => { const {baseUrl = "https://api.limitless.exchange", fetch: fetchFn = fetch, HmacAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (HmacAuth !== undefined) headers.set("lmts-api-key", HmacAuth) const url = `${baseUrl.replace(/\/+$/, '')}/orders${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(orderResponseDto, await res.json()) };