import {z} from 'zod' export type OrderEventCombination = {isTwap?: boolean | undefined, isDepositOrWithdraw?: boolean | undefined, orderType?: number | undefined, eventName?: string | undefined}; export type TradeDirection = 'long' | 'short' | 'swap' | 'any'; export type MarketDirectionFilter = {collateralAddress?: string | undefined, direction: TradeDirection, marketAddress: string}; export type TradesSearchRequest = {cursor?: string | undefined, limit?: number | undefined, showDebugValues?: boolean | undefined, orderEventCombinations?: Array | undefined, marketsDirections?: Array | undefined, toTimestamp?: number | undefined, fromTimestamp?: number | undefined, forAllAccounts?: boolean | undefined, address?: string | undefined}; export type CreateApiTradesSearchArgs = {body: TradesSearchRequest}; export type CreateApiTradesSearchOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const tradeResponse = z.object({reasonBytes: z.string().optional(), reason: z.string().optional(), numberOfParts: z.number().optional(), twapGroupId: z.string().optional(), srcChainId: z.number().optional(), decreasePositionSwapType: z.string().optional(), proportionalPendingImpactUsd: z.string().optional(), collateralTotalCostAmount: z.string().optional(), swapImpactUsd: z.string().optional(), executionAmountOut: z.string().optional(), totalImpactUsd: z.string().optional(), liquidationFeeAmount: z.string().optional(), swapFeeUsd: z.string().optional(), fundingFeeAmount: z.string().optional(), borrowingFeeAmount: z.string().optional(), traderDiscountAmount: z.string().optional(), positionFeeAmount: z.string().optional(), priceImpactDiffUsd: z.string().optional(), priceImpactUsd: z.string().optional(), basePnlUsd: z.string().optional(), pnlUsd: z.string().optional(), minOutputAmount: z.string().optional(), collateralTokenPriceMax: z.string().optional(), collateralTokenPriceMin: z.string().optional(), indexTokenPriceMax: z.string().optional(), indexTokenPriceMin: z.string().optional(), executionPrice: z.string().optional(), triggerPrice: z.string().optional(), acceptablePrice: z.string().optional(), sizeDeltaInTokens: z.string().optional(), sizeDeltaUsd: z.string().optional(), isLong: z.boolean().optional(), marketAddress: z.string().optional(), shouldUnwrapNativeToken: z.boolean().optional(), initialCollateralDeltaAmount: z.string(), initialCollateralTokenAddress: z.string(), swapPath: z.array(z.string()), transactionHash: z.string(), timestamp: z.number(), orderKey: z.string(), orderType: z.number(), account: z.string(), eventName: z.string(), id: z.string()}); export const tradesListResponse = z.object({hasMore: z.boolean(), nextCursor: z.string().nullable(), trades: z.array(tradeResponse)}); 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 }; /** * Trade history search supporting the same filters used by the GMX UI: * * POST /trades/search */ export const createApiTradesSearch = async (args: CreateApiTradesSearchArgs, options?: CreateApiTradesSearchOptions) => { const {baseUrl = "https://arbitrum.gmxapi.io/v1", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/trades/search${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(tradesListResponse, await res.json()) };