import {z} from 'zod' export type GetApiV1ExchangeSnapshotOptions = {baseUrl?: string | undefined, PhoenixBearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const authoritySetView = z.object({adlAuthority: z.string(), backstopAuthority: z.string(), cancelAuthority: z.string(), marketAuthority: z.string(), oracleAuthority: z.string(), riskAuthority: z.string(), rootAuthority: z.string()}); export const exchangeStateSnapshot = z.object({active: z.boolean(), activeTraderBuffer: z.array(z.string()), canonicalMint: z.string(), currentAuthorities: authoritySetView, exchangeStatusBits: z.number().int().gte(0), exchangeStatusFeatures: z.array(z.string()), gated: z.boolean(), globalConfig: z.string(), globalTraderIndex: z.array(z.string()), globalVault: z.string(), perpAssetMap: z.string(), programId: z.string(), usdcMint: z.string(), withdrawQueue: z.string(), withdrawalsAvailable: z.boolean().optional()}); export const exchangeWsMarketPriceBand = z.object({lower: z.string(), upper: z.string()}); export const commodityMarketState = z.enum(["active", "afterHours", "reopen"]); export const exchangeWsCommodityMetadata = z.object({afterHoursRadius: z.string(), executionPriceBand: exchangeWsMarketPriceBand.nullable().optional(), isAfterHours: z.boolean(), isCommodity: z.boolean(), isReopen: z.boolean(), lastIndexExpiryTimestamp: z.number().int().gte(0).nullable().optional(), lastKnownIndexPrice: z.string().nullable().optional(), markPriceBand: exchangeWsMarketPriceBand.nullable().optional(), status: commodityMarketState}); export const exchangeWsFundingConfig = z.object({fundingIntervalSeconds: z.number().int().gte(0), fundingPeriodSeconds: z.number().int().gte(0), maxFundingRatePerInterval: z.number().int()}); export const jsSafeU64 = z.number().int().gte(0); export const exchangeWsLeverageTier = z.object({limitOrderRiskFactor: z.number().int().gte(0), maxLeverage: z.number().int().gte(0), maxSizeBaseLots: jsSafeU64}); export const exchangeWsValidationRule = z.enum(["ignore", "require", "forbid"]); export const exchangeWsMarkPriceParameters = z.object({adjustedExchangeSpotPriceWeight: jsSafeU64, bookHardStaleMultiplier: z.number().int().gte(0).optional(), bookPriceRadius: jsSafeU64, bookPriceStaleThreshold: jsSafeU64, bookPriceWeight: jsSafeU64, commoditiesAfterHoursRadius: jsSafeU64, commoditiesAfterHoursRadiusBps: jsSafeU64, emaDiffRadius: jsSafeU64, emaPeriodSlots: jsSafeU64, exchangePerpPriceWeight: jsSafeU64, minOracleResponses: z.number().int().gte(0), oracleDivergenceRadius: z.number().int().gte(0), oracleHardStaleMultiplier: z.number().int().gte(0).optional(), perpPriceStaleThreshold: jsSafeU64, riskActionPriceValidityRules: z.array(z.array(z.array(exchangeWsValidationRule))), spotPriceStaleThreshold: jsSafeU64}); export const marketStatus = z.enum(["uninitialized", "active", "postOnly", "paused", "closed", "tombstoned"]); export const marketCalendar = z.object({calendarUri: z.string(), contentSha256: z.string(), description: z.string(), id: z.string(), nextMarketTransitionUtc: z.string().nullable().optional()}); export const marketPublicMetadata = z.object({calendar: marketCalendar.nullable().optional(), coinGeckoId: z.string().nullable().optional(), coinMarketCapId: z.number().int().nullable().optional(), description: z.string().nullable().optional(), displayColor: z.string().nullable().optional(), logoUri: z.string().nullable().optional(), name: z.string().nullable().optional(), tokensXyzAssetId: z.string().nullable().optional()}); export const exchangeWsRiskFactors = z.object({backstop: z.number(), backstopBps: z.number().int().gte(0).nullable().optional(), cancelOrder: z.number(), cancelOrderBps: z.number().int().gte(0).nullable().optional(), highRisk: z.number(), highRiskBps: z.number().int().gte(0).nullable().optional(), maintenance: z.number(), maintenanceBps: z.number().int().gte(0).nullable().optional(), upnl: z.number(), upnlBps: z.number().int().gte(0).nullable().optional(), upnlForWithdrawals: z.number(), upnlForWithdrawalsBps: z.number().int().gte(0).nullable().optional()}); export const exchangeMarketSnapshot = z.object({assetId: z.number().int().gte(0), baseLotsDecimals: z.number().int(), commodityMetadata: exchangeWsCommodityMetadata.nullable().optional(), fundingConfig: exchangeWsFundingConfig, isolatedOnly: z.boolean(), leverageTiers: z.array(exchangeWsLeverageTier), makerFee: z.number(), markPriceParameters: exchangeWsMarkPriceParameters, marketPubkey: z.string(), marketStatus: marketStatus, maxLiquidationSizeBaseLots: jsSafeU64, metadata: marketPublicMetadata.nullable().optional(), openInterestCapBaseLots: jsSafeU64, riskFactors: exchangeWsRiskFactors, splinePubkey: z.string(), symbol: z.string(), takerFee: z.number(), tickSize: z.number().int().gte(0)}); export const exchangeSnapshotView = z.object({exchange: exchangeStateSnapshot, markets: z.array(exchangeMarketSnapshot), sequenceNumber: jsSafeU64.nullable().optional(), slot: z.number().int().gte(0), slotIndex: z.number().int().gte(0), version: z.number().int().gte(0)}); 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 exchange snapshot * * GET /v1/exchange/snapshot */ export const getApiV1ExchangeSnapshot = async (options?: GetApiV1ExchangeSnapshotOptions) => { const {baseUrl = "https://perp-api.phoenix.trade", fetch: fetchFn = fetch, PhoenixBearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (PhoenixBearerAuth !== undefined) headers.set('authorization', `Bearer ${PhoenixBearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/exchange/snapshot${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(exchangeSnapshotView, await res.json()) };