@dimes-dot-fi/sdk 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/contract/index.d.cts +2 -2
- package/dist/contract/index.d.ts +2 -2
- package/dist/{dimes-client-DYFvnZUx.d.ts → dimes-client-DLbPP30g.d.ts} +7 -0
- package/dist/{dimes-client-DZPhU1CG.d.cts → dimes-client-ntybPwHK.d.cts} +7 -0
- package/dist/{dimes-error-BlQWPqhQ.d.cts → dimes-error-BhKtCgba.d.cts} +1 -1
- package/dist/{dimes-error-DBKV5bfr.d.ts → dimes-error-DjxvjzCZ.d.ts} +1 -1
- package/dist/index.cjs +6 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.mjs +6 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{quote-CanwfT9m.d.cts → quote-Bc9H5-2H.d.cts} +1 -1
- package/dist/{quote-BFNgVsY-.d.ts → quote-BoTWtznc.d.ts} +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +6 -2
- package/dist/react/index.d.ts +6 -2
- package/dist/react/index.mjs +1 -1
- package/dist/react/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/react/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/react/provider.tsx","../../src/react/use-quote.ts","../../src/react/use-quote-machine.ts","../../src/react/use-markets.ts","../../src/react/use-positions.ts","../../src/react/ws-reconcile.ts","../../src/react/use-contract-info.ts","../../src/react/use-limits.ts","../../src/react/use-cancel-position.ts","../../src/react/use-position-stream.ts","../../src/react/use-market-stream.ts"],"sourcesContent":["import { createContext, useContext, type ReactNode } from \"react\";\nimport type { DimesClient } from \"../client/dimes-client\";\nimport { DimesError } from \"../errors/dimes-error\";\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst DimesContext = createContext<DimesClient | null>(null);\n\nexport interface DimesProviderProps {\n client: DimesClient;\n children: ReactNode;\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/explicit-function-return-type\nexport function DimesProvider({ client, children }: DimesProviderProps) {\n return <DimesContext.Provider value={client}>{children}</DimesContext.Provider>;\n}\n\nexport function useDimesClient(): DimesClient {\n const client = useContext(DimesContext);\n if (!client) {\n throw new DimesError(\"missing_provider\", \"useDimesClient must be used within a <DimesProvider>\");\n }\n return client;\n}\n","import { useCallback, useReducer } from \"react\";\nimport { executeQuote } from \"../quote/quote\";\nimport type { HintAdjustment } from \"../quote/quote-error-hints\";\nimport type { Quote } from \"../types\";\nimport type { QuoteOptions, QuoteParams, QuoteResult } from \"../types/quote\";\nimport { useDimesClient } from \"./provider\";\n\nexport type QuotePhase = \"idle\" | \"loading-draft\" | \"draft-ready\" | \"promoting\" | \"promoted\" | \"market-moved\" | \"error\";\n\nexport interface QuoteState {\n phase: QuotePhase;\n draft?: Quote;\n quote?: Quote;\n /** @deprecated Renamed to {@link QuoteState.quote}. Still populated for backward compatibility. */\n // eslint-disable-next-line no-restricted-syntax -- intentional deprecated alias field\n offer?: Quote;\n corrections: HintAdjustment[];\n retries: number;\n error?: unknown;\n}\n\ntype Action =\n | { type: \"loading\" }\n | { type: \"draftReady\"; draft: Quote }\n | { type: \"promoting\" }\n | { type: \"marketMoved\" }\n | { type: \"done\"; result: QuoteResult }\n | { type: \"error\"; error: unknown }\n | { type: \"reset\" };\n\nfunction reducer(state: QuoteState, action: Action): QuoteState {\n switch (action.type) {\n case \"loading\":\n return { phase: \"loading-draft\", corrections: [], retries: 0 };\n case \"draftReady\":\n return { ...state, phase: \"draft-ready\", draft: action.draft };\n case \"promoting\":\n return { ...state, phase: \"promoting\" };\n case \"marketMoved\":\n return { ...state, phase: \"market-moved\" };\n case \"done\":\n return {\n phase: \"promoted\",\n quote: action.result.quote,\n offer: action.result.quote,\n corrections: action.result.corrections,\n retries: action.result.retries,\n draft: state.draft,\n };\n case \"error\":\n return { ...state, phase: \"error\", error: action.error };\n case \"reset\":\n return { phase: \"idle\", corrections: [], retries: 0 };\n default:\n return state;\n }\n}\n\nexport interface UseQuoteReturn {\n state: QuoteState;\n execute: (params: QuoteParams, options?: QuoteOptions) => Promise<QuoteResult>;\n reset: () => void;\n}\n\nexport function useQuote(): UseQuoteReturn {\n const client = useDimesClient();\n const [state, dispatch] = useReducer(reducer, {\n phase: \"idle\",\n corrections: [],\n retries: 0,\n });\n\n const execute = useCallback(\n async (params: QuoteParams, options?: QuoteOptions): Promise<QuoteResult> => {\n dispatch({ type: \"loading\" });\n\n try {\n const result = await executeQuote(client, params, {\n ...options,\n onDraftReady: (draft) => {\n dispatch({ type: \"draftReady\", draft });\n dispatch({ type: \"promoting\" });\n options?.onDraftReady?.(draft);\n },\n onMarketMoved: (event) => {\n dispatch({ type: \"marketMoved\" });\n return options?.onMarketMoved?.(event);\n },\n onCorrection: (adj) => {\n return options?.onCorrection?.(adj);\n },\n });\n\n dispatch({ type: \"done\", result });\n return result;\n } catch (err) {\n dispatch({ type: \"error\", error: err });\n throw err;\n }\n },\n [client],\n );\n\n const reset = useCallback(() => {\n dispatch({ type: \"reset\" });\n }, []);\n\n return { state, execute, reset };\n}\n","import { useCallback, useReducer, useRef } from \"react\";\nimport { buildQuoteParams } from \"../quote/build-quote-params\";\nimport { isMarketMovedError } from \"../quote/quote\";\nimport type { CreateQuoteParams, Quote } from \"../types\";\nimport type { QuoteParams } from \"../types/quote\";\nimport { useDimesClient } from \"./provider\";\n\nconst DEFAULT_MAX_RETRIES = 3;\n\n/**\n * Interactive, user-in-the-loop quote flow: draft → review → promote, pausing\n * across renders so the UI can show each step. This is the granular companion\n * to `useQuote`/`executeQuote` (which run draft→promote in one call). The steps\n * map directly onto the SDK client (`createDraftQuote`/`promoteDraftQuote`/\n * `createQuote`); on a market-moved promote failure it re-drafts and surfaces a\n * `market-moved` state so the user can review and accept the new draft.\n */\nexport type QuoteMachineState =\n | { phase: \"idle\" }\n | { phase: \"loading-draft\" }\n | { phase: \"draft-ready\"; draft: Quote; quotedAt: number }\n | { phase: \"promoting\"; draft: Quote; quotedAt: number }\n | { phase: \"promoted\"; draft: Quote; promotedQuote: Quote; correctedFrom?: Quote; quotedAt: number }\n | { phase: \"market-moved\"; originalDraft: Quote; newDraft: Quote; retryCount: number; quotedAt: number }\n | { phase: \"error\"; error: unknown; draft?: Quote };\n\ntype Action =\n | { type: \"loading\" }\n | { type: \"draftReady\"; draft: Quote; quotedAt: number }\n | { type: \"promoting\"; draft: Quote; quotedAt: number }\n | { type: \"promoted\"; draft: Quote; promotedQuote: Quote; correctedFrom?: Quote; quotedAt: number }\n | { type: \"marketMoved\"; originalDraft: Quote; newDraft: Quote; retryCount: number; quotedAt: number }\n | { type: \"error\"; error: unknown; draft?: Quote }\n | { type: \"reset\" };\n\nfunction reducer(_state: QuoteMachineState, action: Action): QuoteMachineState {\n switch (action.type) {\n case \"loading\":\n return { phase: \"loading-draft\" };\n case \"draftReady\":\n return { phase: \"draft-ready\", draft: action.draft, quotedAt: action.quotedAt };\n case \"promoting\":\n return { phase: \"promoting\", draft: action.draft, quotedAt: action.quotedAt };\n case \"promoted\":\n return {\n phase: \"promoted\",\n draft: action.draft,\n promotedQuote: action.promotedQuote,\n correctedFrom: action.correctedFrom,\n quotedAt: action.quotedAt,\n };\n case \"marketMoved\":\n return {\n phase: \"market-moved\",\n originalDraft: action.originalDraft,\n newDraft: action.newDraft,\n retryCount: action.retryCount,\n quotedAt: action.quotedAt,\n };\n case \"error\":\n return { phase: \"error\", error: action.error, draft: action.draft };\n case \"reset\":\n return { phase: \"idle\" };\n default:\n return _state;\n }\n}\n\nexport interface UseQuoteMachineOptions {\n /** Maximum number of re-draft attempts on a market-moved promote failure. Default 3. */\n maxRetries?: number;\n}\n\nexport interface UseQuoteMachineReturn {\n state: QuoteMachineState;\n /** Build params from a `QuoteParams` and fetch a draft quote. Moves to `draft-ready`. */\n getDraft: (params: QuoteParams) => Promise<void>;\n /** Promote a reviewed draft into a signed quote. On market-moved, re-drafts and surfaces `market-moved`. */\n promote: (draft: Quote, retryCount?: number) => Promise<void>;\n /** Accept a re-drafted quote after a `market-moved` and promote it. */\n acceptChanges: (newDraft: Quote, retryCount: number) => Promise<void>;\n /** Promote pre-adjusted params directly via `createQuote` (e.g. after applying a correction hint). */\n correctAndPromote: (originalDraft: Quote, adjustedParams: CreateQuoteParams) => Promise<void>;\n reset: () => void;\n}\n\nexport function useQuoteMachine(options?: UseQuoteMachineOptions): UseQuoteMachineReturn {\n const client = useDimesClient();\n const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n const [state, dispatch] = useReducer(reducer, { phase: \"idle\" } as QuoteMachineState);\n const lastParamsRef = useRef<CreateQuoteParams | null>(null);\n const quotedAtRef = useRef(0);\n\n const getDraft = useCallback(\n async (params: QuoteParams): Promise<void> => {\n dispatch({ type: \"loading\" });\n const quoteParams = buildQuoteParams(params);\n lastParamsRef.current = quoteParams;\n try {\n const draft = await client.createDraftQuote(quoteParams);\n\n quotedAtRef.current = Date.now();\n dispatch({ type: \"draftReady\", draft, quotedAt: quotedAtRef.current });\n } catch (err) {\n dispatch({ type: \"error\", error: err });\n }\n },\n [client],\n );\n\n const promote = useCallback(\n async (draft: Quote, retryCount = 0): Promise<void> => {\n const quotedAt = quotedAtRef.current;\n dispatch({ type: \"promoting\", draft, quotedAt });\n try {\n const promotedQuote = await client.promoteDraftQuote(draft.id);\n dispatch({ type: \"promoted\", draft, promotedQuote, quotedAt });\n } catch (err) {\n if (isMarketMovedError(err) && retryCount < maxRetries && lastParamsRef.current) {\n try {\n const newDraft = await client.createDraftQuote(lastParamsRef.current);\n // eslint-disable-next-line require-atomic-updates -- timestamp ref, no contended state\n quotedAtRef.current = Date.now();\n dispatch({\n type: \"marketMoved\",\n originalDraft: draft,\n newDraft,\n retryCount: retryCount + 1,\n quotedAt: quotedAtRef.current,\n });\n } catch (draftErr) {\n dispatch({ type: \"error\", error: draftErr, draft });\n }\n } else {\n dispatch({ type: \"error\", error: err, draft });\n }\n }\n },\n [client, maxRetries],\n );\n\n const acceptChanges = useCallback(\n async (newDraft: Quote, retryCount: number): Promise<void> => {\n await promote(newDraft, retryCount);\n },\n [promote],\n );\n\n const correctAndPromote = useCallback(\n async (originalDraft: Quote, adjustedParams: CreateQuoteParams): Promise<void> => {\n dispatch({ type: \"promoting\", draft: originalDraft, quotedAt: quotedAtRef.current });\n lastParamsRef.current = adjustedParams;\n try {\n const promotedQuote = await client.createQuote(adjustedParams);\n // eslint-disable-next-line require-atomic-updates -- timestamp ref, no contended state\n quotedAtRef.current = Date.now();\n dispatch({\n type: \"promoted\",\n draft: promotedQuote,\n promotedQuote,\n correctedFrom: originalDraft,\n quotedAt: quotedAtRef.current,\n });\n } catch (err) {\n dispatch({ type: \"error\", error: err });\n }\n },\n [client],\n );\n\n const reset = useCallback((): void => {\n dispatch({ type: \"reset\" });\n lastParamsRef.current = null;\n quotedAtRef.current = 0;\n }, []);\n\n return { state, getDraft, promote, acceptChanges, correctAndPromote, reset };\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { GetMarketsParams, SearchMarketsParams } from \"../client/dimes-client\";\nimport type { Market, Paginated } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function useMarkets(\n params?: GetMarketsParams,\n queryOptions?: Partial<UseQueryOptions<Paginated<Market>>>,\n): UseQueryResult<Paginated<Market>> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"markets\", params],\n queryFn: () => client.getMarkets(params),\n ...queryOptions,\n });\n}\n\nexport function useSearchMarkets(\n params: SearchMarketsParams,\n queryOptions?: Partial<UseQueryOptions<Paginated<Market>>>,\n): UseQueryResult<Paginated<Market>> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"markets\", \"search\", params],\n queryFn: () => client.searchMarkets(params),\n enabled: !!params.query,\n ...queryOptions,\n });\n}\n\nexport function useMarket(ticker: string, queryOptions?: Partial<UseQueryOptions<Market>>): UseQueryResult<Market> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"market\", ticker],\n queryFn: () => client.getMarket(ticker),\n enabled: !!ticker,\n ...queryOptions,\n });\n}\n","import { useQuery, type Query, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { GetPositionsParams } from \"../client/dimes-client\";\nimport type { Position } from \"../types\";\nimport { useDimesClient } from \"./provider\";\nimport { defaultReconciliationWindowMs, reconcilePolledPositions, transientPositionStatuses } from \"./ws-reconcile\";\n\nconst DEFAULT_FAST_POLL_MS = 5_000;\nconst DEFAULT_SLOW_POLL_MS = 15_000;\n\nexport interface UsePositionsOptions {\n /**\n * Appended to the query key so changing scope (e.g. switching wallet) does not serve the previous\n * scope's cached positions until a refetch. Omit to keep the default, scope-less cache key.\n */\n scope?: string | null;\n /**\n * Poll faster while any position is in a transient state (pending/closing/settling/unwinding) and\n * slower otherwise. Pass `true` for the defaults (5s / 15s) or an object to tune them.\n */\n adaptivePolling?: boolean | { fastMs?: number; slowMs?: number };\n /**\n * Defer to fresher WebSocket data: when a position was updated over the socket within the\n * reconciliation window, a slower REST poll won't overwrite it. Use with `usePositionStream` in\n * reconcile mode. Pass `true` for the default window or a number of milliseconds.\n */\n reconcile?: boolean | number;\n}\n\nfunction adaptiveRefetchInterval(\n adaptive: NonNullable<UsePositionsOptions[\"adaptivePolling\"]>,\n): (query: Query<Position[]>) => number {\n const fastMs = typeof adaptive === \"object\" ? (adaptive.fastMs ?? DEFAULT_FAST_POLL_MS) : DEFAULT_FAST_POLL_MS;\n const slowMs = typeof adaptive === \"object\" ? (adaptive.slowMs ?? DEFAULT_SLOW_POLL_MS) : DEFAULT_SLOW_POLL_MS;\n return (query) => (query.state.data?.some((p) => transientPositionStatuses.has(p.status)) ? fastMs : slowMs);\n}\n\nfunction reconcileStructuralSharing(reconcile: number | true): (oldData: unknown, newData: unknown) => Position[] {\n const windowMs = typeof reconcile === \"number\" ? reconcile : defaultReconciliationWindowMs;\n return (oldData, newData) =>\n reconcilePolledPositions(oldData as Position[] | undefined, newData as Position[], windowMs, Date.now());\n}\n\nexport function usePositions(\n params?: GetPositionsParams,\n queryOptions?: Partial<UseQueryOptions<Position[]>>,\n options?: UsePositionsOptions,\n): UseQueryResult<Position[]> {\n const client = useDimesClient();\n\n const queryKey =\n options?.scope !== undefined ? [\"dimes\", \"positions\", params, options.scope] : [\"dimes\", \"positions\", params];\n\n const config: UseQueryOptions<Position[]> = {\n queryKey,\n queryFn: () => client.getPositions(params),\n };\n\n if (options?.adaptivePolling) {\n config.refetchInterval = adaptiveRefetchInterval(options.adaptivePolling);\n }\n\n if (options?.reconcile) {\n config.structuralSharing = reconcileStructuralSharing(options.reconcile);\n }\n\n return useQuery({ ...config, ...queryOptions });\n}\n","import type { QueryClient } from \"@tanstack/react-query\";\nimport type { Market, Paginated, Position } from \"../types\";\nimport type { MarketDelta, PositionEvent } from \"../ws\";\n\n/**\n * Shared plumbing for merging WebSocket events into the React Query cache. Used by the optional\n * reconcile mode of `usePositionStream` / `useMarketStream` and the `reconcile` option on\n * `usePositions`. Kept internal so the query keys and the WS-timestamp registry stay in sync.\n */\n\nexport const positionsQueryKey = [\"dimes\", \"positions\"] as const;\n\nexport const marketsQueryKey = [\"dimes\", \"markets\"] as const;\n\nexport const defaultReconciliationWindowMs = 12_000;\n\n/** Position statuses that indicate an in-flight transition — polled faster by `adaptivePolling`. */\nexport const transientPositionStatuses: ReadonlySet<string> = new Set([\"pending\", \"closing\", \"settling\", \"unwinding\"]);\n\n/**\n * Records the last time each position id was written from a WebSocket event. Polling reconciliation\n * uses this so a slower REST poll never clobbers fresher WS data inside the reconciliation window.\n */\nexport const wsPositionTimestamps = new Map<string, number>();\n\n/** Merge a single position event into every cached positions query. */\nexport function mergePositionEvent(queryClient: QueryClient, event: PositionEvent, now: number): void {\n const position = event.data;\n queryClient.setQueriesData<Position[]>({ queryKey: positionsQueryKey }, (old) => {\n if (!old) {\n return old;\n }\n const idx = old.findIndex((p) => p.id === position.id);\n if (idx >= 0) {\n const next = [...old];\n next[idx] = position;\n return next;\n }\n if (event.type === \"position.created\") {\n return [position, ...old];\n }\n return old;\n });\n wsPositionTimestamps.set(position.id, now);\n}\n\n/**\n * `structuralSharing` for a polled positions list: keep the cached (WS-fresher) copy of any position\n * updated over the socket within `windowMs`, otherwise accept the polled copy.\n */\nexport function reconcilePolledPositions(\n oldData: Position[] | undefined,\n newData: Position[],\n windowMs: number,\n now: number,\n): Position[] {\n if (!oldData) {\n return newData;\n }\n return newData.map((polled) => {\n const wsTime = wsPositionTimestamps.get(polled.id);\n if (wsTime !== undefined && now - wsTime < windowMs) {\n const fresher = oldData.find((p) => p.id === polled.id);\n return fresher ?? polled;\n }\n if (wsTime !== undefined) {\n wsPositionTimestamps.delete(polled.id);\n }\n return polled;\n });\n}\n\n/**\n * Deep-merge a market delta onto a cached market. The nested `leverage` block must be merged rather\n * than replaced — a max-leverage delta carries only the changed leverage fields, so a shallow spread\n * would drop the constant `minBps`/`stepBps` until the next full refetch.\n */\nfunction mergeMarket(prev: Market, delta: MarketDelta): Market {\n return {\n ...prev,\n ...delta,\n leverage: delta.leverage ? { ...prev.leverage, ...delta.leverage } : prev.leverage,\n };\n}\n\n/** Merge market deltas into every cached paginated markets query (no-op for ids not present). */\nexport function mergeMarketDeltas(queryClient: QueryClient, deltas: MarketDelta[]): void {\n queryClient.setQueriesData<Paginated<Market>>({ queryKey: marketsQueryKey }, (old) => {\n if (!old) {\n return old;\n }\n const data = old.data.map((market) => {\n const delta = deltas.find((d) => d.id === market.id);\n return delta ? mergeMarket(market, delta) : market;\n });\n const changed = data.some((market, i) => market !== old.data[i]);\n return changed ? { ...old, data } : old;\n });\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { ContractInfo } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function useContractInfo(queryOptions?: Partial<UseQueryOptions<ContractInfo>>): UseQueryResult<ContractInfo> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"contractInfo\"],\n queryFn: () => client.getContractInfo(),\n staleTime: Infinity,\n ...queryOptions,\n });\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { CustomerLimit } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\n/** User trading limits (JWT auth) — `GET /user-limits`. */\nexport function useUserLimits(queryOptions?: Partial<UseQueryOptions<CustomerLimit>>): UseQueryResult<CustomerLimit> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"user-limits\"],\n queryFn: () => client.getUserLimits(),\n ...queryOptions,\n });\n}\n\n/** Partner-wide limits (API-key auth) — `GET /partner-limits`. */\nexport function usePartnerLimits(\n queryOptions?: Partial<UseQueryOptions<CustomerLimit>>,\n): UseQueryResult<CustomerLimit> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"partner-limits\"],\n queryFn: () => client.getPartnerLimits(),\n ...queryOptions,\n });\n}\n\n/** @deprecated Use {@link useUserLimits}. Alias kept for back-compat; resolves to user limits. */\nexport function useLimits(queryOptions?: Partial<UseQueryOptions<CustomerLimit>>): UseQueryResult<CustomerLimit> {\n return useUserLimits(queryOptions);\n}\n","import { useMutation, type UseMutationOptions, type UseMutationResult } from \"@tanstack/react-query\";\nimport { DimesApiError } from \"../errors/dimes-error\";\nimport { useDimesClient } from \"./provider\";\n\nconst HTTP_CONFLICT = 409;\n\nexport type CancelPositionResult = \"cancelled\" | \"already_cancelling\";\n\nexport interface UseCancelPositionOptions {\n /**\n * Treat a 409 Conflict (the position is already being cancelled) as success, resolving to\n * `\"already_cancelling\"` instead of throwing. Default false — a 409 rejects like any other error.\n */\n treatConflictAsAlreadyCancelling?: boolean;\n}\n\nexport function useCancelPosition(\n mutationOptions?: Partial<UseMutationOptions<CancelPositionResult, Error, string>>,\n options?: UseCancelPositionOptions,\n): UseMutationResult<CancelPositionResult, Error, string> {\n const client = useDimesClient();\n const treatConflictAsAlreadyCancelling = options?.treatConflictAsAlreadyCancelling ?? false;\n\n return useMutation({\n mutationFn: async (positionId: string): Promise<CancelPositionResult> => {\n try {\n await client.cancelPosition(positionId);\n return \"cancelled\";\n } catch (err) {\n if (treatConflictAsAlreadyCancelling && err instanceof DimesApiError && err.status === HTTP_CONFLICT) {\n return \"already_cancelling\";\n }\n throw err;\n }\n },\n ...mutationOptions,\n });\n}\n","import { useQueryClient } from \"@tanstack/react-query\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { PositionSocket, type NotificationEvent, type PositionEvent } from \"../ws\";\nimport { useDimesClient } from \"./provider\";\nimport { mergePositionEvent, positionsQueryKey } from \"./ws-reconcile\";\n\nexport type StreamMode = \"raw\" | \"reconcile\";\n\nexport interface UsePositionStreamOptions {\n /** Connect the socket. Default true. Set false to gate on auth being ready. */\n enabled?: boolean;\n /**\n * `\"reconcile\"` (default) merges every event into the `usePositions` query cache so the UI updates\n * instantly; `\"raw\"` does not touch the cache and only forwards events to your callbacks.\n */\n mode?: StreamMode;\n /** Disconnect while the tab is hidden and reconnect when it becomes visible again. Default true. */\n pauseOnHidden?: boolean;\n /** Invalidate the positions query on reconnect (skipping the first connect) to catch missed events. Default true. */\n invalidateOnReconnect?: boolean;\n /** Always called with the raw (camelCased) event, in both modes. */\n onEvent?: (event: PositionEvent) => void;\n /** Called with user-gateway notification events (toasts, fill progress…). Never touches the cache. */\n onNotification?: (event: NotificationEvent) => void;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: unknown) => void;\n}\n\nexport interface UsePositionStreamResult {\n socket: PositionSocket | null;\n connected: boolean;\n}\n\n/**\n * Subscribe to the user position WebSocket gateway. In `reconcile` mode (default) events are merged\n * into the React Query cache used by `usePositions`; in `raw` mode you handle events yourself via\n * `onEvent`. App-specific side effects (toasts, stores) belong in the callbacks, not the SDK.\n */\nexport function usePositionStream(options?: UsePositionStreamOptions): UsePositionStreamResult {\n const client = useDimesClient();\n const queryClient = useQueryClient();\n const socketRef = useRef<PositionSocket | null>(null);\n const [connected, setConnected] = useState(false);\n\n const enabled = options?.enabled ?? true;\n const mode = options?.mode ?? \"reconcile\";\n const pauseOnHidden = options?.pauseOnHidden ?? true;\n const invalidateOnReconnect = options?.invalidateOnReconnect ?? true;\n\n // Keep the latest callbacks/flags in a ref so the socket effect does not reconnect on every render.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n useEffect(() => {\n if (!enabled) {\n return undefined;\n }\n\n const socket = new PositionSocket({\n baseUrl: client.baseUrl,\n getToken: (): string | null => client.getToken(),\n });\n socketRef.current = socket;\n\n const unsubEvent = socket.on(\"*\", (event) => {\n if (mode === \"reconcile\") {\n mergePositionEvent(queryClient, event, Date.now());\n }\n optionsRef.current?.onEvent?.(event);\n });\n\n const unsubNotification = socket.onNotification((event) => {\n optionsRef.current?.onNotification?.(event);\n });\n\n let firstConnect = true;\n const unsubConnect = socket.onConnect(() => {\n setConnected(true);\n if (firstConnect) {\n firstConnect = false;\n } else if (mode === \"reconcile\" && invalidateOnReconnect) {\n void queryClient.invalidateQueries({ queryKey: positionsQueryKey });\n }\n optionsRef.current?.onConnect?.();\n });\n\n const unsubDisconnect = socket.onDisconnect(() => {\n setConnected(false);\n optionsRef.current?.onDisconnect?.();\n });\n\n const unsubError = socket.onError((error) => {\n optionsRef.current?.onError?.(error);\n });\n\n const handleVisibility =\n pauseOnHidden && typeof document !== \"undefined\"\n ? (): void => {\n if (document.hidden) {\n socket.disconnect();\n } else {\n socket.connect();\n }\n }\n : null;\n if (handleVisibility) {\n document.addEventListener(\"visibilitychange\", handleVisibility);\n }\n\n socket.connect();\n\n return (): void => {\n if (handleVisibility) {\n document.removeEventListener(\"visibilitychange\", handleVisibility);\n }\n unsubEvent();\n unsubNotification();\n unsubConnect();\n unsubDisconnect();\n unsubError();\n socket.disconnect();\n socketRef.current = null;\n setConnected(false);\n };\n }, [client, queryClient, enabled, mode, pauseOnHidden, invalidateOnReconnect]);\n\n return { socket: socketRef.current, connected };\n}\n","import { useQueryClient } from \"@tanstack/react-query\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { MarketSocket, type MarketDelta, type MarketEvent } from \"../ws\";\nimport { useDimesClient } from \"./provider\";\nimport type { StreamMode } from \"./use-position-stream\";\nimport { marketsQueryKey, mergeMarketDeltas } from \"./ws-reconcile\";\n\nexport interface UseMarketStreamOptions {\n /** Connect the socket. Default true. */\n enabled?: boolean;\n /**\n * `\"reconcile\"` (default) merges `eligibility_changed` / `max_leverage_changed` deltas into the\n * `useMarkets` query cache; `\"raw\"` only forwards events. `market.discovered` events are never\n * injected into the paginated cache (that would pollute server-filtered views) — handle them via\n * `onEvent` in either mode.\n */\n mode?: StreamMode;\n /** Disconnect while the tab is hidden and reconnect when visible again. Default true. */\n pauseOnHidden?: boolean;\n /** Invalidate the markets query on reconnect (skipping the first connect). Default true. */\n invalidateOnReconnect?: boolean;\n /** Always called with the raw (camelCased) event, in both modes. */\n onEvent?: (event: MarketEvent) => void;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: unknown) => void;\n}\n\nexport interface UseMarketStreamResult {\n socket: MarketSocket | null;\n connected: boolean;\n}\n\n/**\n * Subscribe to the user market WebSocket gateway. In `reconcile` mode (default) eligibility and\n * max-leverage deltas are deep-merged into the `useMarkets` cache; discovered markets are forwarded\n * to `onEvent` for the app to route (e.g. a \"new markets\" strip).\n */\nexport function useMarketStream(options?: UseMarketStreamOptions): UseMarketStreamResult {\n const client = useDimesClient();\n const queryClient = useQueryClient();\n const socketRef = useRef<MarketSocket | null>(null);\n const [connected, setConnected] = useState(false);\n\n const enabled = options?.enabled ?? true;\n const mode = options?.mode ?? \"reconcile\";\n const pauseOnHidden = options?.pauseOnHidden ?? true;\n const invalidateOnReconnect = options?.invalidateOnReconnect ?? true;\n\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n useEffect(() => {\n if (!enabled) {\n return undefined;\n }\n\n const socket = new MarketSocket({\n baseUrl: client.baseUrl,\n getToken: (): string | null => client.getToken(),\n });\n socketRef.current = socket;\n\n const unsubEvent = socket.on(\"*\", (event) => {\n if (mode === \"reconcile\" && event.type !== \"market.discovered\") {\n mergeMarketDeltas(queryClient, event.data as MarketDelta[]);\n }\n optionsRef.current?.onEvent?.(event);\n });\n\n let firstConnect = true;\n const unsubConnect = socket.onConnect(() => {\n setConnected(true);\n if (firstConnect) {\n firstConnect = false;\n } else if (mode === \"reconcile\" && invalidateOnReconnect) {\n void queryClient.invalidateQueries({ queryKey: marketsQueryKey });\n }\n optionsRef.current?.onConnect?.();\n });\n\n const unsubDisconnect = socket.onDisconnect(() => {\n setConnected(false);\n optionsRef.current?.onDisconnect?.();\n });\n\n const unsubError = socket.onError((error) => {\n optionsRef.current?.onError?.(error);\n });\n\n const handleVisibility =\n pauseOnHidden && typeof document !== \"undefined\"\n ? (): void => {\n if (document.hidden) {\n socket.disconnect();\n } else {\n socket.connect();\n }\n }\n : null;\n if (handleVisibility) {\n document.addEventListener(\"visibilitychange\", handleVisibility);\n }\n\n socket.connect();\n\n return (): void => {\n if (handleVisibility) {\n document.removeEventListener(\"visibilitychange\", handleVisibility);\n }\n unsubEvent();\n unsubConnect();\n unsubDisconnect();\n unsubError();\n socket.disconnect();\n socketRef.current = null;\n setConnected(false);\n };\n }, [client, queryClient, enabled, mode, pauseOnHidden, invalidateOnReconnect]);\n\n return { socket: socketRef.current, connected };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,eAAe,kBAAkC;AAcjD;AATT,IAAM,eAAe,cAAkC,IAAI;AAQpD,SAAS,cAAc,EAAE,QAAQ,SAAS,GAAuB;AACtE,SAAO,oBAAC,aAAa,UAAb,EAAsB,OAAO,QAAS,UAAS;AACzD;AAEO,SAAS,iBAA8B;AAC5C,QAAM,SAAS,WAAW,YAAY;AACtC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,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AgB,CAAC;AAAA,MAClE;AACA,iBAAW,SAAS,YAAY;AAAA,IAClC,CAAC;AAED,UAAM,kBAAkB,OAAO,aAAa,MAAM;AAChD,mBAAa,KAAK;AAClB,iBAAW,SAAS,eAAe;AAAA,IACrC,CAAC;AAED,UAAM,aAAa,OAAO,QAAQ,CAAC,UAAU;AAC3C,iBAAW,SAAS,UAAU,KAAK;AAAA,IACrC,CAAC;AAED,UAAM,mBACJ,iBAAiB,OAAO,aAAa,cACjC,MAAY;AACV,UAAI,SAAS,QAAQ;AACnB,eAAO,WAAW;AAAA,MACpB,OAAO;AACL,eAAO,QAAQ;AAAA,MACjB;AAAA,IACF,IACA;AACN,QAAI,kBAAkB;AACpB,eAAS,iBAAiB,oBAAoB,gBAAgB;AAAA,IAChE;AAEA,WAAO,QAAQ;AAEf,WAAO,MAAY;AACjB,UAAI,kBAAkB;AACpB,iBAAS,oBAAoB,oBAAoB,gBAAgB;AAAA,MACnE;AACA,iBAAW;AACX,mBAAa;AACb,sBAAgB;AAChB,iBAAW;AACX,aAAO,WAAW;AAClB,gBAAU,UAAU;AACpB,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF,GAAG,CAAC,QAAQ,aAAa,SAAS,MAAM,eAAe,qBAAqB,CAAC;AAE7E,SAAO,EAAE,QAAQ,UAAU,SAAS,UAAU;AAChD;","names":["useCallback","useReducer","reducer","useReducer","useCallback","useQuery","useQuery","useQuery","useQuery","useQuery","useQuery","useRef","useRef","useQueryClient","useEffect","useRef","useState","useQueryClient","useRef","useState","useEffect"]}
|
|
1
|
+
{"version":3,"sources":["../../src/react/provider.tsx","../../src/react/use-quote.ts","../../src/react/use-quote-machine.ts","../../src/react/use-markets.ts","../../src/react/use-positions.ts","../../src/react/ws-reconcile.ts","../../src/react/use-contract-info.ts","../../src/react/use-limits.ts","../../src/react/use-cancel-position.ts","../../src/react/use-position-stream.ts","../../src/react/use-market-stream.ts"],"sourcesContent":["import { createContext, useContext, type ReactNode } from \"react\";\nimport type { DimesClient } from \"../client/dimes-client\";\nimport { DimesError } from \"../errors/dimes-error\";\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst DimesContext = createContext<DimesClient | null>(null);\n\nexport interface DimesProviderProps {\n client: DimesClient;\n children: ReactNode;\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/explicit-function-return-type\nexport function DimesProvider({ client, children }: DimesProviderProps) {\n return <DimesContext.Provider value={client}>{children}</DimesContext.Provider>;\n}\n\nexport function useDimesClient(): DimesClient {\n const client = useContext(DimesContext);\n if (!client) {\n throw new DimesError(\"missing_provider\", \"useDimesClient must be used within a <DimesProvider>\");\n }\n return client;\n}\n","import { useCallback, useReducer } from \"react\";\nimport { executeQuote } from \"../quote/quote\";\nimport type { HintAdjustment } from \"../quote/quote-error-hints\";\nimport type { Quote } from \"../types\";\nimport type { QuoteOptions, QuoteParams, QuoteResult } from \"../types/quote\";\nimport { useDimesClient } from \"./provider\";\n\nexport type QuotePhase = \"idle\" | \"loading-draft\" | \"draft-ready\" | \"promoting\" | \"promoted\" | \"market-moved\" | \"error\";\n\nexport interface QuoteState {\n phase: QuotePhase;\n draft?: Quote;\n quote?: Quote;\n /** @deprecated Renamed to {@link QuoteState.quote}. Still populated for backward compatibility. */\n // eslint-disable-next-line no-restricted-syntax -- intentional deprecated alias field\n offer?: Quote;\n corrections: HintAdjustment[];\n retries: number;\n error?: unknown;\n}\n\ntype Action =\n | { type: \"loading\" }\n | { type: \"draftReady\"; draft: Quote }\n | { type: \"promoting\" }\n | { type: \"marketMoved\" }\n | { type: \"done\"; result: QuoteResult }\n | { type: \"error\"; error: unknown }\n | { type: \"reset\" };\n\nfunction reducer(state: QuoteState, action: Action): QuoteState {\n switch (action.type) {\n case \"loading\":\n return { phase: \"loading-draft\", corrections: [], retries: 0 };\n case \"draftReady\":\n return { ...state, phase: \"draft-ready\", draft: action.draft };\n case \"promoting\":\n return { ...state, phase: \"promoting\" };\n case \"marketMoved\":\n return { ...state, phase: \"market-moved\" };\n case \"done\":\n return {\n phase: \"promoted\",\n quote: action.result.quote,\n offer: action.result.quote,\n corrections: action.result.corrections,\n retries: action.result.retries,\n draft: state.draft,\n };\n case \"error\":\n return { ...state, phase: \"error\", error: action.error };\n case \"reset\":\n return { phase: \"idle\", corrections: [], retries: 0 };\n default:\n return state;\n }\n}\n\nexport interface UseQuoteReturn {\n state: QuoteState;\n execute: (params: QuoteParams, options?: QuoteOptions) => Promise<QuoteResult>;\n reset: () => void;\n}\n\nexport function useQuote(): UseQuoteReturn {\n const client = useDimesClient();\n const [state, dispatch] = useReducer(reducer, {\n phase: \"idle\",\n corrections: [],\n retries: 0,\n });\n\n const execute = useCallback(\n async (params: QuoteParams, options?: QuoteOptions): Promise<QuoteResult> => {\n dispatch({ type: \"loading\" });\n\n try {\n const result = await executeQuote(client, params, {\n ...options,\n onDraftReady: (draft) => {\n dispatch({ type: \"draftReady\", draft });\n dispatch({ type: \"promoting\" });\n options?.onDraftReady?.(draft);\n },\n onMarketMoved: (event) => {\n dispatch({ type: \"marketMoved\" });\n return options?.onMarketMoved?.(event);\n },\n onCorrection: (adj) => {\n return options?.onCorrection?.(adj);\n },\n });\n\n dispatch({ type: \"done\", result });\n return result;\n } catch (err) {\n dispatch({ type: \"error\", error: err });\n throw err;\n }\n },\n [client],\n );\n\n const reset = useCallback(() => {\n dispatch({ type: \"reset\" });\n }, []);\n\n return { state, execute, reset };\n}\n","import { useCallback, useReducer, useRef } from \"react\";\nimport { buildQuoteParams } from \"../quote/build-quote-params\";\nimport { isMarketMovedError } from \"../quote/quote\";\nimport type { CreateQuoteParams, Quote } from \"../types\";\nimport type { QuoteParams } from \"../types/quote\";\nimport { useDimesClient } from \"./provider\";\n\nconst DEFAULT_MAX_RETRIES = 3;\n\n/**\n * Interactive, user-in-the-loop quote flow: draft → review → promote, pausing\n * across renders so the UI can show each step. This is the granular companion\n * to `useQuote`/`executeQuote` (which run draft→promote in one call). The steps\n * map directly onto the SDK client (`createDraftQuote`/`promoteDraftQuote`/\n * `createQuote`); on a market-moved promote failure it re-drafts and surfaces a\n * `market-moved` state so the user can review and accept the new draft.\n */\nexport type QuoteMachineState =\n | { phase: \"idle\" }\n | { phase: \"loading-draft\" }\n | { phase: \"draft-ready\"; draft: Quote; quotedAt: number }\n | { phase: \"promoting\"; draft: Quote; quotedAt: number }\n | { phase: \"promoted\"; draft: Quote; promotedQuote: Quote; correctedFrom?: Quote; quotedAt: number }\n | { phase: \"market-moved\"; originalDraft: Quote; newDraft: Quote; retryCount: number; quotedAt: number }\n | { phase: \"error\"; error: unknown; draft?: Quote };\n\ntype Action =\n | { type: \"loading\" }\n | { type: \"draftReady\"; draft: Quote; quotedAt: number }\n | { type: \"promoting\"; draft: Quote; quotedAt: number }\n | { type: \"promoted\"; draft: Quote; promotedQuote: Quote; correctedFrom?: Quote; quotedAt: number }\n | { type: \"marketMoved\"; originalDraft: Quote; newDraft: Quote; retryCount: number; quotedAt: number }\n | { type: \"error\"; error: unknown; draft?: Quote }\n | { type: \"reset\" };\n\nfunction reducer(_state: QuoteMachineState, action: Action): QuoteMachineState {\n switch (action.type) {\n case \"loading\":\n return { phase: \"loading-draft\" };\n case \"draftReady\":\n return { phase: \"draft-ready\", draft: action.draft, quotedAt: action.quotedAt };\n case \"promoting\":\n return { phase: \"promoting\", draft: action.draft, quotedAt: action.quotedAt };\n case \"promoted\":\n return {\n phase: \"promoted\",\n draft: action.draft,\n promotedQuote: action.promotedQuote,\n correctedFrom: action.correctedFrom,\n quotedAt: action.quotedAt,\n };\n case \"marketMoved\":\n return {\n phase: \"market-moved\",\n originalDraft: action.originalDraft,\n newDraft: action.newDraft,\n retryCount: action.retryCount,\n quotedAt: action.quotedAt,\n };\n case \"error\":\n return { phase: \"error\", error: action.error, draft: action.draft };\n case \"reset\":\n return { phase: \"idle\" };\n default:\n return _state;\n }\n}\n\nexport interface UseQuoteMachineOptions {\n /** Maximum number of re-draft attempts on a market-moved promote failure. Default 3. */\n maxRetries?: number;\n}\n\nexport interface UseQuoteMachineReturn {\n state: QuoteMachineState;\n /** Build params from a `QuoteParams` and fetch a draft quote. Moves to `draft-ready`. */\n getDraft: (params: QuoteParams) => Promise<void>;\n /** Promote a reviewed draft into a signed quote. On market-moved, re-drafts and surfaces `market-moved`. */\n promote: (draft: Quote, retryCount?: number) => Promise<void>;\n /** Accept a re-drafted quote after a `market-moved` and promote it. */\n acceptChanges: (newDraft: Quote, retryCount: number) => Promise<void>;\n /** Promote pre-adjusted params directly via `createQuote` (e.g. after applying a correction hint). */\n correctAndPromote: (originalDraft: Quote, adjustedParams: CreateQuoteParams) => Promise<void>;\n reset: () => void;\n}\n\nexport function useQuoteMachine(options?: UseQuoteMachineOptions): UseQuoteMachineReturn {\n const client = useDimesClient();\n const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n const [state, dispatch] = useReducer(reducer, { phase: \"idle\" } as QuoteMachineState);\n const lastParamsRef = useRef<CreateQuoteParams | null>(null);\n const quotedAtRef = useRef(0);\n\n const getDraft = useCallback(\n async (params: QuoteParams): Promise<void> => {\n dispatch({ type: \"loading\" });\n const quoteParams = buildQuoteParams(params);\n lastParamsRef.current = quoteParams;\n try {\n const draft = await client.createDraftQuote(quoteParams);\n\n quotedAtRef.current = Date.now();\n dispatch({ type: \"draftReady\", draft, quotedAt: quotedAtRef.current });\n } catch (err) {\n dispatch({ type: \"error\", error: err });\n }\n },\n [client],\n );\n\n const promote = useCallback(\n async (draft: Quote, retryCount = 0): Promise<void> => {\n const quotedAt = quotedAtRef.current;\n dispatch({ type: \"promoting\", draft, quotedAt });\n try {\n const promotedQuote = await client.promoteDraftQuote(draft.id);\n dispatch({ type: \"promoted\", draft, promotedQuote, quotedAt });\n } catch (err) {\n if (isMarketMovedError(err) && retryCount < maxRetries && lastParamsRef.current) {\n try {\n const newDraft = await client.createDraftQuote(lastParamsRef.current);\n // eslint-disable-next-line require-atomic-updates -- timestamp ref, no contended state\n quotedAtRef.current = Date.now();\n dispatch({\n type: \"marketMoved\",\n originalDraft: draft,\n newDraft,\n retryCount: retryCount + 1,\n quotedAt: quotedAtRef.current,\n });\n } catch (draftErr) {\n dispatch({ type: \"error\", error: draftErr, draft });\n }\n } else {\n dispatch({ type: \"error\", error: err, draft });\n }\n }\n },\n [client, maxRetries],\n );\n\n const acceptChanges = useCallback(\n async (newDraft: Quote, retryCount: number): Promise<void> => {\n await promote(newDraft, retryCount);\n },\n [promote],\n );\n\n const correctAndPromote = useCallback(\n async (originalDraft: Quote, adjustedParams: CreateQuoteParams): Promise<void> => {\n dispatch({ type: \"promoting\", draft: originalDraft, quotedAt: quotedAtRef.current });\n lastParamsRef.current = adjustedParams;\n try {\n const promotedQuote = await client.createQuote(adjustedParams);\n // eslint-disable-next-line require-atomic-updates -- timestamp ref, no contended state\n quotedAtRef.current = Date.now();\n dispatch({\n type: \"promoted\",\n draft: promotedQuote,\n promotedQuote,\n correctedFrom: originalDraft,\n quotedAt: quotedAtRef.current,\n });\n } catch (err) {\n dispatch({ type: \"error\", error: err });\n }\n },\n [client],\n );\n\n const reset = useCallback((): void => {\n dispatch({ type: \"reset\" });\n lastParamsRef.current = null;\n quotedAtRef.current = 0;\n }, []);\n\n return { state, getDraft, promote, acceptChanges, correctAndPromote, reset };\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\n// eslint-disable-next-line import-x/no-deprecated -- SearchMarketsParams imported for the deprecated shim below\nimport type { GetMarketsParams, SearchMarketsParams } from \"../client/dimes-client\";\nimport type { Market, Paginated } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function useMarkets(\n params?: GetMarketsParams,\n queryOptions?: Partial<UseQueryOptions<Paginated<Market>>>,\n): UseQueryResult<Paginated<Market>> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"markets\", params],\n queryFn: () => client.getMarkets(params),\n ...queryOptions,\n });\n}\n\n/**\n * @deprecated Use {@link useMarkets} with a `query` param: `useMarkets({ query })`.\n * Search is now served by `GET /markets?query=` instead of the deprecated `/markets/search` path.\n */\nexport function useSearchMarkets(\n // eslint-disable-next-line @typescript-eslint/no-deprecated, import-x/no-deprecated -- this IS the deprecated hook\n params: SearchMarketsParams,\n queryOptions?: Partial<UseQueryOptions<Paginated<Market>>>,\n): UseQueryResult<Paginated<Market>> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"markets\", \"search\", params],\n queryFn: () => client.getMarkets(params),\n enabled: !!params.query,\n ...queryOptions,\n });\n}\n\nexport function useMarket(ticker: string, queryOptions?: Partial<UseQueryOptions<Market>>): UseQueryResult<Market> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"market\", ticker],\n queryFn: () => client.getMarket(ticker),\n enabled: !!ticker,\n ...queryOptions,\n });\n}\n","import { useQuery, type Query, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { GetPositionsParams } from \"../client/dimes-client\";\nimport type { Position } from \"../types\";\nimport { useDimesClient } from \"./provider\";\nimport { defaultReconciliationWindowMs, reconcilePolledPositions, transientPositionStatuses } from \"./ws-reconcile\";\n\nconst DEFAULT_FAST_POLL_MS = 5_000;\nconst DEFAULT_SLOW_POLL_MS = 15_000;\n\nexport interface UsePositionsOptions {\n /**\n * Appended to the query key so changing scope (e.g. switching wallet) does not serve the previous\n * scope's cached positions until a refetch. Omit to keep the default, scope-less cache key.\n */\n scope?: string | null;\n /**\n * Poll faster while any position is in a transient state (pending/closing/settling/unwinding) and\n * slower otherwise. Pass `true` for the defaults (5s / 15s) or an object to tune them.\n */\n adaptivePolling?: boolean | { fastMs?: number; slowMs?: number };\n /**\n * Defer to fresher WebSocket data: when a position was updated over the socket within the\n * reconciliation window, a slower REST poll won't overwrite it. Use with `usePositionStream` in\n * reconcile mode. Pass `true` for the default window or a number of milliseconds.\n */\n reconcile?: boolean | number;\n}\n\nfunction adaptiveRefetchInterval(\n adaptive: NonNullable<UsePositionsOptions[\"adaptivePolling\"]>,\n): (query: Query<Position[]>) => number {\n const fastMs = typeof adaptive === \"object\" ? (adaptive.fastMs ?? DEFAULT_FAST_POLL_MS) : DEFAULT_FAST_POLL_MS;\n const slowMs = typeof adaptive === \"object\" ? (adaptive.slowMs ?? DEFAULT_SLOW_POLL_MS) : DEFAULT_SLOW_POLL_MS;\n return (query) => (query.state.data?.some((p) => transientPositionStatuses.has(p.status)) ? fastMs : slowMs);\n}\n\nfunction reconcileStructuralSharing(reconcile: number | true): (oldData: unknown, newData: unknown) => Position[] {\n const windowMs = typeof reconcile === \"number\" ? reconcile : defaultReconciliationWindowMs;\n return (oldData, newData) =>\n reconcilePolledPositions(oldData as Position[] | undefined, newData as Position[], windowMs, Date.now());\n}\n\nexport function usePositions(\n params?: GetPositionsParams,\n queryOptions?: Partial<UseQueryOptions<Position[]>>,\n options?: UsePositionsOptions,\n): UseQueryResult<Position[]> {\n const client = useDimesClient();\n\n const queryKey =\n options?.scope !== undefined ? [\"dimes\", \"positions\", params, options.scope] : [\"dimes\", \"positions\", params];\n\n const config: UseQueryOptions<Position[]> = {\n queryKey,\n queryFn: () => client.getPositions(params),\n };\n\n if (options?.adaptivePolling) {\n config.refetchInterval = adaptiveRefetchInterval(options.adaptivePolling);\n }\n\n if (options?.reconcile) {\n config.structuralSharing = reconcileStructuralSharing(options.reconcile);\n }\n\n return useQuery({ ...config, ...queryOptions });\n}\n","import type { QueryClient } from \"@tanstack/react-query\";\nimport type { Market, Paginated, Position } from \"../types\";\nimport type { MarketDelta, PositionEvent } from \"../ws\";\n\n/**\n * Shared plumbing for merging WebSocket events into the React Query cache. Used by the optional\n * reconcile mode of `usePositionStream` / `useMarketStream` and the `reconcile` option on\n * `usePositions`. Kept internal so the query keys and the WS-timestamp registry stay in sync.\n */\n\nexport const positionsQueryKey = [\"dimes\", \"positions\"] as const;\n\nexport const marketsQueryKey = [\"dimes\", \"markets\"] as const;\n\nexport const defaultReconciliationWindowMs = 12_000;\n\n/** Position statuses that indicate an in-flight transition — polled faster by `adaptivePolling`. */\nexport const transientPositionStatuses: ReadonlySet<string> = new Set([\"pending\", \"closing\", \"settling\", \"unwinding\"]);\n\n/**\n * Records the last time each position id was written from a WebSocket event. Polling reconciliation\n * uses this so a slower REST poll never clobbers fresher WS data inside the reconciliation window.\n */\nexport const wsPositionTimestamps = new Map<string, number>();\n\n/** Merge a single position event into every cached positions query. */\nexport function mergePositionEvent(queryClient: QueryClient, event: PositionEvent, now: number): void {\n const position = event.data;\n queryClient.setQueriesData<Position[]>({ queryKey: positionsQueryKey }, (old) => {\n if (!old) {\n return old;\n }\n const idx = old.findIndex((p) => p.id === position.id);\n if (idx >= 0) {\n const next = [...old];\n next[idx] = position;\n return next;\n }\n if (event.type === \"position.created\") {\n return [position, ...old];\n }\n return old;\n });\n wsPositionTimestamps.set(position.id, now);\n}\n\n/**\n * `structuralSharing` for a polled positions list: keep the cached (WS-fresher) copy of any position\n * updated over the socket within `windowMs`, otherwise accept the polled copy.\n */\nexport function reconcilePolledPositions(\n oldData: Position[] | undefined,\n newData: Position[],\n windowMs: number,\n now: number,\n): Position[] {\n if (!oldData) {\n return newData;\n }\n return newData.map((polled) => {\n const wsTime = wsPositionTimestamps.get(polled.id);\n if (wsTime !== undefined && now - wsTime < windowMs) {\n const fresher = oldData.find((p) => p.id === polled.id);\n return fresher ?? polled;\n }\n if (wsTime !== undefined) {\n wsPositionTimestamps.delete(polled.id);\n }\n return polled;\n });\n}\n\n/**\n * Deep-merge a market delta onto a cached market. The nested `leverage` block must be merged rather\n * than replaced — a max-leverage delta carries only the changed leverage fields, so a shallow spread\n * would drop the constant `minBps`/`stepBps` until the next full refetch.\n */\nfunction mergeMarket(prev: Market, delta: MarketDelta): Market {\n return {\n ...prev,\n ...delta,\n leverage: delta.leverage ? { ...prev.leverage, ...delta.leverage } : prev.leverage,\n };\n}\n\n/** Merge market deltas into every cached paginated markets query (no-op for ids not present). */\nexport function mergeMarketDeltas(queryClient: QueryClient, deltas: MarketDelta[]): void {\n queryClient.setQueriesData<Paginated<Market>>({ queryKey: marketsQueryKey }, (old) => {\n if (!old) {\n return old;\n }\n const data = old.data.map((market) => {\n const delta = deltas.find((d) => d.id === market.id);\n return delta ? mergeMarket(market, delta) : market;\n });\n const changed = data.some((market, i) => market !== old.data[i]);\n return changed ? { ...old, data } : old;\n });\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { ContractInfo } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function useContractInfo(queryOptions?: Partial<UseQueryOptions<ContractInfo>>): UseQueryResult<ContractInfo> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"contractInfo\"],\n queryFn: () => client.getContractInfo(),\n staleTime: Infinity,\n ...queryOptions,\n });\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { CustomerLimit } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\n/** User trading limits (JWT auth) — `GET /user-limits`. */\nexport function useUserLimits(queryOptions?: Partial<UseQueryOptions<CustomerLimit>>): UseQueryResult<CustomerLimit> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"user-limits\"],\n queryFn: () => client.getUserLimits(),\n ...queryOptions,\n });\n}\n\n/** Partner-wide limits (API-key auth) — `GET /partner-limits`. */\nexport function usePartnerLimits(\n queryOptions?: Partial<UseQueryOptions<CustomerLimit>>,\n): UseQueryResult<CustomerLimit> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"partner-limits\"],\n queryFn: () => client.getPartnerLimits(),\n ...queryOptions,\n });\n}\n\n/** @deprecated Use {@link useUserLimits}. Alias kept for back-compat; resolves to user limits. */\nexport function useLimits(queryOptions?: Partial<UseQueryOptions<CustomerLimit>>): UseQueryResult<CustomerLimit> {\n return useUserLimits(queryOptions);\n}\n","import { useMutation, type UseMutationOptions, type UseMutationResult } from \"@tanstack/react-query\";\nimport { DimesApiError } from \"../errors/dimes-error\";\nimport { useDimesClient } from \"./provider\";\n\nconst HTTP_CONFLICT = 409;\n\nexport type CancelPositionResult = \"cancelled\" | \"already_cancelling\";\n\nexport interface UseCancelPositionOptions {\n /**\n * Treat a 409 Conflict (the position is already being cancelled) as success, resolving to\n * `\"already_cancelling\"` instead of throwing. Default false — a 409 rejects like any other error.\n */\n treatConflictAsAlreadyCancelling?: boolean;\n}\n\nexport function useCancelPosition(\n mutationOptions?: Partial<UseMutationOptions<CancelPositionResult, Error, string>>,\n options?: UseCancelPositionOptions,\n): UseMutationResult<CancelPositionResult, Error, string> {\n const client = useDimesClient();\n const treatConflictAsAlreadyCancelling = options?.treatConflictAsAlreadyCancelling ?? false;\n\n return useMutation({\n mutationFn: async (positionId: string): Promise<CancelPositionResult> => {\n try {\n await client.cancelPosition(positionId);\n return \"cancelled\";\n } catch (err) {\n if (treatConflictAsAlreadyCancelling && err instanceof DimesApiError && err.status === HTTP_CONFLICT) {\n return \"already_cancelling\";\n }\n throw err;\n }\n },\n ...mutationOptions,\n });\n}\n","import { useQueryClient } from \"@tanstack/react-query\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { PositionSocket, type NotificationEvent, type PositionEvent } from \"../ws\";\nimport { useDimesClient } from \"./provider\";\nimport { mergePositionEvent, positionsQueryKey } from \"./ws-reconcile\";\n\nexport type StreamMode = \"raw\" | \"reconcile\";\n\nexport interface UsePositionStreamOptions {\n /** Connect the socket. Default true. Set false to gate on auth being ready. */\n enabled?: boolean;\n /**\n * `\"reconcile\"` (default) merges every event into the `usePositions` query cache so the UI updates\n * instantly; `\"raw\"` does not touch the cache and only forwards events to your callbacks.\n */\n mode?: StreamMode;\n /** Disconnect while the tab is hidden and reconnect when it becomes visible again. Default true. */\n pauseOnHidden?: boolean;\n /** Invalidate the positions query on reconnect (skipping the first connect) to catch missed events. Default true. */\n invalidateOnReconnect?: boolean;\n /** Always called with the raw (camelCased) event, in both modes. */\n onEvent?: (event: PositionEvent) => void;\n /** Called with user-gateway notification events (toasts, fill progress…). Never touches the cache. */\n onNotification?: (event: NotificationEvent) => void;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: unknown) => void;\n}\n\nexport interface UsePositionStreamResult {\n socket: PositionSocket | null;\n connected: boolean;\n}\n\n/**\n * Subscribe to the user position WebSocket gateway. In `reconcile` mode (default) events are merged\n * into the React Query cache used by `usePositions`; in `raw` mode you handle events yourself via\n * `onEvent`. App-specific side effects (toasts, stores) belong in the callbacks, not the SDK.\n */\nexport function usePositionStream(options?: UsePositionStreamOptions): UsePositionStreamResult {\n const client = useDimesClient();\n const queryClient = useQueryClient();\n const socketRef = useRef<PositionSocket | null>(null);\n const [connected, setConnected] = useState(false);\n\n const enabled = options?.enabled ?? true;\n const mode = options?.mode ?? \"reconcile\";\n const pauseOnHidden = options?.pauseOnHidden ?? true;\n const invalidateOnReconnect = options?.invalidateOnReconnect ?? true;\n\n // Keep the latest callbacks/flags in a ref so the socket effect does not reconnect on every render.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n useEffect(() => {\n if (!enabled) {\n return undefined;\n }\n\n const socket = new PositionSocket({\n baseUrl: client.baseUrl,\n getToken: (): string | null => client.getToken(),\n });\n socketRef.current = socket;\n\n const unsubEvent = socket.on(\"*\", (event) => {\n if (mode === \"reconcile\") {\n mergePositionEvent(queryClient, event, Date.now());\n }\n optionsRef.current?.onEvent?.(event);\n });\n\n const unsubNotification = socket.onNotification((event) => {\n optionsRef.current?.onNotification?.(event);\n });\n\n let firstConnect = true;\n const unsubConnect = socket.onConnect(() => {\n setConnected(true);\n if (firstConnect) {\n firstConnect = false;\n } else if (mode === \"reconcile\" && invalidateOnReconnect) {\n void queryClient.invalidateQueries({ queryKey: positionsQueryKey });\n }\n optionsRef.current?.onConnect?.();\n });\n\n const unsubDisconnect = socket.onDisconnect(() => {\n setConnected(false);\n optionsRef.current?.onDisconnect?.();\n });\n\n const unsubError = socket.onError((error) => {\n optionsRef.current?.onError?.(error);\n });\n\n const handleVisibility =\n pauseOnHidden && typeof document !== \"undefined\"\n ? (): void => {\n if (document.hidden) {\n socket.disconnect();\n } else {\n socket.connect();\n }\n }\n : null;\n if (handleVisibility) {\n document.addEventListener(\"visibilitychange\", handleVisibility);\n }\n\n socket.connect();\n\n return (): void => {\n if (handleVisibility) {\n document.removeEventListener(\"visibilitychange\", handleVisibility);\n }\n unsubEvent();\n unsubNotification();\n unsubConnect();\n unsubDisconnect();\n unsubError();\n socket.disconnect();\n socketRef.current = null;\n setConnected(false);\n };\n }, [client, queryClient, enabled, mode, pauseOnHidden, invalidateOnReconnect]);\n\n return { socket: socketRef.current, connected };\n}\n","import { useQueryClient } from \"@tanstack/react-query\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { MarketSocket, type MarketDelta, type MarketEvent } from \"../ws\";\nimport { useDimesClient } from \"./provider\";\nimport type { StreamMode } from \"./use-position-stream\";\nimport { marketsQueryKey, mergeMarketDeltas } from \"./ws-reconcile\";\n\nexport interface UseMarketStreamOptions {\n /** Connect the socket. Default true. */\n enabled?: boolean;\n /**\n * `\"reconcile\"` (default) merges `eligibility_changed` / `max_leverage_changed` deltas into the\n * `useMarkets` query cache; `\"raw\"` only forwards events. `market.discovered` events are never\n * injected into the paginated cache (that would pollute server-filtered views) — handle them via\n * `onEvent` in either mode.\n */\n mode?: StreamMode;\n /** Disconnect while the tab is hidden and reconnect when visible again. Default true. */\n pauseOnHidden?: boolean;\n /** Invalidate the markets query on reconnect (skipping the first connect). Default true. */\n invalidateOnReconnect?: boolean;\n /** Always called with the raw (camelCased) event, in both modes. */\n onEvent?: (event: MarketEvent) => void;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: unknown) => void;\n}\n\nexport interface UseMarketStreamResult {\n socket: MarketSocket | null;\n connected: boolean;\n}\n\n/**\n * Subscribe to the user market WebSocket gateway. In `reconcile` mode (default) eligibility and\n * max-leverage deltas are deep-merged into the `useMarkets` cache; discovered markets are forwarded\n * to `onEvent` for the app to route (e.g. a \"new markets\" strip).\n */\nexport function useMarketStream(options?: UseMarketStreamOptions): UseMarketStreamResult {\n const client = useDimesClient();\n const queryClient = useQueryClient();\n const socketRef = useRef<MarketSocket | null>(null);\n const [connected, setConnected] = useState(false);\n\n const enabled = options?.enabled ?? true;\n const mode = options?.mode ?? \"reconcile\";\n const pauseOnHidden = options?.pauseOnHidden ?? true;\n const invalidateOnReconnect = options?.invalidateOnReconnect ?? true;\n\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n useEffect(() => {\n if (!enabled) {\n return undefined;\n }\n\n const socket = new MarketSocket({\n baseUrl: client.baseUrl,\n getToken: (): string | null => client.getToken(),\n });\n socketRef.current = socket;\n\n const unsubEvent = socket.on(\"*\", (event) => {\n if (mode === \"reconcile\" && event.type !== \"market.discovered\") {\n mergeMarketDeltas(queryClient, event.data as MarketDelta[]);\n }\n optionsRef.current?.onEvent?.(event);\n });\n\n let firstConnect = true;\n const unsubConnect = socket.onConnect(() => {\n setConnected(true);\n if (firstConnect) {\n firstConnect = false;\n } else if (mode === \"reconcile\" && invalidateOnReconnect) {\n void queryClient.invalidateQueries({ queryKey: marketsQueryKey });\n }\n optionsRef.current?.onConnect?.();\n });\n\n const unsubDisconnect = socket.onDisconnect(() => {\n setConnected(false);\n optionsRef.current?.onDisconnect?.();\n });\n\n const unsubError = socket.onError((error) => {\n optionsRef.current?.onError?.(error);\n });\n\n const handleVisibility =\n pauseOnHidden && typeof document !== \"undefined\"\n ? (): void => {\n if (document.hidden) {\n socket.disconnect();\n } else {\n socket.connect();\n }\n }\n : null;\n if (handleVisibility) {\n document.addEventListener(\"visibilitychange\", handleVisibility);\n }\n\n socket.connect();\n\n return (): void => {\n if (handleVisibility) {\n document.removeEventListener(\"visibilitychange\", handleVisibility);\n }\n unsubEvent();\n unsubConnect();\n unsubDisconnect();\n unsubError();\n socket.disconnect();\n socketRef.current = null;\n setConnected(false);\n };\n }, [client, queryClient, enabled, mode, pauseOnHidden, invalidateOnReconnect]);\n\n return { socket: socketRef.current, connected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AAM,SAAS,qBAAqB;AAC9D,0BAAkB,aAAa,MAAM,IAAqB;AAAA,MAC5D;AACA,iBAAW,SAAS,UAAU,KAAK;AAAA,IACrC,CAAC;AAED,QAAI,eAAe;AACnB,UAAM,eAAe,OAAO,UAAU,MAAM;AAC1C,mBAAa,IAAI;AACjB,UAAI,cAAc;AAChB,uBAAe;AAAA,MACjB,WAAW,SAAS,eAAe,uBAAuB;AACxD,aAAK,YAAY,kBAAkB,EAAE,UAAU,gBAAgB,CAAC;AAAA,MAClE;AACA,iBAAW,SAAS,YAAY;AAAA,IAClC,CAAC;AAED,UAAM,kBAAkB,OAAO,aAAa,MAAM;AAChD,mBAAa,KAAK;AAClB,iBAAW,SAAS,eAAe;AAAA,IACrC,CAAC;AAED,UAAM,aAAa,OAAO,QAAQ,CAAC,UAAU;AAC3C,iBAAW,SAAS,UAAU,KAAK;AAAA,IACrC,CAAC;AAED,UAAM,mBACJ,iBAAiB,OAAO,aAAa,cACjC,MAAY;AACV,UAAI,SAAS,QAAQ;AACnB,eAAO,WAAW;AAAA,MACpB,OAAO;AACL,eAAO,QAAQ;AAAA,MACjB;AAAA,IACF,IACA;AACN,QAAI,kBAAkB;AACpB,eAAS,iBAAiB,oBAAoB,gBAAgB;AAAA,IAChE;AAEA,WAAO,QAAQ;AAEf,WAAO,MAAY;AACjB,UAAI,kBAAkB;AACpB,iBAAS,oBAAoB,oBAAoB,gBAAgB;AAAA,MACnE;AACA,iBAAW;AACX,mBAAa;AACb,sBAAgB;AAChB,iBAAW;AACX,aAAO,WAAW;AAClB,gBAAU,UAAU;AACpB,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF,GAAG,CAAC,QAAQ,aAAa,SAAS,MAAM,eAAe,qBAAqB,CAAC;AAE7E,SAAO,EAAE,QAAQ,UAAU,SAAS,UAAU;AAChD;","names":["useCallback","useReducer","reducer","useReducer","useCallback","useQuery","useQuery","useQuery","useQuery","useQuery","useQuery","useRef","useRef","useQueryClient","useEffect","useRef","useState","useQueryClient","useRef","useState","useEffect"]}
|