@dimes-dot-fi/sdk 2.3.0 → 2.5.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.
Files changed (44) hide show
  1. package/README.md +10 -0
  2. package/dist/{aliases-Dne14KBa.d.cts → aliases-lNsFUKPA.d.cts} +147 -10
  3. package/dist/{aliases-Dne14KBa.d.ts → aliases-lNsFUKPA.d.ts} +147 -10
  4. package/dist/{chunk-E6YJDY4F.cjs → chunk-ERM4WP6D.cjs} +9 -4
  5. package/dist/chunk-ERM4WP6D.cjs.map +1 -0
  6. package/dist/{chunk-4OKYU5D7.mjs → chunk-GA7ZBK6W.mjs} +9 -4
  7. package/dist/chunk-GA7ZBK6W.mjs.map +1 -0
  8. package/dist/{chunk-IJO5E22G.mjs → chunk-HJ5EVO5A.mjs} +11 -6
  9. package/dist/chunk-HJ5EVO5A.mjs.map +1 -0
  10. package/dist/{chunk-GY6L2QGR.cjs → chunk-L273PAD4.cjs} +14 -9
  11. package/dist/chunk-L273PAD4.cjs.map +1 -0
  12. package/dist/contract/index.cjs +557 -67
  13. package/dist/contract/index.cjs.map +1 -1
  14. package/dist/contract/index.d.cts +69 -8
  15. package/dist/contract/index.d.ts +69 -8
  16. package/dist/contract/index.mjs +544 -54
  17. package/dist/contract/index.mjs.map +1 -1
  18. package/dist/{dimes-client-DJ1d_p31.d.ts → dimes-client-BUAeOsgL.d.cts} +48 -3
  19. package/dist/{dimes-client-D9tohawC.d.cts → dimes-client-DDF-f8yA.d.ts} +48 -3
  20. package/dist/{dimes-error-hSoOierP.d.ts → dimes-error-CkcjExUy.d.ts} +1 -1
  21. package/dist/{dimes-error-E9yPAZb-.d.cts → dimes-error-I7lEZ2V5.d.cts} +1 -1
  22. package/dist/index.cjs +78 -8
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +10 -9
  25. package/dist/index.d.ts +10 -9
  26. package/dist/index.mjs +74 -4
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/{quote-D4QunMtN.d.ts → quote-B_cMLw7P.d.cts} +7 -2
  29. package/dist/{quote-sWguOcoJ.d.cts → quote-Z88cryAN.d.ts} +7 -2
  30. package/dist/react/index.cjs +34 -33
  31. package/dist/react/index.cjs.map +1 -1
  32. package/dist/react/index.d.cts +12 -8
  33. package/dist/react/index.d.ts +12 -8
  34. package/dist/react/index.mjs +7 -6
  35. package/dist/react/index.mjs.map +1 -1
  36. package/dist/{types-BHU4Qq7e.d.ts → types-BvZf3uFL.d.ts} +1 -1
  37. package/dist/{types-Bvj_WDbX.d.cts → types-F2rHf2Qv.d.cts} +1 -1
  38. package/dist/ws/index.d.cts +3 -3
  39. package/dist/ws/index.d.ts +3 -3
  40. package/package.json +1 -1
  41. package/dist/chunk-4OKYU5D7.mjs.map +0 -1
  42. package/dist/chunk-E6YJDY4F.cjs.map +0 -1
  43. package/dist/chunk-GY6L2QGR.cjs.map +0 -1
  44. package/dist/chunk-IJO5E22G.mjs.map +0 -1
@@ -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-partial-closes.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 { PositionPartialCloseList } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function usePositionPartialCloses(\n positionId: string | null | undefined,\n queryOptions?: Partial<UseQueryOptions<PositionPartialCloseList>>,\n): UseQueryResult<PositionPartialCloseList> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"positionPartialCloses\", positionId],\n queryFn: () => {\n if (positionId == null) {\n return Promise.reject(new Error(\"positionId is required\"));\n }\n return client.getPositionPartialCloses(positionId);\n },\n enabled: Boolean(positionId),\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,WAAW,oBAAoB,sDAAsD;AAAA,EACjG;AACA,SAAO;AACT;;;ACvBA,SAAS,aAAa,kBAAkB;AA8BxC,SAAS,QAAQ,OAAmB,QAA4B;AAC9D,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AACH,aAAO,EAAE,OAAO,iBAAiB,aAAa,CAAC,GAAG,SAAS,EAAE;AAAA,IAC/D,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,OAAO,eAAe,OAAO,OAAO,MAAM;AAAA,IAC/D,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,OAAO,YAAY;AAAA,IACxC,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,OAAO,eAAe;AAAA,IAC3C,KAAK;AACH,aAAO;AAAA,QACL,OAAO;AAAA,QACP,OAAO,OAAO,OAAO;AAAA,QACrB,OAAO,OAAO,OAAO;AAAA,QACrB,aAAa,OAAO,OAAO;AAAA,QAC3B,SAAS,OAAO,OAAO;AAAA,QACvB,OAAO,MAAM;AAAA,MACf;AAAA,IACF,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,OAAO,SAAS,OAAO,OAAO,MAAM;AAAA,IACzD,KAAK;AACH,aAAO,EAAE,OAAO,QAAQ,aAAa,CAAC,GAAG,SAAS,EAAE;AAAA,IACtD;AACE,aAAO;AAAA,EACX;AACF;AAQO,SAAS,WAA2B;AACzC,QAAM,SAAS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AA,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","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-partial-closes.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, RiskMode } 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 /**\n * Promote a reviewed draft into a signed quote, in `riskMode` if given — a draft is always drawn\n * up as adaptive, so this is where a mode the user picked after seeing the draft is applied.\n * On market-moved, re-drafts and surfaces `market-moved`.\n */\n promote: (draft: Quote, retryCount?: number, riskMode?: RiskMode) => Promise<void>;\n /** Accept a re-drafted quote after a `market-moved` and promote it, in `riskMode` if given. */\n acceptChanges: (newDraft: Quote, retryCount: number, riskMode?: RiskMode) => 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, riskModeOverride?: RiskMode): Promise<void> => {\n const quotedAt = quotedAtRef.current;\n dispatch({ type: \"promoting\", draft, quotedAt });\n try {\n // A draft carries no mode — the promotion query decides it, and omitting it means adaptive.\n // The caller passes the mode the user picked off the draft's `committedUnwinds`; without one,\n // fall back to the mode the draft was requested with.\n const riskMode = riskModeOverride ?? lastParamsRef.current?.riskMode;\n const promotedQuote = await client.promoteDraftQuote(draft.id, riskMode ? { riskMode } : undefined);\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, riskMode?: RiskMode): Promise<void> => {\n await promote(newDraft, retryCount, riskMode);\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 { PositionPartialCloseList } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function usePositionPartialCloses(\n positionId: string | null | undefined,\n queryOptions?: Partial<UseQueryOptions<PositionPartialCloseList>>,\n): UseQueryResult<PositionPartialCloseList> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"positionPartialCloses\", positionId],\n queryFn: () => {\n if (positionId == null) {\n return Promise.reject(new Error(\"positionId is required\"));\n }\n return client.getPositionPartialCloses(positionId);\n },\n enabled: Boolean(positionId),\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,WAAW,oBAAoB,sDAAsD;AAAA,EACjG;AACA,SAAO;AACT;;;ACvBA,SAAS,aAAa,kBAAkB;AA8BxC,SAAS,QAAQ,OAAmB,QAA4B;AAC9D,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AACH,aAAO,EAAE,OAAO,iBAAiB,aAAa,CAAC,GAAG,SAAS,EAAE;AAAA,IAC/D,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,OAAO,eAAe,OAAO,OAAO,MAAM;AAAA,IAC/D,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,OAAO,YAAY;AAAA,IACxC,KAAK;AACH,aAAO,EAAE,GAAG,OAAO,OAAO,eAAe;AAAA,IAC3C,KAAK;AACH,aAAO;AAAA,QACL,OAAO;AAAA,QACP,OAAO,OAAO,OAAO;AAAA,QACrB,OAAO,OAAO,OAAO;AAAA,QACrB,aAAa,OAAO,OAAO;AAAA,QAC3B,SAAS,OAAO,OAAO;AAAA,QACvB,OAAO,MAAM;AAAA,MACf;AAAA,IACF,KAAK;AACH,aAAO,EAAE,GAAG,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,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","useQuery","useQuery","useRef","useRef","useQueryClient","useEffect","useRef","useState","useQueryClient","useRef","useState","useEffect"]}
@@ -1,4 +1,4 @@
1
- import { P as Position, M as Market, a as MarketPolymarket, b as MarketLeverage } from './aliases-Dne14KBa.js';
1
+ import { P as Position, M as Market, a as MarketPolymarket, b as MarketLeverage } from './aliases-lNsFUKPA.js';
2
2
 
3
3
  declare const positionEventTypes: readonly ["position.cancelled", "position.close_requested", "position.closed", "position.created", "position.force_unwound", "position.liquidated", "position.opened", "position.opening", "position.partial_close_requested", "position.partial_close_initiated", "position.partial_closed", "position.partial_close_aborted", "position.reverted", "position.settled", "position.settlement_state_changed"];
4
4
  type PositionEventType = (typeof positionEventTypes)[number];
@@ -1,4 +1,4 @@
1
- import { P as Position, M as Market, a as MarketPolymarket, b as MarketLeverage } from './aliases-Dne14KBa.cjs';
1
+ import { P as Position, M as Market, a as MarketPolymarket, b as MarketLeverage } from './aliases-lNsFUKPA.cjs';
2
2
 
3
3
  declare const positionEventTypes: readonly ["position.cancelled", "position.close_requested", "position.closed", "position.created", "position.force_unwound", "position.liquidated", "position.opened", "position.opening", "position.partial_close_requested", "position.partial_close_initiated", "position.partial_closed", "position.partial_close_aborted", "position.reverted", "position.settled", "position.settlement_state_changed"];
4
4
  type PositionEventType = (typeof positionEventTypes)[number];
@@ -1,6 +1,6 @@
1
- import { a as PositionEventType, P as PositionEvent, N as NotificationEvent, b as MarketEventType, M as MarketEvent } from '../types-Bvj_WDbX.cjs';
2
- export { c as MarketDelta, d as MarketEventEnvelope, e as NotificationCode, f as NotificationEventEnvelope, g as PositionEventEnvelope, m as marketEventTypes, n as notificationCodes, p as positionEventTypes } from '../types-Bvj_WDbX.cjs';
3
- import '../aliases-Dne14KBa.cjs';
1
+ import { a as PositionEventType, P as PositionEvent, N as NotificationEvent, b as MarketEventType, M as MarketEvent } from '../types-F2rHf2Qv.cjs';
2
+ export { c as MarketDelta, d as MarketEventEnvelope, e as NotificationCode, f as NotificationEventEnvelope, g as PositionEventEnvelope, m as marketEventTypes, n as notificationCodes, p as positionEventTypes } from '../types-F2rHf2Qv.cjs';
3
+ import '../aliases-lNsFUKPA.cjs';
4
4
 
5
5
  interface PositionSocketOptions {
6
6
  baseUrl?: string;
@@ -1,6 +1,6 @@
1
- import { a as PositionEventType, P as PositionEvent, N as NotificationEvent, b as MarketEventType, M as MarketEvent } from '../types-BHU4Qq7e.js';
2
- export { c as MarketDelta, d as MarketEventEnvelope, e as NotificationCode, f as NotificationEventEnvelope, g as PositionEventEnvelope, m as marketEventTypes, n as notificationCodes, p as positionEventTypes } from '../types-BHU4Qq7e.js';
3
- import '../aliases-Dne14KBa.js';
1
+ import { a as PositionEventType, P as PositionEvent, N as NotificationEvent, b as MarketEventType, M as MarketEvent } from '../types-BvZf3uFL.js';
2
+ export { c as MarketDelta, d as MarketEventEnvelope, e as NotificationCode, f as NotificationEventEnvelope, g as PositionEventEnvelope, m as marketEventTypes, n as notificationCodes, p as positionEventTypes } from '../types-BvZf3uFL.js';
3
+ import '../aliases-lNsFUKPA.js';
4
4
 
5
5
  interface PositionSocketOptions {
6
6
  baseUrl?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dimes-dot-fi/sdk",
3
- "version": "2.3.0",
3
+ "version": "2.5.0",
4
4
  "description": "TypeScript SDK for the Dimes prediction market API",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/dimes-fi/dimes-sdk#readme",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/parse.ts","../src/utils/format.ts","../src/errors/error-messages.ts","../src/errors/dimes-error.ts"],"sourcesContent":["export type Params = Record<string, unknown> | null;\n\nexport function asNumber(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n return null;\n}\n\nexport function asBigInt(value: unknown): bigint | null {\n if (typeof value === \"bigint\") {\n return value;\n }\n if (typeof value === \"string\" && /^-?\\d+$/.test(value.trim())) {\n return BigInt(value.trim());\n }\n if (typeof value === \"number\" && Number.isInteger(value)) {\n return BigInt(value);\n }\n return null;\n}\n\nexport function getParam(params: Params, key: string): unknown {\n return params ? params[key] : undefined;\n}\n","import { asNumber, asBigInt } from \"./parse\";\n\nconst BPS_PER_UNIT = 10_000;\nconst BPS_PER_PCT = 100;\nconst FRACTION_TO_PCT = 100;\nconst PIPS_PER_USD = 1_000_000n;\nconst ROUNDING_OFFSET = 5_000n;\nconst CENTS_DIVISOR = 10_000n;\nconst CENTS_PAD = 2;\n\nexport function formatLeverage(value: unknown): string | null {\n const n = asNumber(value);\n if (n === null) {\n return null;\n }\n return `${(n / BPS_PER_UNIT).toLocaleString(undefined, { maximumFractionDigits: 2 })}x`;\n}\n\nexport function formatBpsPct(value: unknown): string | null {\n const n = asNumber(value);\n if (n === null) {\n return null;\n }\n return `${(n / BPS_PER_PCT).toLocaleString(undefined, { maximumFractionDigits: 2 })}%`;\n}\n\nexport function formatFractionPct(value: unknown): string | null {\n const n = asNumber(value);\n if (n === null) {\n return null;\n }\n return `${(n * FRACTION_TO_PCT).toLocaleString(undefined, { maximumFractionDigits: 1 })}%`;\n}\n\nexport function formatPipsUsd(value: unknown): string | null {\n const big = asBigInt(value);\n if (big === null) {\n return null;\n }\n const negative = big < 0n;\n const absUnits = negative ? -big : big;\n const whole = absUnits / PIPS_PER_USD;\n const frac = absUnits % PIPS_PER_USD;\n const cents = (frac + ROUNDING_OFFSET) / CENTS_DIVISOR;\n const formatted = `$${whole.toLocaleString()}.${cents.toString().padStart(CENTS_PAD, \"0\")}`;\n return negative ? `-${formatted}` : formatted;\n}\n","import { formatLeverage, formatBpsPct, formatFractionPct, formatPipsUsd } from \"../utils/format\";\nimport { type Params, getParam } from \"../utils/parse\";\n\ntype FriendlyEntry = string | ((params: Params) => string);\n\nconst minFillBpsMaxForMessage = 5_000;\n\nconst friendlyByCode: Record<string, FriendlyEntry> = {\n invalid_evm_address: \"Invalid EVM address.\",\n invalid_solana_address: \"Invalid Solana address.\",\n invalid_string_for_chain_address: \"Invalid wallet address for the selected chain.\",\n invalid_wallet_address: \"Invalid wallet address.\",\n customer_auth_invalid_wallet_address: \"Invalid wallet address.\",\n\n unauthorized: \"Session expired. Please reconnect your wallet.\",\n forbidden: \"You do not have access to this resource.\",\n\n array_out_of_bounds: \"Internal indexing error. Please try again.\",\n batch_compute_not_available: \"Cached pricing is temporarily unavailable. Try again shortly.\",\n internal_server_error: \"Something went wrong on our side. Please try again.\",\n unexpected_error: \"Something went wrong. Please try again.\",\n provider_not_available: \"Upstream provider is unavailable. Try again shortly.\",\n request_already_in_progress: \"A previous request is still in flight. Wait for it to complete and try again.\",\n math_error: \"A numeric calculation failed. Please try again.\",\n invalid_number: \"Invalid numeric value in request.\",\n invalid_message: \"Received an invalid upstream message.\",\n invalid_filter_combination: \"That combination of filters is not supported.\",\n\n cancel_position_delay_not_elapsed: \"Cancel delay has not elapsed yet. Try again shortly.\",\n cancel_position_transaction_failed: \"Cancel transaction failed on-chain.\",\n cancel_position_not_found: \"Position not found.\",\n cancel_position_not_in_created_state: \"This position can only be cancelled before it has filled.\",\n cancel_position_not_on_polygon: \"Cancel is only supported for Polygon positions.\",\n customer_cancel_position_evm_only: \"Cancel is only supported for EVM positions.\",\n customer_cancel_position_not_cancellable: \"This position can no longer be cancelled.\",\n customer_cancel_position_not_owner: \"You do not own this position.\",\n customer_cancel_position_not_found: \"Position not found.\",\n\n circuit_breaker_price_divergence_tripped: \"Trading is temporarily paused due to price divergence. Try again shortly.\",\n\n customer_market_not_found: \"Market not found.\",\n customer_position_not_found: \"Position not found.\",\n customer_position_transactions_not_found: \"Position not found.\",\n\n close_position_transaction_failed: \"Close transaction failed on-chain.\",\n close_position_transaction_not_found: \"Close transaction not found.\",\n finalize_close_transaction_failed: \"Finalising the close transaction failed.\",\n close_no_open_position_transaction: \"No open transaction found for this position.\",\n close_no_request_close_transaction: \"No close request found for this position.\",\n close_polymarket_order_failed: \"Polymarket close order failed.\",\n close_polymarket_order_retry_failed: \"Polymarket close order failed after retries.\",\n close_position_already_closed: \"This position is already closed.\",\n close_position_has_no_tokens: \"This position has no tokens to close.\",\n close_position_not_found: \"Position not found.\",\n close_position_not_originated: \"Position has not been originated yet — nothing to close.\",\n\n exchange_order_submission_locked: \"Order submission is temporarily locked. Try again shortly.\",\n\n quote_partner_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `Partner position limit reached. Remaining capacity: ${available}.`\n : \"Partner position limit reached. Try a smaller size.\";\n },\n quote_user_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `You have reached your position limit on this market. Remaining capacity: ${available}.`\n : \"You have reached your position limit on this market.\";\n },\n quote_market_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `This market has reached its open-interest cap. Remaining capacity: ${available}.`\n : \"This market has reached its open-interest cap. Try a smaller size or another market.\";\n },\n quote_global_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `Global position limit reached. Remaining capacity: ${available}.`\n : \"Global position limit reached. Try again shortly.\";\n },\n quote_side_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `This side of the market is at its position limit. Remaining capacity: ${available}.`\n : \"This side of the market is at its position limit. Try the other side or a smaller size.\";\n },\n quote_side_capacity_exceeded: (params) => {\n const maxCollateral = formatPipsUsd(getParam(params, \"maxSupportedCollateralUsdPips\"));\n return maxCollateral\n ? `Not enough capacity on this side of the market. Max supported collateral at this size: ${maxCollateral}.`\n : \"Not enough capacity on this side of the market for that size.\";\n },\n quote_position_limit_exceeded: \"Position limit reached for this request.\",\n\n quote_insufficient_liquidity: \"Not enough liquidity on the order book to fill this size.\",\n quote_slippage_too_high: (params) => {\n const max = formatBpsPct(getParam(params, \"maxSlippageBps\"));\n const current = formatBpsPct(getParam(params, \"currentSlippageBps\"));\n if (max && current) {\n return `Required slippage ${current} exceeds your tolerance (${max}). Reduce size or raise tolerance.`;\n }\n if (max) {\n return `Required slippage exceeds your tolerance (${max}). Reduce size or raise tolerance.`;\n }\n return \"Price would move too far to fill this order. Reduce size or raise your slippage tolerance.\";\n },\n quote_event_not_started: \"This event has not started yet. Trading opens at the scheduled start time.\",\n quote_entry_bid_depth_too_low: \"Order book depth on the entry side is too thin to open this position safely.\",\n quote_entry_capacity_exceeded: \"Entry size exceeds the market's available capacity.\",\n quote_entry_depth_too_low: \"Order book depth is too thin to open this position safely.\",\n quote_entry_spread_too_wide: \"Bid/ask spread is too wide to open right now. Try again shortly.\",\n quote_entry_order_book_stale: \"Order book data is stale. Refresh and try again.\",\n quote_entry_price_stale: \"Price data is stale. Refresh and try again.\",\n quote_entry_crypto_price_stale: \"Crypto price data is stale. Refresh and try again.\",\n quote_entry_sport_data_stale: \"Sport event data is stale. Refresh and try again.\",\n quote_entry_volume_too_low: \"Recent traded volume on this market is too low to open new positions.\",\n quote_entry_top_holder_too_high: \"A single trader holds too much of this market. Opening here is restricted.\",\n quote_entry_price_out_of_range: \"Current price is outside the range we can open at. Try again shortly.\",\n quote_entry_exit_drop_too_high: \"Exit liquidity is too thin to safely open this size.\",\n quote_entry_market_too_elapsed: (params) => {\n const elapsed = formatFractionPct(getParam(params, \"pctElapsed\"));\n const max = formatFractionPct(getParam(params, \"maxPctElapsed\"));\n if (elapsed && max) {\n return `Market is ${elapsed} elapsed (max ${max}). Too close to resolution to open new positions.`;\n }\n return \"Market is too close to resolution to open new positions.\";\n },\n quote_entry_excluded_market_type: \"This market type is not supported for leveraged positions.\",\n quote_entry_excluded_sport: \"This sport is not supported for leveraged positions.\",\n quote_price_too_low: \"Underlying price is too low to open a leveraged position.\",\n quote_open_interest_unavailable: \"Open-interest data is unavailable right now. Try again shortly.\",\n\n quote_leverage_below_minimum: (params) => {\n const min = formatLeverage(getParam(params, \"minLeverageBps\"));\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n if (min && current) {\n return `Leverage ${current} is below the minimum allowed (${min}).`;\n }\n if (min) {\n return `Leverage is below the minimum allowed (${min}).`;\n }\n return \"Leverage is below the minimum allowed for this market.\";\n },\n quote_leverage_exceeds_maximum: (params) => {\n const max = formatLeverage(getParam(params, \"maxLeverageBps\"));\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n if (max && current) {\n return `Leverage ${current} is above the maximum allowed (${max}).`;\n }\n if (max) {\n return `Leverage is above the maximum allowed (${max}).`;\n }\n return \"Leverage is above the maximum allowed for this market.\";\n },\n quote_leverage_exceeds_collateral_floor: (params) => {\n const min = formatPipsUsd(getParam(params, \"minCollateralUsdPips\"));\n const current = formatPipsUsd(getParam(params, \"currentCollateralUsdPips\"));\n if (min && current) {\n return `Collateral ${current} is below the minimum ${min} required at this leverage. Raise collateral to at least ${min}.`;\n }\n if (min) {\n return `Collateral is below the minimum ${min} required at this leverage. Raise collateral to at least ${min}.`;\n }\n return \"Collateral is below the minimum required at this leverage. Raise collateral.\";\n },\n quote_leverage_exceeds_model_max: (params) => {\n const max = formatLeverage(getParam(params, \"maxLeverageBps\"));\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n if (max && current) {\n return `Leverage ${current} exceeds the risk-model limit (${max}) for this market.`;\n }\n if (max) {\n return `Leverage exceeds the risk-model limit (${max}) for this market.`;\n }\n return \"Leverage exceeds the risk-model limit for this market.\";\n },\n quote_leverage_too_high_for_price: (params) => {\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n const max = formatLeverage(getParam(params, \"maxAcceptableLeverageBps\"));\n if (current && max) {\n return `Leverage ${current} is too high for the current price. Maximum is ${max}.`;\n }\n if (current) {\n return `Leverage ${current} is too high for the current price. Reduce leverage.`;\n }\n return \"Leverage is too high for the current price. Reduce leverage.\";\n },\n quote_trading_window_closing: \"Trading window is closing. Reduce leverage.\",\n quote_hard_exit_too_close: \"Trading window is closing. Reduce leverage.\",\n quote_liquidation_not_viable: (params) => {\n const tolerance = formatBpsPct(getParam(params, \"minTolerancePctBps\"));\n return tolerance\n ? `Liquidation price is too close to entry (minimum buffer ${tolerance}). Reduce leverage.`\n : \"Liquidation price is not viable at this leverage. Reduce leverage.\";\n },\n\n quote_min_fill_bps_requires_fak: \"Partial-fill request was malformed. Please re-quote.\",\n quote_min_fill_bps_out_of_range: \"Minimum fill must be between 20% and 50%.\",\n quote_min_fill_bps_step_invalid: \"Minimum fill must be set in 5% steps.\",\n quote_min_fill_bps_below_floor: (params) => {\n const floorRaw = getParam(params, \"floorMinFillBps\");\n const floorPct = formatBpsPct(floorRaw);\n const limit = getParam(params, \"boundBy\") === \"notional\" ? \"minimum order size\" : \"minimum collateral\";\n const floorBeyondMax = typeof floorRaw === \"number\" && floorRaw > minFillBpsMaxForMessage;\n if (floorBeyondMax || !floorPct) {\n return `This trade is too small for a partial fill without falling below the ${limit}. Increase your trade size, or turn off partial fill to open atomically.`;\n }\n return `This trade is too small for that minimum fill — a partial fill could fall below the ${limit}. Raise the minimum fill to at least ${floorPct}, or increase your trade size.`;\n },\n quote_fak_order_type_disabled: \"Partial fills are temporarily unavailable. Turn off partial fill to continue.\",\n\n quote_market_not_active: \"Market is not active.\",\n quote_market_not_eligible: \"Market is not eligible for leveraged trading.\",\n quote_market_not_ready: \"Market is not ready yet. Try again shortly.\",\n quote_market_not_found: \"Market not found.\",\n quote_market_risk_too_high: \"Market risk is too high right now. Try again later.\",\n quote_market_unsupported_category: \"This market category is not supported.\",\n quote_market_no_prices: \"No price data available for this market.\",\n quote_market_missing_polymarket_condition_id: \"This market is missing required Polymarket data.\",\n\n quote_polymarket_market_closed: \"This Polymarket market is closed and not accepting new positions.\",\n quote_polymarket_market_inactive: \"This Polymarket market is inactive and not accepting new positions.\",\n quote_polymarket_market_not_accepting_orders:\n \"Polymarket is not accepting orders on this market right now. Try again shortly or pick another market.\",\n quote_polymarket_missing_token: \"This Polymarket market is missing a tradable outcome token.\",\n quote_invalid_polymarket_wallet_address: \"Invalid Polymarket wallet address.\",\n quote_invalid_kalshi_wallet_address: \"Invalid Kalshi wallet address.\",\n\n kalshi_quote_market_closed: \"This Kalshi market is closed.\",\n\n quote_draft_not_found: \"This quote has expired or does not exist. Please request a new quote.\",\n\n quote_twap_data_stale: \"Reference price (TWAP) is stale. Try again shortly.\",\n quote_twap_data_unavailable: \"Reference price (TWAP) is unavailable for this market.\",\n quote_revision_required: \"Quote needs to be refreshed before submitting.\",\n quote_price_provider_not_found: \"No price provider configured for this market.\",\n\n notional_selector_insufficient_liquidity: \"Not enough liquidity to fill an order of this size. Try a smaller size.\",\n notional_selector_below_min_notional:\n \"This side of the market doesn't have enough liquidity to support the minimum position size right now.\",\n notional_selector_empty_order_book:\n \"This side of the market has no available liquidity right now. Try again shortly.\",\n notional_selector_pregame_insufficient_liquidity:\n \"This market doesn't yet have enough pre-game liquidity to support a position. \" +\n \"Try again closer to the event start.\",\n\n evm_gas_price_circuit_breaker: \"EVM gas price is too high — trading is temporarily paused.\",\n evm_gas_price_spike: \"EVM gas price spiked. Try again shortly.\",\n evm_simulation_failed: \"Transaction simulation failed. The transaction would revert on-chain.\",\n evm_receipt_timeout: \"Transaction confirmation timed out. Check status before retrying.\",\n evm_transaction_failed: \"EVM transaction failed.\",\n\n position_transition_conflicting_operation: \"Another operation on this position is in progress. Try again shortly.\",\n position_transition_invalid_state: \"Position is not in a state that allows this action.\",\n\n quote_creation_disabled: \"Quote creation is temporarily disabled. Try again shortly.\",\n};\n\nfunction humanizeCode(code: string): string {\n const spaced = code.replace(/_/g, \" \");\n return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n}\n\nexport function resolveFriendlyMessage(code: string, params: Params): string | null {\n const entry = friendlyByCode[code];\n if (entry === undefined) {\n return null;\n }\n return typeof entry === \"function\" ? entry(params) : entry;\n}\n\nexport function formatErrorMessage(code: string, params: Params): string {\n return resolveFriendlyMessage(code, params) ?? humanizeCode(code);\n}\n","import type { QuoteHint } from \"../quote/quote-error-hints\";\nimport { resolveFriendlyMessage } from \"./error-messages\";\n\nexport class DimesError extends Error {\n public readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = \"DimesError\";\n this.code = code;\n }\n}\n\nexport class DimesApiError extends DimesError {\n public readonly status: number;\n\n public readonly type: string | null;\n\n public readonly rawMessage: string;\n\n public readonly params: Record<string, unknown> | null;\n\n public readonly hint: QuoteHint | null;\n\n constructor(options: {\n status: number;\n code: string;\n type: string | null;\n message: string;\n params: Record<string, unknown> | null;\n hint?: QuoteHint | null;\n }) {\n const friendly = resolveFriendlyMessage(options.code, options.params) ?? options.message;\n super(options.code, friendly);\n this.name = \"DimesApiError\";\n this.status = options.status;\n this.type = options.type;\n this.rawMessage = options.message;\n this.params = options.params;\n this.hint = options.hint ?? null;\n }\n}\n\nexport class DimesContractError extends DimesError {\n constructor(code: string, message: string) {\n super(code, message);\n this.name = \"DimesContractError\";\n }\n}\n"],"mappings":";AAEO,SAAS,SAAS,OAA+B;AACtD,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GAAG;AACvD,WAAO;AAAA,EACT;AACA,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,IAAI;AACpD,UAAM,SAAS,OAAO,KAAK;AAC3B,QAAI,OAAO,SAAS,MAAM,GAAG;AAC3B,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,SAAS,OAA+B;AACtD,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO;AAAA,EACT;AACA,MAAI,OAAO,UAAU,YAAY,UAAU,KAAK,MAAM,KAAK,CAAC,GAAG;AAC7D,WAAO,OAAO,MAAM,KAAK,CAAC;AAAA,EAC5B;AACA,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,GAAG;AACxD,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO;AACT;AAEO,SAAS,SAAS,QAAgB,KAAsB;AAC7D,SAAO,SAAS,OAAO,GAAG,IAAI;AAChC;;;AC5BA,IAAM,eAAe;AACrB,IAAM,cAAc;AACpB,IAAM,kBAAkB;AACxB,IAAM,eAAe;AACrB,IAAM,kBAAkB;AACxB,IAAM,gBAAgB;AACtB,IAAM,YAAY;AAEX,SAAS,eAAe,OAA+B;AAC5D,QAAM,IAAI,SAAS,KAAK;AACxB,MAAI,MAAM,MAAM;AACd,WAAO;AAAA,EACT;AACA,SAAO,IAAI,IAAI,cAAc,eAAe,QAAW,EAAE,uBAAuB,EAAE,CAAC,CAAC;AACtF;AAEO,SAAS,aAAa,OAA+B;AAC1D,QAAM,IAAI,SAAS,KAAK;AACxB,MAAI,MAAM,MAAM;AACd,WAAO;AAAA,EACT;AACA,SAAO,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,QAA+B;AAClF,QAAM,QAAQ,eAAe,IAAI;AACjC,MAAI,UAAU,QAAW;AACvB,WAAO;AAAA,EACT;AACA,SAAO,OAAO,UAAU,aAAa,MAAM,MAAM,IAAI;AACvD;AAEO,SAAS,mBAAmB,MAAc,QAAwB;AACvE,SAAO,uBAAuB,MAAM,MAAM,KAAK,aAAa,IAAI;AAClE;;;AChRO,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpB;AAAA,EAEhB,YAAY,MAAc,SAAiB;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,gBAAN,cAA4B,WAAW;AAAA,EAC5B;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEhB,YAAY,SAOT;AACD,UAAM,WAAW,uBAAuB,QAAQ,MAAM,QAAQ,MAAM,KAAK,QAAQ;AACjF,UAAM,QAAQ,MAAM,QAAQ;AAC5B,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ;AACpB,SAAK,aAAa,QAAQ;AAC1B,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ,QAAQ;AAAA,EAC9B;AACF;AAEO,IAAM,qBAAN,cAAiC,WAAW;AAAA,EACjD,YAAY,MAAc,SAAiB;AACzC,UAAM,MAAM,OAAO;AACnB,SAAK,OAAO;AAAA,EACd;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/Users/alexemery/bl/dimes-sdk/dist/chunk-E6YJDY4F.cjs","../src/utils/parse.ts","../src/utils/format.ts","../src/errors/error-messages.ts","../src/errors/dimes-error.ts"],"names":[],"mappings":"AAAA;ACEO,SAAS,QAAA,CAAS,KAAA,EAA+B;AACtD,EAAA,GAAA,CAAI,OAAO,MAAA,IAAU,SAAA,GAAY,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,EAAG;AACvD,IAAA,OAAO,KAAA;AAAA,EACT;AACA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AA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AAEA,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AAEA,EAAA;AAIA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACF;AAES;AACD,EAAA;AACC,EAAA;AACT;AAEgB;AACR,EAAA;AACF,EAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAEgB;AACP,EAAA;AACT;AH0BU;AACA;AI3SG;AACK,EAAA;AAEhB,EAAA;AACQ,IAAA;AACD,IAAA;AACA,IAAA;AACP,EAAA;AACF;AAEa;AACK,EAAA;AAEA,EAAA;AAEA,EAAA;AAEA,EAAA;AAEA,EAAA;AAEhB,EAAA;AAQQ,IAAA;AACA,IAAA;AACD,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACP,EAAA;AACF;AAEa;AACX,EAAA;AACQ,IAAA;AACD,IAAA;AACP,EAAA;AACF;AJ8RU;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/alexemery/bl/dimes-sdk/dist/chunk-E6YJDY4F.cjs","sourcesContent":[null,"export type Params = Record<string, unknown> | null;\n\nexport function asNumber(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n return null;\n}\n\nexport function asBigInt(value: unknown): bigint | null {\n if (typeof value === \"bigint\") {\n return value;\n }\n if (typeof value === \"string\" && /^-?\\d+$/.test(value.trim())) {\n return BigInt(value.trim());\n }\n if (typeof value === \"number\" && Number.isInteger(value)) {\n return BigInt(value);\n }\n return null;\n}\n\nexport function getParam(params: Params, key: string): unknown {\n return params ? params[key] : undefined;\n}\n","import { asNumber, asBigInt } from \"./parse\";\n\nconst BPS_PER_UNIT = 10_000;\nconst BPS_PER_PCT = 100;\nconst FRACTION_TO_PCT = 100;\nconst PIPS_PER_USD = 1_000_000n;\nconst ROUNDING_OFFSET = 5_000n;\nconst CENTS_DIVISOR = 10_000n;\nconst CENTS_PAD = 2;\n\nexport function formatLeverage(value: unknown): string | null {\n const n = asNumber(value);\n if (n === null) {\n return null;\n }\n return `${(n / BPS_PER_UNIT).toLocaleString(undefined, { maximumFractionDigits: 2 })}x`;\n}\n\nexport function formatBpsPct(value: unknown): string | null {\n const n = asNumber(value);\n if (n === null) {\n return null;\n }\n return `${(n / BPS_PER_PCT).toLocaleString(undefined, { maximumFractionDigits: 2 })}%`;\n}\n\nexport function formatFractionPct(value: unknown): string | null {\n const n = asNumber(value);\n if (n === null) {\n return null;\n }\n return `${(n * FRACTION_TO_PCT).toLocaleString(undefined, { maximumFractionDigits: 1 })}%`;\n}\n\nexport function formatPipsUsd(value: unknown): string | null {\n const big = asBigInt(value);\n if (big === null) {\n return null;\n }\n const negative = big < 0n;\n const absUnits = negative ? -big : big;\n const whole = absUnits / PIPS_PER_USD;\n const frac = absUnits % PIPS_PER_USD;\n const cents = (frac + ROUNDING_OFFSET) / CENTS_DIVISOR;\n const formatted = `$${whole.toLocaleString()}.${cents.toString().padStart(CENTS_PAD, \"0\")}`;\n return negative ? `-${formatted}` : formatted;\n}\n","import { formatLeverage, formatBpsPct, formatFractionPct, formatPipsUsd } from \"../utils/format\";\nimport { type Params, getParam } from \"../utils/parse\";\n\ntype FriendlyEntry = string | ((params: Params) => string);\n\nconst minFillBpsMaxForMessage = 5_000;\n\nconst friendlyByCode: Record<string, FriendlyEntry> = {\n invalid_evm_address: \"Invalid EVM address.\",\n invalid_solana_address: \"Invalid Solana address.\",\n invalid_string_for_chain_address: \"Invalid wallet address for the selected chain.\",\n invalid_wallet_address: \"Invalid wallet address.\",\n customer_auth_invalid_wallet_address: \"Invalid wallet address.\",\n\n unauthorized: \"Session expired. Please reconnect your wallet.\",\n forbidden: \"You do not have access to this resource.\",\n\n array_out_of_bounds: \"Internal indexing error. Please try again.\",\n batch_compute_not_available: \"Cached pricing is temporarily unavailable. Try again shortly.\",\n internal_server_error: \"Something went wrong on our side. Please try again.\",\n unexpected_error: \"Something went wrong. Please try again.\",\n provider_not_available: \"Upstream provider is unavailable. Try again shortly.\",\n request_already_in_progress: \"A previous request is still in flight. Wait for it to complete and try again.\",\n math_error: \"A numeric calculation failed. Please try again.\",\n invalid_number: \"Invalid numeric value in request.\",\n invalid_message: \"Received an invalid upstream message.\",\n invalid_filter_combination: \"That combination of filters is not supported.\",\n\n cancel_position_delay_not_elapsed: \"Cancel delay has not elapsed yet. Try again shortly.\",\n cancel_position_transaction_failed: \"Cancel transaction failed on-chain.\",\n cancel_position_not_found: \"Position not found.\",\n cancel_position_not_in_created_state: \"This position can only be cancelled before it has filled.\",\n cancel_position_not_on_polygon: \"Cancel is only supported for Polygon positions.\",\n customer_cancel_position_evm_only: \"Cancel is only supported for EVM positions.\",\n customer_cancel_position_not_cancellable: \"This position can no longer be cancelled.\",\n customer_cancel_position_not_owner: \"You do not own this position.\",\n customer_cancel_position_not_found: \"Position not found.\",\n\n circuit_breaker_price_divergence_tripped: \"Trading is temporarily paused due to price divergence. Try again shortly.\",\n\n customer_market_not_found: \"Market not found.\",\n customer_position_not_found: \"Position not found.\",\n customer_position_transactions_not_found: \"Position not found.\",\n\n close_position_transaction_failed: \"Close transaction failed on-chain.\",\n close_position_transaction_not_found: \"Close transaction not found.\",\n finalize_close_transaction_failed: \"Finalising the close transaction failed.\",\n close_no_open_position_transaction: \"No open transaction found for this position.\",\n close_no_request_close_transaction: \"No close request found for this position.\",\n close_polymarket_order_failed: \"Polymarket close order failed.\",\n close_polymarket_order_retry_failed: \"Polymarket close order failed after retries.\",\n close_position_already_closed: \"This position is already closed.\",\n close_position_has_no_tokens: \"This position has no tokens to close.\",\n close_position_not_found: \"Position not found.\",\n close_position_not_originated: \"Position has not been originated yet — nothing to close.\",\n\n exchange_order_submission_locked: \"Order submission is temporarily locked. Try again shortly.\",\n\n quote_partner_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `Partner position limit reached. Remaining capacity: ${available}.`\n : \"Partner position limit reached. Try a smaller size.\";\n },\n quote_user_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `You have reached your position limit on this market. Remaining capacity: ${available}.`\n : \"You have reached your position limit on this market.\";\n },\n quote_market_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `This market has reached its open-interest cap. Remaining capacity: ${available}.`\n : \"This market has reached its open-interest cap. Try a smaller size or another market.\";\n },\n quote_global_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `Global position limit reached. Remaining capacity: ${available}.`\n : \"Global position limit reached. Try again shortly.\";\n },\n quote_side_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `This side of the market is at its position limit. Remaining capacity: ${available}.`\n : \"This side of the market is at its position limit. Try the other side or a smaller size.\";\n },\n quote_side_capacity_exceeded: (params) => {\n const maxCollateral = formatPipsUsd(getParam(params, \"maxSupportedCollateralUsdPips\"));\n return maxCollateral\n ? `Not enough capacity on this side of the market. Max supported collateral at this size: ${maxCollateral}.`\n : \"Not enough capacity on this side of the market for that size.\";\n },\n quote_position_limit_exceeded: \"Position limit reached for this request.\",\n\n quote_insufficient_liquidity: \"Not enough liquidity on the order book to fill this size.\",\n quote_slippage_too_high: (params) => {\n const max = formatBpsPct(getParam(params, \"maxSlippageBps\"));\n const current = formatBpsPct(getParam(params, \"currentSlippageBps\"));\n if (max && current) {\n return `Required slippage ${current} exceeds your tolerance (${max}). Reduce size or raise tolerance.`;\n }\n if (max) {\n return `Required slippage exceeds your tolerance (${max}). Reduce size or raise tolerance.`;\n }\n return \"Price would move too far to fill this order. Reduce size or raise your slippage tolerance.\";\n },\n quote_event_not_started: \"This event has not started yet. Trading opens at the scheduled start time.\",\n quote_entry_bid_depth_too_low: \"Order book depth on the entry side is too thin to open this position safely.\",\n quote_entry_capacity_exceeded: \"Entry size exceeds the market's available capacity.\",\n quote_entry_depth_too_low: \"Order book depth is too thin to open this position safely.\",\n quote_entry_spread_too_wide: \"Bid/ask spread is too wide to open right now. Try again shortly.\",\n quote_entry_order_book_stale: \"Order book data is stale. Refresh and try again.\",\n quote_entry_price_stale: \"Price data is stale. Refresh and try again.\",\n quote_entry_crypto_price_stale: \"Crypto price data is stale. Refresh and try again.\",\n quote_entry_sport_data_stale: \"Sport event data is stale. Refresh and try again.\",\n quote_entry_volume_too_low: \"Recent traded volume on this market is too low to open new positions.\",\n quote_entry_top_holder_too_high: \"A single trader holds too much of this market. Opening here is restricted.\",\n quote_entry_price_out_of_range: \"Current price is outside the range we can open at. Try again shortly.\",\n quote_entry_exit_drop_too_high: \"Exit liquidity is too thin to safely open this size.\",\n quote_entry_market_too_elapsed: (params) => {\n const elapsed = formatFractionPct(getParam(params, \"pctElapsed\"));\n const max = formatFractionPct(getParam(params, \"maxPctElapsed\"));\n if (elapsed && max) {\n return `Market is ${elapsed} elapsed (max ${max}). Too close to resolution to open new positions.`;\n }\n return \"Market is too close to resolution to open new positions.\";\n },\n quote_entry_excluded_market_type: \"This market type is not supported for leveraged positions.\",\n quote_entry_excluded_sport: \"This sport is not supported for leveraged positions.\",\n quote_price_too_low: \"Underlying price is too low to open a leveraged position.\",\n quote_open_interest_unavailable: \"Open-interest data is unavailable right now. Try again shortly.\",\n\n quote_leverage_below_minimum: (params) => {\n const min = formatLeverage(getParam(params, \"minLeverageBps\"));\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n if (min && current) {\n return `Leverage ${current} is below the minimum allowed (${min}).`;\n }\n if (min) {\n return `Leverage is below the minimum allowed (${min}).`;\n }\n return \"Leverage is below the minimum allowed for this market.\";\n },\n quote_leverage_exceeds_maximum: (params) => {\n const max = formatLeverage(getParam(params, \"maxLeverageBps\"));\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n if (max && current) {\n return `Leverage ${current} is above the maximum allowed (${max}).`;\n }\n if (max) {\n return `Leverage is above the maximum allowed (${max}).`;\n }\n return \"Leverage is above the maximum allowed for this market.\";\n },\n quote_leverage_exceeds_collateral_floor: (params) => {\n const min = formatPipsUsd(getParam(params, \"minCollateralUsdPips\"));\n const current = formatPipsUsd(getParam(params, \"currentCollateralUsdPips\"));\n if (min && current) {\n return `Collateral ${current} is below the minimum ${min} required at this leverage. Raise collateral to at least ${min}.`;\n }\n if (min) {\n return `Collateral is below the minimum ${min} required at this leverage. Raise collateral to at least ${min}.`;\n }\n return \"Collateral is below the minimum required at this leverage. Raise collateral.\";\n },\n quote_leverage_exceeds_model_max: (params) => {\n const max = formatLeverage(getParam(params, \"maxLeverageBps\"));\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n if (max && current) {\n return `Leverage ${current} exceeds the risk-model limit (${max}) for this market.`;\n }\n if (max) {\n return `Leverage exceeds the risk-model limit (${max}) for this market.`;\n }\n return \"Leverage exceeds the risk-model limit for this market.\";\n },\n quote_leverage_too_high_for_price: (params) => {\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n const max = formatLeverage(getParam(params, \"maxAcceptableLeverageBps\"));\n if (current && max) {\n return `Leverage ${current} is too high for the current price. Maximum is ${max}.`;\n }\n if (current) {\n return `Leverage ${current} is too high for the current price. Reduce leverage.`;\n }\n return \"Leverage is too high for the current price. Reduce leverage.\";\n },\n quote_trading_window_closing: \"Trading window is closing. Reduce leverage.\",\n quote_hard_exit_too_close: \"Trading window is closing. Reduce leverage.\",\n quote_liquidation_not_viable: (params) => {\n const tolerance = formatBpsPct(getParam(params, \"minTolerancePctBps\"));\n return tolerance\n ? `Liquidation price is too close to entry (minimum buffer ${tolerance}). Reduce leverage.`\n : \"Liquidation price is not viable at this leverage. Reduce leverage.\";\n },\n\n quote_min_fill_bps_requires_fak: \"Partial-fill request was malformed. Please re-quote.\",\n quote_min_fill_bps_out_of_range: \"Minimum fill must be between 20% and 50%.\",\n quote_min_fill_bps_step_invalid: \"Minimum fill must be set in 5% steps.\",\n quote_min_fill_bps_below_floor: (params) => {\n const floorRaw = getParam(params, \"floorMinFillBps\");\n const floorPct = formatBpsPct(floorRaw);\n const limit = getParam(params, \"boundBy\") === \"notional\" ? \"minimum order size\" : \"minimum collateral\";\n const floorBeyondMax = typeof floorRaw === \"number\" && floorRaw > minFillBpsMaxForMessage;\n if (floorBeyondMax || !floorPct) {\n return `This trade is too small for a partial fill without falling below the ${limit}. Increase your trade size, or turn off partial fill to open atomically.`;\n }\n return `This trade is too small for that minimum fill — a partial fill could fall below the ${limit}. Raise the minimum fill to at least ${floorPct}, or increase your trade size.`;\n },\n quote_fak_order_type_disabled: \"Partial fills are temporarily unavailable. Turn off partial fill to continue.\",\n\n quote_market_not_active: \"Market is not active.\",\n quote_market_not_eligible: \"Market is not eligible for leveraged trading.\",\n quote_market_not_ready: \"Market is not ready yet. Try again shortly.\",\n quote_market_not_found: \"Market not found.\",\n quote_market_risk_too_high: \"Market risk is too high right now. Try again later.\",\n quote_market_unsupported_category: \"This market category is not supported.\",\n quote_market_no_prices: \"No price data available for this market.\",\n quote_market_missing_polymarket_condition_id: \"This market is missing required Polymarket data.\",\n\n quote_polymarket_market_closed: \"This Polymarket market is closed and not accepting new positions.\",\n quote_polymarket_market_inactive: \"This Polymarket market is inactive and not accepting new positions.\",\n quote_polymarket_market_not_accepting_orders:\n \"Polymarket is not accepting orders on this market right now. Try again shortly or pick another market.\",\n quote_polymarket_missing_token: \"This Polymarket market is missing a tradable outcome token.\",\n quote_invalid_polymarket_wallet_address: \"Invalid Polymarket wallet address.\",\n quote_invalid_kalshi_wallet_address: \"Invalid Kalshi wallet address.\",\n\n kalshi_quote_market_closed: \"This Kalshi market is closed.\",\n\n quote_draft_not_found: \"This quote has expired or does not exist. Please request a new quote.\",\n\n quote_twap_data_stale: \"Reference price (TWAP) is stale. Try again shortly.\",\n quote_twap_data_unavailable: \"Reference price (TWAP) is unavailable for this market.\",\n quote_revision_required: \"Quote needs to be refreshed before submitting.\",\n quote_price_provider_not_found: \"No price provider configured for this market.\",\n\n notional_selector_insufficient_liquidity: \"Not enough liquidity to fill an order of this size. Try a smaller size.\",\n notional_selector_below_min_notional:\n \"This side of the market doesn't have enough liquidity to support the minimum position size right now.\",\n notional_selector_empty_order_book:\n \"This side of the market has no available liquidity right now. Try again shortly.\",\n notional_selector_pregame_insufficient_liquidity:\n \"This market doesn't yet have enough pre-game liquidity to support a position. \" +\n \"Try again closer to the event start.\",\n\n evm_gas_price_circuit_breaker: \"EVM gas price is too high — trading is temporarily paused.\",\n evm_gas_price_spike: \"EVM gas price spiked. Try again shortly.\",\n evm_simulation_failed: \"Transaction simulation failed. The transaction would revert on-chain.\",\n evm_receipt_timeout: \"Transaction confirmation timed out. Check status before retrying.\",\n evm_transaction_failed: \"EVM transaction failed.\",\n\n position_transition_conflicting_operation: \"Another operation on this position is in progress. Try again shortly.\",\n position_transition_invalid_state: \"Position is not in a state that allows this action.\",\n\n quote_creation_disabled: \"Quote creation is temporarily disabled. Try again shortly.\",\n};\n\nfunction humanizeCode(code: string): string {\n const spaced = code.replace(/_/g, \" \");\n return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n}\n\nexport function resolveFriendlyMessage(code: string, params: Params): string | null {\n const entry = friendlyByCode[code];\n if (entry === undefined) {\n return null;\n }\n return typeof entry === \"function\" ? entry(params) : entry;\n}\n\nexport function formatErrorMessage(code: string, params: Params): string {\n return resolveFriendlyMessage(code, params) ?? humanizeCode(code);\n}\n","import type { QuoteHint } from \"../quote/quote-error-hints\";\nimport { resolveFriendlyMessage } from \"./error-messages\";\n\nexport class DimesError extends Error {\n public readonly code: string;\n\n constructor(code: string, message: string) {\n super(message);\n this.name = \"DimesError\";\n this.code = code;\n }\n}\n\nexport class DimesApiError extends DimesError {\n public readonly status: number;\n\n public readonly type: string | null;\n\n public readonly rawMessage: string;\n\n public readonly params: Record<string, unknown> | null;\n\n public readonly hint: QuoteHint | null;\n\n constructor(options: {\n status: number;\n code: string;\n type: string | null;\n message: string;\n params: Record<string, unknown> | null;\n hint?: QuoteHint | null;\n }) {\n const friendly = resolveFriendlyMessage(options.code, options.params) ?? options.message;\n super(options.code, friendly);\n this.name = \"DimesApiError\";\n this.status = options.status;\n this.type = options.type;\n this.rawMessage = options.message;\n this.params = options.params;\n this.hint = options.hint ?? null;\n }\n}\n\nexport class DimesContractError extends DimesError {\n constructor(code: string, message: string) {\n super(code, message);\n this.name = \"DimesContractError\";\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/Users/alexemery/bl/dimes-sdk/dist/chunk-GY6L2QGR.cjs","../src/quote/build-quote-params.ts","../src/quote/quote-error-hints.ts","../src/quote/quote.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACFA,IAAM,0BAAA,EAA4B,IAAA;AAE3B,SAAS,gBAAA,CAAiB,MAAA,EAAqB,QAAA,EAAkB,yBAAA,EAA8C;AACpH,EAAA,MAAM,YAAA,EAAc,IAAA,CAAK,KAAA,CAAM,MAAA,CAAO,YAAA,EAAc,OAAO,EAAA,EAAI,OAAA;AAC/D,EAAA,MAAM,gBAAA,EAAkB,IAAA,CAAK,KAAA,CAAM,MAAA,CAAO,cAAA,EAAgB,WAAW,CAAA;AAErE,EAAA,OAAO;AAAA,IACL,YAAA,EAAc,MAAA,CAAO,YAAA;AAAA,IACrB,aAAA,EAAe,MAAA,CAAO,IAAA;AAAA,IACtB,WAAA;AAAA,IACA,qBAAA,EAAuB,eAAA,CAAgB,QAAA,CAAS,CAAA;AAAA,IAChD,WAAA,EAAa,MAAA,CAAO,WA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AAA;AACA,UAAA;AACF,QAAA;AACF,MAAA;AAEA,MAAA;AACF,IAAA;AACF,EAAA;AAEM,EAAA;AACR;AHwLU;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/alexemery/bl/dimes-sdk/dist/chunk-GY6L2QGR.cjs","sourcesContent":[null,"import type { CreateQuoteParams } from \"../types\";\nimport type { QuoteParams } from \"../types/quote\";\n\nconst DEFAULT_LEVERAGE_STEP_BPS = 2500;\n\nexport function buildQuoteParams(params: QuoteParams, stepBps: number = DEFAULT_LEVERAGE_STEP_BPS): CreateQuoteParams {\n const leverageBps = Math.round(params.leverageBps / stepBps) * stepBps;\n const notionalUsdPips = Math.round(params.collateralUsd * leverageBps);\n\n return {\n marketTicker: params.marketTicker,\n effectiveSide: params.side,\n leverageBps,\n notionalAmountUsdPips: notionalUsdPips.toString(),\n slippageBps: params.slippageBps,\n ...(params.allowPartialFill !== undefined ? { allowPartialFill: params.allowPartialFill } : {}),\n ...(params.allowPartialFill && params.minFillBps !== undefined ? { minFillBps: params.minFillBps } : {}),\n };\n}\n","const pipsPerUsd = 10_000;\nconst bpsPerUnit = 10_000;\nconst bpsPerPct = 100;\nconst minFillBpsMax = 5_000;\nconst centsFactor = 100;\nconst decimalPlaces = 2;\n\nexport const marketMovedCodes = new Set([\n \"quote_slippage_too_high\",\n \"quote_insufficient_liquidity\",\n \"quote_entry_price_out_of_range\",\n \"quote_entry_bid_depth_too_low\",\n \"quote_entry_depth_too_low\",\n \"quote_entry_spread_too_wide\",\n]);\n\nexport type QuoteHint =\n | { kind: \"use-max-collateral\"; maxCollateralUsd: number; minCollateralUsd: number }\n | { kind: \"raise-collateral\"; minCollateralUsd: number }\n | { kind: \"clamp-leverage\"; maxLeverageBps?: number }\n | { kind: \"raise-leverage\"; minLeverageBps: number }\n | { kind: \"raise-slippage\"; currentSlippageBps: number; maxSlippageBps: number }\n | { kind: \"raise-min-fill\"; minFillBps: number }\n | { kind: \"market-full\" }\n | { kind: \"insufficient-liquidity\"; maxCollateralUsd: number; minCollateralUsd: number }\n | null;\n\ntype Params = Record<string, unknown> | null | undefined;\n\nfunction num(params: Params, key: string): number | null {\n if (!params) {\n return null;\n }\n const raw = params[key];\n if (raw === null || raw === undefined) {\n return null;\n }\n // eslint-disable-next-line no-restricted-syntax\n const n = typeof raw === \"string\" ? Number(raw) : typeof raw === \"number\" ? raw : NaN;\n return Number.isFinite(n) ? n : null;\n}\n\nfunction pipsToUsd(pips: number): number {\n return pips / pipsPerUsd;\n}\n\nfunction notionalPipsToCollateralUsd(notionalPips: number, leverageBps: number): number | null {\n if (!Number.isFinite(leverageBps) || leverageBps <= 0) {\n return null;\n }\n return (notionalPips * bpsPerUnit) / leverageBps / pipsPerUsd;\n}\n\nfunction buildExhaustedHint(\n exhaustedKind: \"market-full\" | \"insufficient-liquidity\",\n maxCollateralUsd: number,\n minCollateralUsd: number,\n): QuoteHint {\n if (exhaustedKind === \"insufficient-liquidity\") {\n return { kind: \"insufficient-liquidity\", maxCollateralUsd, minCollateralUsd };\n }\n return { kind: \"market-full\" };\n}\n\nfunction resolveMaxCollateralHint(\n params: Params,\n context: { leverageBps: number },\n capacityKey: string,\n exhaustedKind: \"market-full\" | \"insufficient-liquidity\",\n): QuoteHint {\n const serverMaxCollateralPips = num(params, \"maxSupportedCollateralUsdPips\");\n const capacityPips = num(params, capacityKey);\n const minNotionalPips = num(params, \"minNotionalUsdPips\");\n\n const fromServer = serverMaxCollateralPips !== null ? pipsToUsd(serverMaxCollateralPips) : null;\n const fromCapacity = capacityPips !== null ? notionalPipsToCollateralUsd(capacityPips, context.leverageBps) : null;\n const maxCollateralUsd =\n fromServer !== null && fromCapacity !== null ? Math.min(fromServer, fromCapacity) : (fromServer ?? fromCapacity);\n\n const minCollateralUsd =\n minNotionalPips !== null ? notionalPipsToCollateralUsd(minNotionalPips, context.leverageBps) : null;\n\n if (maxCollateralUsd === null || minCollateralUsd === null) {\n return null;\n }\n if (maxCollateralUsd < minCollateralUsd) {\n return buildExhaustedHint(exhaustedKind, maxCollateralUsd, minCollateralUsd);\n }\n return { kind: \"use-max-collateral\", maxCollateralUsd, minCollateralUsd };\n}\n\n// eslint-disable-next-line complexity\nexport function quoteErrorHint(code: string | null, params: Params, context: { leverageBps: number }): QuoteHint {\n if (!code) {\n return null;\n }\n\n switch (code) {\n case \"quote_side_capacity_exceeded\":\n case \"quote_user_position_limit_exceeded\":\n case \"quote_market_position_limit_exceeded\":\n case \"quote_side_position_limit_exceeded\":\n case \"quote_global_position_limit_exceeded\":\n case \"quote_partner_position_limit_exceeded\":\n return resolveMaxCollateralHint(params, context, \"availableCapacityUsdPips\", \"market-full\");\n\n case \"quote_insufficient_liquidity\":\n return resolveMaxCollateralHint(params, context, \"slippageMaxUsdPips\", \"market-full\");\n\n case \"notional_selector_insufficient_liquidity\":\n return resolveMaxCollateralHint(params, context, \"slippageMaxUsdPips\", \"insufficient-liquidity\");\n\n case \"quote_leverage_exceeds_collateral_floor\": {\n const minCollateralPips = num(params, \"minCollateralUsdPips\");\n if (minCollateralPips === null) {\n return null;\n }\n return { kind: \"raise-collateral\", minCollateralUsd: pipsToUsd(minCollateralPips) };\n }\n\n case \"quote_leverage_exceeds_maximum\":\n case \"quote_leverage_exceeds_model_max\": {\n const maxLeverageBps = num(params, \"maxLeverageBps\");\n if (maxLeverageBps === null) {\n return null;\n }\n return { kind: \"clamp-leverage\", maxLeverageBps };\n }\n\n case \"quote_leverage_too_high_for_price\": {\n const maxLeverageBps = num(params, \"maxAcceptableLeverageBps\");\n if (maxLeverageBps === null) {\n return null;\n }\n return { kind: \"clamp-leverage\", maxLeverageBps };\n }\n\n case \"quote_leverage_below_minimum\": {\n const minLeverageBps = num(params, \"minLeverageBps\");\n if (minLeverageBps === null) {\n return null;\n }\n return { kind: \"raise-leverage\", minLeverageBps };\n }\n\n case \"quote_min_fill_bps_below_floor\": {\n const floorMinFillBps = num(params, \"floorMinFillBps\");\n if (floorMinFillBps === null || floorMinFillBps > minFillBpsMax) {\n return null;\n }\n return { kind: \"raise-min-fill\", minFillBps: floorMinFillBps };\n }\n\n case \"quote_slippage_too_high\": {\n const currentSlippageBps = num(params, \"currentSlippageBps\");\n const maxSlippageBps = num(params, \"maxSlippageBps\");\n if (currentSlippageBps === null || maxSlippageBps === null) {\n return null;\n }\n return { kind: \"raise-slippage\", currentSlippageBps, maxSlippageBps };\n }\n\n default:\n return null;\n }\n}\n\nexport type CorrectedField = \"collateral\" | \"leverage\" | \"slippage\" | \"minFill\";\n\nexport type HintAdjustment =\n | {\n field: \"collateral\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"max-collateral\" | \"min-collateral\";\n }\n | {\n field: \"leverage\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"clamp-max\" | \"raise-min\";\n }\n | {\n field: \"slippage\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"raise-slippage\";\n }\n | {\n field: \"minFill\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"raise-min-fill\";\n }\n | null;\n\nfunction formatUsd(value: number): string {\n return new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n }).format(value);\n}\n\nfunction bpsToMultiplier(bps: number): string {\n return `${(bps / bpsPerUnit).toFixed(1).replace(/\\.0$/, \"\")}x`;\n}\n\n// eslint-disable-next-line complexity\nexport function hintAdjustment(\n hint: QuoteHint,\n current: { collateralUsd: number; leverageBps: number; slippageBps: number; minFillBps?: number },\n): HintAdjustment {\n if (!hint) {\n return null;\n }\n\n switch (hint.kind) {\n case \"use-max-collateral\": {\n const to = Math.max(0, Math.floor(hint.maxCollateralUsd * centsFactor) / centsFactor);\n if (to <= 0) {\n return null;\n }\n return {\n field: \"collateral\",\n fromValue: current.collateralUsd,\n toValue: to,\n toLabel: formatUsd(to),\n reason: \"max-collateral\",\n };\n }\n case \"raise-collateral\": {\n const to = Math.ceil(hint.minCollateralUsd * centsFactor) / centsFactor;\n if (to <= 0) {\n return null;\n }\n return {\n field: \"collateral\",\n fromValue: current.collateralUsd,\n toValue: to,\n toLabel: formatUsd(to),\n reason: \"min-collateral\",\n };\n }\n case \"clamp-leverage\": {\n if (hint.maxLeverageBps === undefined) {\n return null;\n }\n return {\n field: \"leverage\",\n fromValue: current.leverageBps,\n toValue: hint.maxLeverageBps,\n toLabel: bpsToMultiplier(hint.maxLeverageBps),\n reason: \"clamp-max\",\n };\n }\n case \"raise-leverage\":\n return {\n field: \"leverage\",\n fromValue: current.leverageBps,\n toValue: hint.minLeverageBps,\n toLabel: bpsToMultiplier(hint.minLeverageBps),\n reason: \"raise-min\",\n };\n case \"raise-slippage\":\n return {\n field: \"slippage\",\n fromValue: hint.currentSlippageBps,\n toValue: hint.maxSlippageBps,\n toLabel: `${(hint.maxSlippageBps / bpsPerPct).toFixed(decimalPlaces).replace(/\\.?0+$/, \"\")}%`,\n reason: \"raise-slippage\",\n };\n case \"raise-min-fill\":\n return {\n field: \"minFill\",\n fromValue: current.minFillBps ?? 0,\n toValue: hint.minFillBps,\n toLabel: `${(hint.minFillBps / bpsPerPct).toFixed(decimalPlaces).replace(/\\.?0+$/, \"\")}%`,\n reason: \"raise-min-fill\",\n };\n default:\n return null;\n }\n}\n","import { DimesApiError, DimesError } from \"../errors/dimes-error\";\nimport type { CreateQuoteParams, Quote } from \"../types\";\nimport type { QuoteOptions, QuoteParams, QuoteResult } from \"../types/quote\";\nimport { buildQuoteParams } from \"./build-quote-params\";\nimport { type HintAdjustment, hintAdjustment, marketMovedCodes, quoteErrorHint } from \"./quote-error-hints\";\n\nexport interface QuoteClient {\n createDraftQuote(params: CreateQuoteParams): Promise<Quote>;\n promoteDraftQuote(draftId: string): Promise<Quote>;\n createQuote(params: CreateQuoteParams): Promise<Quote>;\n}\n\nconst DEFAULT_MAX_RETRIES = 3;\n\nexport function isMarketMovedError(err: unknown): boolean {\n return err instanceof DimesApiError && marketMovedCodes.has(err.code);\n}\n\nfunction applyAdjustment(\n params: CreateQuoteParams,\n adj: NonNullable<HintAdjustment>,\n currentParams: QuoteParams,\n): CreateQuoteParams {\n switch (adj.field) {\n case \"collateral\": {\n const notionalUsdPips = Math.round(adj.toValue * params.leverageBps);\n return { ...params, notionalAmountUsdPips: notionalUsdPips.toString() };\n }\n case \"leverage\": {\n const notionalUsdPips = Math.round(currentParams.collateralUsd * adj.toValue);\n return {\n ...params,\n leverageBps: adj.toValue,\n notionalAmountUsdPips: notionalUsdPips.toString(),\n };\n }\n case \"slippage\":\n return { ...params, slippageBps: adj.toValue };\n case \"minFill\":\n return { ...params, allowPartialFill: true, minFillBps: adj.toValue };\n default:\n return params;\n }\n}\n\nfunction handleMarketMoved(err: unknown, attempt: number, maxRetries: number): boolean {\n return isMarketMovedError(err) && attempt < maxRetries;\n}\n\nfunction handleCorrection(err: unknown, currentParams: QuoteParams): { adj: NonNullable<HintAdjustment> } | null {\n if (!(err instanceof DimesApiError)) {\n return null;\n }\n\n const hint = quoteErrorHint(err.code, err.params, {\n leverageBps: currentParams.leverageBps,\n });\n\n const adj = hintAdjustment(hint, {\n collateralUsd: currentParams.collateralUsd,\n leverageBps: currentParams.leverageBps,\n slippageBps: currentParams.slippageBps,\n minFillBps: currentParams.minFillBps,\n });\n\n if (!adj) {\n return null;\n }\n\n return { adj };\n}\n\n// eslint-disable-next-line complexity\nexport async function executeQuote(\n client: QuoteClient,\n params: QuoteParams,\n options?: QuoteOptions,\n): Promise<QuoteResult> {\n const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n const autoCorrect = options?.autoCorrect ?? true;\n const corrections: NonNullable<HintAdjustment>[] = [];\n let retries = 0;\n\n let quoteParams = buildQuoteParams(params);\n const currentParams = { ...params };\n\n const draft = await client.createDraftQuote(quoteParams);\n options?.onDraftReady?.(draft);\n\n let currentDraft: Quote = draft;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const promotedQuote = await client.promoteDraftQuote(currentDraft.id);\n return { quote: promotedQuote, offer: promotedQuote, corrections, retries };\n } catch (err) {\n if (handleMarketMoved(err, attempt, maxRetries)) {\n const newDraft = await client.createDraftQuote(quoteParams);\n retries++;\n\n const callbackResult = options?.onMarketMoved?.({\n originalDraft: currentDraft,\n newDraft,\n retryCount: retries,\n });\n\n if (callbackResult === false) {\n throw err;\n }\n\n currentDraft = newDraft;\n continue;\n }\n\n if (autoCorrect) {\n const correction = handleCorrection(err, currentParams);\n\n if (correction) {\n const callbackResult = options?.onCorrection?.(correction.adj);\n if (callbackResult === false) {\n throw err;\n }\n\n quoteParams = applyAdjustment(quoteParams, correction.adj, currentParams);\n corrections.push(correction.adj);\n\n const correctedQuote = await client.createQuote(quoteParams);\n return { quote: correctedQuote, offer: correctedQuote, corrections, retries };\n }\n }\n\n throw err;\n }\n }\n\n throw new DimesError(\"market_moved_retries_exhausted\", \"Exhausted market-moved retries\");\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/quote/build-quote-params.ts","../src/quote/quote-error-hints.ts","../src/quote/quote.ts"],"sourcesContent":["import type { CreateQuoteParams } from \"../types\";\nimport type { QuoteParams } from \"../types/quote\";\n\nconst DEFAULT_LEVERAGE_STEP_BPS = 2500;\n\nexport function buildQuoteParams(params: QuoteParams, stepBps: number = DEFAULT_LEVERAGE_STEP_BPS): CreateQuoteParams {\n const leverageBps = Math.round(params.leverageBps / stepBps) * stepBps;\n const notionalUsdPips = Math.round(params.collateralUsd * leverageBps);\n\n return {\n marketTicker: params.marketTicker,\n effectiveSide: params.side,\n leverageBps,\n notionalAmountUsdPips: notionalUsdPips.toString(),\n slippageBps: params.slippageBps,\n ...(params.allowPartialFill !== undefined ? { allowPartialFill: params.allowPartialFill } : {}),\n ...(params.allowPartialFill && params.minFillBps !== undefined ? { minFillBps: params.minFillBps } : {}),\n };\n}\n","const pipsPerUsd = 10_000;\nconst bpsPerUnit = 10_000;\nconst bpsPerPct = 100;\nconst minFillBpsMax = 5_000;\nconst centsFactor = 100;\nconst decimalPlaces = 2;\n\nexport const marketMovedCodes = new Set([\n \"quote_slippage_too_high\",\n \"quote_insufficient_liquidity\",\n \"quote_entry_price_out_of_range\",\n \"quote_entry_bid_depth_too_low\",\n \"quote_entry_depth_too_low\",\n \"quote_entry_spread_too_wide\",\n]);\n\nexport type QuoteHint =\n | { kind: \"use-max-collateral\"; maxCollateralUsd: number; minCollateralUsd: number }\n | { kind: \"raise-collateral\"; minCollateralUsd: number }\n | { kind: \"clamp-leverage\"; maxLeverageBps?: number }\n | { kind: \"raise-leverage\"; minLeverageBps: number }\n | { kind: \"raise-slippage\"; currentSlippageBps: number; maxSlippageBps: number }\n | { kind: \"raise-min-fill\"; minFillBps: number }\n | { kind: \"market-full\" }\n | { kind: \"insufficient-liquidity\"; maxCollateralUsd: number; minCollateralUsd: number }\n | null;\n\ntype Params = Record<string, unknown> | null | undefined;\n\nfunction num(params: Params, key: string): number | null {\n if (!params) {\n return null;\n }\n const raw = params[key];\n if (raw === null || raw === undefined) {\n return null;\n }\n // eslint-disable-next-line no-restricted-syntax\n const n = typeof raw === \"string\" ? Number(raw) : typeof raw === \"number\" ? raw : NaN;\n return Number.isFinite(n) ? n : null;\n}\n\nfunction pipsToUsd(pips: number): number {\n return pips / pipsPerUsd;\n}\n\nfunction notionalPipsToCollateralUsd(notionalPips: number, leverageBps: number): number | null {\n if (!Number.isFinite(leverageBps) || leverageBps <= 0) {\n return null;\n }\n return (notionalPips * bpsPerUnit) / leverageBps / pipsPerUsd;\n}\n\nfunction buildExhaustedHint(\n exhaustedKind: \"market-full\" | \"insufficient-liquidity\",\n maxCollateralUsd: number,\n minCollateralUsd: number,\n): QuoteHint {\n if (exhaustedKind === \"insufficient-liquidity\") {\n return { kind: \"insufficient-liquidity\", maxCollateralUsd, minCollateralUsd };\n }\n return { kind: \"market-full\" };\n}\n\nfunction resolveMaxCollateralHint(\n params: Params,\n context: { leverageBps: number },\n capacityKey: string,\n exhaustedKind: \"market-full\" | \"insufficient-liquidity\",\n): QuoteHint {\n const serverMaxCollateralPips = num(params, \"maxSupportedCollateralUsdPips\");\n const capacityPips = num(params, capacityKey);\n const minNotionalPips = num(params, \"minNotionalUsdPips\");\n\n const fromServer = serverMaxCollateralPips !== null ? pipsToUsd(serverMaxCollateralPips) : null;\n const fromCapacity = capacityPips !== null ? notionalPipsToCollateralUsd(capacityPips, context.leverageBps) : null;\n const maxCollateralUsd =\n fromServer !== null && fromCapacity !== null ? Math.min(fromServer, fromCapacity) : (fromServer ?? fromCapacity);\n\n const minCollateralUsd =\n minNotionalPips !== null ? notionalPipsToCollateralUsd(minNotionalPips, context.leverageBps) : null;\n\n if (maxCollateralUsd === null || minCollateralUsd === null) {\n return null;\n }\n if (maxCollateralUsd < minCollateralUsd) {\n return buildExhaustedHint(exhaustedKind, maxCollateralUsd, minCollateralUsd);\n }\n return { kind: \"use-max-collateral\", maxCollateralUsd, minCollateralUsd };\n}\n\n// eslint-disable-next-line complexity\nexport function quoteErrorHint(code: string | null, params: Params, context: { leverageBps: number }): QuoteHint {\n if (!code) {\n return null;\n }\n\n switch (code) {\n case \"quote_side_capacity_exceeded\":\n case \"quote_user_position_limit_exceeded\":\n case \"quote_market_position_limit_exceeded\":\n case \"quote_side_position_limit_exceeded\":\n case \"quote_global_position_limit_exceeded\":\n case \"quote_partner_position_limit_exceeded\":\n return resolveMaxCollateralHint(params, context, \"availableCapacityUsdPips\", \"market-full\");\n\n case \"quote_insufficient_liquidity\":\n return resolveMaxCollateralHint(params, context, \"slippageMaxUsdPips\", \"market-full\");\n\n case \"notional_selector_insufficient_liquidity\":\n return resolveMaxCollateralHint(params, context, \"slippageMaxUsdPips\", \"insufficient-liquidity\");\n\n case \"quote_leverage_exceeds_collateral_floor\": {\n const minCollateralPips = num(params, \"minCollateralUsdPips\");\n if (minCollateralPips === null) {\n return null;\n }\n return { kind: \"raise-collateral\", minCollateralUsd: pipsToUsd(minCollateralPips) };\n }\n\n case \"quote_leverage_exceeds_maximum\":\n case \"quote_leverage_exceeds_model_max\": {\n const maxLeverageBps = num(params, \"maxLeverageBps\");\n if (maxLeverageBps === null) {\n return null;\n }\n return { kind: \"clamp-leverage\", maxLeverageBps };\n }\n\n case \"quote_leverage_too_high_for_price\": {\n const maxLeverageBps = num(params, \"maxAcceptableLeverageBps\");\n if (maxLeverageBps === null) {\n return null;\n }\n return { kind: \"clamp-leverage\", maxLeverageBps };\n }\n\n case \"quote_leverage_below_minimum\": {\n const minLeverageBps = num(params, \"minLeverageBps\");\n if (minLeverageBps === null) {\n return null;\n }\n return { kind: \"raise-leverage\", minLeverageBps };\n }\n\n case \"quote_min_fill_bps_below_floor\": {\n const floorMinFillBps = num(params, \"floorMinFillBps\");\n if (floorMinFillBps === null || floorMinFillBps > minFillBpsMax) {\n return null;\n }\n return { kind: \"raise-min-fill\", minFillBps: floorMinFillBps };\n }\n\n case \"quote_slippage_too_high\": {\n const currentSlippageBps = num(params, \"currentSlippageBps\");\n const maxSlippageBps = num(params, \"maxSlippageBps\");\n if (currentSlippageBps === null || maxSlippageBps === null) {\n return null;\n }\n return { kind: \"raise-slippage\", currentSlippageBps, maxSlippageBps };\n }\n\n default:\n return null;\n }\n}\n\nexport type CorrectedField = \"collateral\" | \"leverage\" | \"slippage\" | \"minFill\";\n\nexport type HintAdjustment =\n | {\n field: \"collateral\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"max-collateral\" | \"min-collateral\";\n }\n | {\n field: \"leverage\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"clamp-max\" | \"raise-min\";\n }\n | {\n field: \"slippage\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"raise-slippage\";\n }\n | {\n field: \"minFill\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"raise-min-fill\";\n }\n | null;\n\nfunction formatUsd(value: number): string {\n return new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n }).format(value);\n}\n\nfunction bpsToMultiplier(bps: number): string {\n return `${(bps / bpsPerUnit).toFixed(1).replace(/\\.0$/, \"\")}x`;\n}\n\n// eslint-disable-next-line complexity\nexport function hintAdjustment(\n hint: QuoteHint,\n current: { collateralUsd: number; leverageBps: number; slippageBps: number; minFillBps?: number },\n): HintAdjustment {\n if (!hint) {\n return null;\n }\n\n switch (hint.kind) {\n case \"use-max-collateral\": {\n const to = Math.max(0, Math.floor(hint.maxCollateralUsd * centsFactor) / centsFactor);\n if (to <= 0) {\n return null;\n }\n return {\n field: \"collateral\",\n fromValue: current.collateralUsd,\n toValue: to,\n toLabel: formatUsd(to),\n reason: \"max-collateral\",\n };\n }\n case \"raise-collateral\": {\n const to = Math.ceil(hint.minCollateralUsd * centsFactor) / centsFactor;\n if (to <= 0) {\n return null;\n }\n return {\n field: \"collateral\",\n fromValue: current.collateralUsd,\n toValue: to,\n toLabel: formatUsd(to),\n reason: \"min-collateral\",\n };\n }\n case \"clamp-leverage\": {\n if (hint.maxLeverageBps === undefined) {\n return null;\n }\n return {\n field: \"leverage\",\n fromValue: current.leverageBps,\n toValue: hint.maxLeverageBps,\n toLabel: bpsToMultiplier(hint.maxLeverageBps),\n reason: \"clamp-max\",\n };\n }\n case \"raise-leverage\":\n return {\n field: \"leverage\",\n fromValue: current.leverageBps,\n toValue: hint.minLeverageBps,\n toLabel: bpsToMultiplier(hint.minLeverageBps),\n reason: \"raise-min\",\n };\n case \"raise-slippage\":\n return {\n field: \"slippage\",\n fromValue: hint.currentSlippageBps,\n toValue: hint.maxSlippageBps,\n toLabel: `${(hint.maxSlippageBps / bpsPerPct).toFixed(decimalPlaces).replace(/\\.?0+$/, \"\")}%`,\n reason: \"raise-slippage\",\n };\n case \"raise-min-fill\":\n return {\n field: \"minFill\",\n fromValue: current.minFillBps ?? 0,\n toValue: hint.minFillBps,\n toLabel: `${(hint.minFillBps / bpsPerPct).toFixed(decimalPlaces).replace(/\\.?0+$/, \"\")}%`,\n reason: \"raise-min-fill\",\n };\n default:\n return null;\n }\n}\n","import { DimesApiError, DimesError } from \"../errors/dimes-error\";\nimport type { CreateQuoteParams, Quote } from \"../types\";\nimport type { QuoteOptions, QuoteParams, QuoteResult } from \"../types/quote\";\nimport { buildQuoteParams } from \"./build-quote-params\";\nimport { type HintAdjustment, hintAdjustment, marketMovedCodes, quoteErrorHint } from \"./quote-error-hints\";\n\nexport interface QuoteClient {\n createDraftQuote(params: CreateQuoteParams): Promise<Quote>;\n promoteDraftQuote(draftId: string): Promise<Quote>;\n createQuote(params: CreateQuoteParams): Promise<Quote>;\n}\n\nconst DEFAULT_MAX_RETRIES = 3;\n\nexport function isMarketMovedError(err: unknown): boolean {\n return err instanceof DimesApiError && marketMovedCodes.has(err.code);\n}\n\nfunction applyAdjustment(\n params: CreateQuoteParams,\n adj: NonNullable<HintAdjustment>,\n currentParams: QuoteParams,\n): CreateQuoteParams {\n switch (adj.field) {\n case \"collateral\": {\n const notionalUsdPips = Math.round(adj.toValue * params.leverageBps);\n return { ...params, notionalAmountUsdPips: notionalUsdPips.toString() };\n }\n case \"leverage\": {\n const notionalUsdPips = Math.round(currentParams.collateralUsd * adj.toValue);\n return {\n ...params,\n leverageBps: adj.toValue,\n notionalAmountUsdPips: notionalUsdPips.toString(),\n };\n }\n case \"slippage\":\n return { ...params, slippageBps: adj.toValue };\n case \"minFill\":\n return { ...params, allowPartialFill: true, minFillBps: adj.toValue };\n default:\n return params;\n }\n}\n\nfunction handleMarketMoved(err: unknown, attempt: number, maxRetries: number): boolean {\n return isMarketMovedError(err) && attempt < maxRetries;\n}\n\nfunction handleCorrection(err: unknown, currentParams: QuoteParams): { adj: NonNullable<HintAdjustment> } | null {\n if (!(err instanceof DimesApiError)) {\n return null;\n }\n\n const hint = quoteErrorHint(err.code, err.params, {\n leverageBps: currentParams.leverageBps,\n });\n\n const adj = hintAdjustment(hint, {\n collateralUsd: currentParams.collateralUsd,\n leverageBps: currentParams.leverageBps,\n slippageBps: currentParams.slippageBps,\n minFillBps: currentParams.minFillBps,\n });\n\n if (!adj) {\n return null;\n }\n\n return { adj };\n}\n\n// eslint-disable-next-line complexity\nexport async function executeQuote(\n client: QuoteClient,\n params: QuoteParams,\n options?: QuoteOptions,\n): Promise<QuoteResult> {\n const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n const autoCorrect = options?.autoCorrect ?? true;\n const corrections: NonNullable<HintAdjustment>[] = [];\n let retries = 0;\n\n let quoteParams = buildQuoteParams(params);\n const currentParams = { ...params };\n\n const draft = await client.createDraftQuote(quoteParams);\n options?.onDraftReady?.(draft);\n\n let currentDraft: Quote = draft;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const promotedQuote = await client.promoteDraftQuote(currentDraft.id);\n return { quote: promotedQuote, offer: promotedQuote, corrections, retries };\n } catch (err) {\n if (handleMarketMoved(err, attempt, maxRetries)) {\n const newDraft = await client.createDraftQuote(quoteParams);\n retries++;\n\n const callbackResult = options?.onMarketMoved?.({\n originalDraft: currentDraft,\n newDraft,\n retryCount: retries,\n });\n\n if (callbackResult === false) {\n throw err;\n }\n\n currentDraft = newDraft;\n continue;\n }\n\n if (autoCorrect) {\n const correction = handleCorrection(err, currentParams);\n\n if (correction) {\n const callbackResult = options?.onCorrection?.(correction.adj);\n if (callbackResult === false) {\n throw err;\n }\n\n quoteParams = applyAdjustment(quoteParams, correction.adj, currentParams);\n corrections.push(correction.adj);\n\n const correctedQuote = await client.createQuote(quoteParams);\n return { quote: correctedQuote, offer: correctedQuote, corrections, retries };\n }\n }\n\n throw err;\n }\n }\n\n throw new DimesError(\"market_moved_retries_exhausted\", \"Exhausted market-moved retries\");\n}\n"],"mappings":";;;;;;AAGA,IAAM,4BAA4B;AAE3B,SAAS,iBAAiB,QAAqB,UAAkB,2BAA8C;AACpH,QAAM,cAAc,KAAK,MAAM,OAAO,cAAc,OAAO,IAAI;AAC/D,QAAM,kBAAkB,KAAK,MAAM,OAAO,gBAAgB,WAAW;AAErE,SAAO;AAAA,IACL,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