import {z} from 'zod' export type GetApiPositionsKeyArgs = {key: string, includeRelatedOrders?: boolean | undefined}; export type GetApiPositionsKeyOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const orderResponse = z.object({requestId: z.string().nullable(), dataList: z.array(z.string()), autoCancel: z.boolean(), isFrozen: z.boolean(), shouldUnwrapNativeToken: z.boolean(), isLong: z.boolean(), srcChainId: z.string(), validFromTime: z.string(), updatedAtTime: z.string(), uiFeeFactor: z.string().nullable(), minOutputAmount: z.string(), callbackGasLimit: z.string(), executionFee: z.string(), acceptablePrice: z.string(), triggerPrice: z.string(), initialCollateralDeltaAmount: z.string(), sizeDeltaUsd: z.string(), decreasePositionSwapType: z.number(), orderType: z.number(), swapPath: z.array(z.string()), initialCollateralTokenAddress: z.string(), marketAddress: z.string(), uiFeeReceiver: z.string(), callbackContract: z.string(), cancellationReceiver: z.string(), receiver: z.string(), account: z.string(), key: z.string()}); export const positionResponse = z.object({relatedOrders: z.array(orderResponse).optional(), pendingClaimableFundingFeesUsd: z.string(), pendingFundingFeesUsd: z.string(), uiFeeUsd: z.string(), closingFeeUsd: z.string(), netValue: z.string(), leverageWithoutPnl: z.string().optional(), leverageWithPnl: z.string().optional(), leverage: z.string().optional(), closePriceImpactDeltaUsd: z.string(), pendingImpactUsd: z.string(), priceImpactDiffUsd: z.string(), netPriceImapctDeltaUsd: z.string(), pnlAfterAllFeesPercentage: z.string(), pnlAfterAllFees: z.string(), netValueAfterAllFees: z.string(), pnlAfterFeesPercentage: z.string(), pnlAfterFees: z.string(), pnlPercentage: z.string(), hasLowCollateral: z.boolean(), remainingCollateralAmount: z.string(), remainingCollateralUsd: z.string(), collateralUsd: z.string(), liquidationPrice: z.string().optional(), entryPrice: z.string().optional(), markPrice: z.string(), poolName: z.string(), indexName: z.string(), data: z.string(), pendingImpactAmount: z.string(), positionValueInUsd: z.string(), uiFeeAmount: z.string(), traderDiscountAmount: z.string(), positionFeeAmount: z.string(), pnl: z.string(), isOpening: z.boolean().optional(), claimableShortTokenAmount: z.string(), claimableLongTokenAmount: z.string(), fundingFeeAmount: z.string(), isLong: z.boolean(), decreasedAtTime: z.string(), increasedAtTime: z.string(), pendingBorrowingFeesUsd: z.string(), collateralAmount: z.string(), sizeInTokens: z.string(), sizeInUsd: z.string(), collateralTokenAddress: z.string(), marketAddress: z.string(), account: z.string(), contractKey: z.string(), key: z.string()}); 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 /positions/{key} */ export const getApiPositionsKey = async (args: GetApiPositionsKeyArgs, options?: GetApiPositionsKeyOptions) => { const {baseUrl = "https://arbitrum.gmxapi.io/v1", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.includeRelatedOrders != null) query.append("includeRelatedOrders", String(args.includeRelatedOrders)) const url = `${baseUrl.replace(/\/+$/, '')}/positions/${encodeURIComponent(String(args.key))}${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(positionResponse, await res.json()) };