@dimes-dot-fi/sdk 1.4.2 → 1.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 (39) hide show
  1. package/dist/{aliases-Dtl19fcM.d.cts → aliases-ByZ2DcA5.d.cts} +280 -5
  2. package/dist/{aliases-Dtl19fcM.d.ts → aliases-ByZ2DcA5.d.ts} +280 -5
  3. package/dist/{chunk-SGA6OZEU.mjs → chunk-3OPRSKCY.mjs} +18 -2
  4. package/dist/chunk-3OPRSKCY.mjs.map +1 -0
  5. package/dist/{chunk-DYPABUKC.cjs → chunk-72LTVPD2.cjs} +16 -1
  6. package/dist/chunk-72LTVPD2.cjs.map +1 -0
  7. package/dist/{chunk-BVILILIV.mjs → chunk-PZCBUVPD.mjs} +16 -1
  8. package/dist/chunk-PZCBUVPD.mjs.map +1 -0
  9. package/dist/{chunk-COSLZ5TM.cjs → chunk-Y5WQ3UWF.cjs} +21 -5
  10. package/dist/chunk-Y5WQ3UWF.cjs.map +1 -0
  11. package/dist/contract/index.cjs +13 -13
  12. package/dist/contract/index.d.cts +3 -3
  13. package/dist/contract/index.d.ts +3 -3
  14. package/dist/contract/index.mjs +1 -1
  15. package/dist/{dimes-client-DsRQSCTw.d.ts → dimes-client-B-thu7VQ.d.cts} +18 -3
  16. package/dist/{dimes-client-Bd7DE-tr.d.cts → dimes-client-CerC9mTr.d.ts} +18 -3
  17. package/dist/{dimes-error-DNcs8hsc.d.cts → dimes-error-BY5qVGZC.d.cts} +1 -1
  18. package/dist/{dimes-error-B46ZbXNX.d.ts → dimes-error-CrvPuFzB.d.ts} +1 -1
  19. package/dist/index.cjs +88 -6
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +138 -8
  22. package/dist/index.d.ts +138 -8
  23. package/dist/index.mjs +85 -3
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/{quote-BMw6RUjG.d.ts → quote-Czq3Selh.d.ts} +2 -2
  26. package/dist/{quote-IRF_hecL.d.cts → quote-quIOosIv.d.cts} +2 -2
  27. package/dist/react/index.cjs +4 -4
  28. package/dist/react/index.d.cts +3 -3
  29. package/dist/react/index.d.ts +3 -3
  30. package/dist/react/index.mjs +2 -2
  31. package/dist/{types-DTgaOUUw.d.cts → types-2bGyrtqd.d.cts} +1 -1
  32. package/dist/{types-Ct7tufPh.d.ts → types-CAuPxEwO.d.ts} +1 -1
  33. package/dist/ws/index.d.cts +3 -3
  34. package/dist/ws/index.d.ts +3 -3
  35. package/package.json +1 -1
  36. package/dist/chunk-BVILILIV.mjs.map +0 -1
  37. package/dist/chunk-COSLZ5TM.cjs.map +0 -1
  38. package/dist/chunk-DYPABUKC.cjs.map +0 -1
  39. package/dist/chunk-SGA6OZEU.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/dimes-client.ts","../src/client/http.ts","../src/client/auth.ts","../src/types/aliases.ts","../src/utils/eligibility.ts","../src/utils/leverage.ts","../src/utils/fees.ts"],"sourcesContent":["import { decamelizeKeys } from \"humps\";\nimport type {\n ContractInfo,\n CreateOfferParams,\n CustomerLimit,\n Market,\n Offer,\n Paginated,\n Position,\n PositionTransactions,\n} from \"../types\";\nimport type { AuthProvider } from \"./auth\";\nimport { HttpClient } from \"./http\";\n\nexport interface DimesClientOptions {\n baseUrl?: string;\n auth: AuthProvider;\n fetch?: typeof globalThis.fetch;\n maxRetries?: number;\n maxRetryDelayMs?: number;\n}\n\nexport type MarketSort = \"ticker_asc\" | \"depth_desc\" | \"discovered_at_desc\";\n\nexport interface GetMarketsParams {\n cursor?: string;\n limit?: number;\n category?: string;\n status?: string;\n provider?: \"polymarket\" | \"kalshi\";\n sort?: MarketSort;\n}\n\nexport interface GetPositionsParams {\n cursor?: string;\n limit?: number;\n status?: \"open\" | \"closed\";\n}\n\nfunction buildQueryFromEntries(entries: [string, unknown][]): string {\n const filtered = entries.filter(([, v]) => v !== undefined && v !== null);\n if (filtered.length === 0) {\n return \"\";\n }\n\n const search = new URLSearchParams();\n for (const [key, value] of filtered) {\n search.set(\n key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`),\n String(value),\n );\n }\n\n return `?${search.toString()}`;\n}\n\nexport class DimesClient {\n private readonly http: HttpClient;\n\n constructor(options: DimesClientOptions) {\n this.http = new HttpClient({\n baseUrl: options.baseUrl ?? \"https://api.dimes.fi\",\n auth: options.auth,\n fetch: options.fetch,\n maxRetries: options.maxRetries,\n maxRetryDelayMs: options.maxRetryDelayMs,\n });\n }\n\n public async getMarkets(params?: GetMarketsParams): Promise<Paginated<Market>> {\n const query = params ? buildQueryFromEntries(Object.entries(params)) : \"\";\n return this.http.request<Paginated<Market>>(`/v1/prediction-markets/markets${query}`);\n }\n\n public async getMarket(ticker: string): Promise<Market> {\n return this.http.request<Market>(`/v1/prediction-markets/markets/${encodeURIComponent(ticker)}`);\n }\n\n public async createDraftQuote(params: CreateOfferParams): Promise<Offer> {\n return this.http.request<Offer>(\"/v1/prediction-markets/draft-quotes\", {\n method: \"POST\",\n body: JSON.stringify(decamelizeKeys(params)),\n });\n }\n\n public async promoteDraftQuote(draftId: string): Promise<Offer> {\n return this.http.request<Offer>(`/v1/prediction-markets/promoted-quotes/${encodeURIComponent(draftId)}`, {\n method: \"POST\",\n });\n }\n\n public async createQuote(params: CreateOfferParams): Promise<Offer> {\n return this.http.request<Offer>(\"/v1/prediction-markets/quotes\", {\n method: \"POST\",\n body: JSON.stringify(decamelizeKeys(params)),\n });\n }\n\n public async getPositions(params?: GetPositionsParams): Promise<Position[]> {\n const query = params ? buildQueryFromEntries(Object.entries(params)) : \"\";\n return this.http.requestList<Position>(`/v1/prediction-markets/positions${query}`);\n }\n\n public async getPositionTransactions(positionId: string): Promise<PositionTransactions> {\n return this.http.request<PositionTransactions>(\n `/v1/prediction-markets/positions/${encodeURIComponent(positionId)}/transactions`,\n );\n }\n\n public async cancelPosition(positionId: string): Promise<void> {\n await this.http.request<unknown>(`/v1/prediction-markets/positions/${encodeURIComponent(positionId)}/cancel`, {\n method: \"POST\",\n });\n }\n\n public async getContractInfo(): Promise<ContractInfo> {\n return this.http.request<ContractInfo>(\"/v1/prediction-markets/contract-info\");\n }\n\n public async getLimits(): Promise<CustomerLimit> {\n return this.http.request<CustomerLimit>(\"/v1/prediction-markets/limits\");\n }\n}\n","import { camelizeKeys, type Camelized } from \"humps\";\nimport { DimesApiError } from \"../errors/dimes-error\";\nimport type { AuthProvider } from \"./auth\";\n\nexport type { Camelized };\n\ninterface ApiErrorBody {\n error?: {\n type?: string;\n code?: string;\n message: string;\n params?: Record<string, unknown>;\n };\n}\n\nconst HTTP_UNAUTHORIZED = 401;\nconst HTTP_TOO_MANY_REQUESTS = 429;\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 60_000;\nconst DEFAULT_RETRY_DELAY_MS = 1000;\nconst BACKOFF_FACTOR = 2;\nconst MS_PER_SECOND = 1000;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction parseRetryAfterMs(header: string | null, attempt: number): number {\n const fallbackMs = DEFAULT_RETRY_DELAY_MS * BACKOFF_FACTOR ** attempt;\n if (!header) {\n return fallbackMs;\n }\n\n const seconds = Number(header);\n if (!Number.isNaN(seconds) && seconds >= 0) {\n return seconds * MS_PER_SECOND;\n }\n\n const dateMs = Date.parse(header);\n if (!Number.isNaN(dateMs)) {\n return Math.max(0, dateMs - Date.now());\n }\n\n return fallbackMs;\n}\n\n// eslint-disable-next-line complexity\nasync function throwFromResponse(response: Response): Promise<never> {\n const rawBody = await response.text();\n let parsed: ApiErrorBody | null;\n try {\n parsed = rawBody ? (JSON.parse(rawBody) as ApiErrorBody) : null;\n } catch {\n parsed = null;\n }\n\n const code = parsed?.error?.code ?? \"unknown_error\";\n const type = parsed?.error?.type ?? null;\n const message = parsed?.error?.message ?? `API error ${response.status}`;\n const rawParams = parsed?.error?.params;\n const params = rawParams ? (camelizeKeys(rawParams) as Record<string, unknown>) : null;\n\n throw new DimesApiError({ status: response.status, code, type, message, params });\n}\n\nexport interface HttpClientOptions {\n baseUrl: string;\n auth: AuthProvider;\n fetch?: typeof globalThis.fetch;\n maxRetries?: number;\n maxRetryDelayMs?: number;\n}\n\nexport class HttpClient {\n private readonly baseUrl: string;\n\n private readonly auth: AuthProvider;\n\n private readonly fetchFn: typeof globalThis.fetch;\n\n private readonly maxRetries: number;\n\n private readonly maxRetryDelayMs: number;\n\n constructor(options: HttpClientOptions) {\n this.baseUrl = options.baseUrl;\n this.auth = options.auth;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n this.maxRetryDelayMs = options.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n }\n\n public async request<T>(path: string, options?: RequestInit): Promise<T> {\n const authHeaders = await this.auth.getHeaders();\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...authHeaders,\n ...(options?.headers as Record<string, string> | undefined),\n };\n\n let response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers,\n });\n\n if (response.status === HTTP_UNAUTHORIZED && this.auth.refresh) {\n await this.auth.refresh();\n const retryHeaders = await this.auth.getHeaders();\n response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers: { ...headers, ...retryHeaders },\n });\n }\n\n for (let attempt = 0; response.status === HTTP_TOO_MANY_REQUESTS && attempt < this.maxRetries; attempt++) {\n const delayMs = parseRetryAfterMs(response.headers.get(\"retry-after\"), attempt);\n if (delayMs > this.maxRetryDelayMs) {\n break;\n }\n await sleep(delayMs);\n const freshAuth = await this.auth.getHeaders();\n response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers: { ...headers, ...freshAuth },\n });\n }\n\n if (!response.ok) {\n await throwFromResponse(response);\n }\n\n return camelizeKeys(await response.json()) as T;\n }\n\n public async requestList<T>(path: string, options?: RequestInit): Promise<T[]> {\n const result = await this.request<{ data: T[] }>(path, options);\n return result.data;\n }\n}\n","import { DimesError } from \"../errors/dimes-error\";\n\nexport interface AuthProvider {\n getHeaders(): Promise<Record<string, string>>;\n refresh?(): Promise<void>;\n}\n\ninterface TokenResponse {\n token: string;\n expires_at: string;\n}\n\nexport interface ApiKeyAuthOptions {\n apiKey: string;\n walletAddress: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n}\n\nexport class ApiKeyAuth implements AuthProvider {\n private jwt: string | null = null;\n\n private expiresAt = 0;\n\n private refreshPromise: Promise<void> | null = null;\n\n private readonly apiKey: string;\n\n private readonly walletAddress: string;\n\n private readonly baseUrl: string;\n\n private readonly fetchFn: typeof globalThis.fetch;\n\n constructor(options: ApiKeyAuthOptions) {\n this.apiKey = options.apiKey;\n this.walletAddress = options.walletAddress;\n this.baseUrl = options.baseUrl ?? \"https://api.dimes.fi\";\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n public async getHeaders(): Promise<Record<string, string>> {\n const TOKEN_EXPIRY_BUFFER_MS = 30_000;\n if (!this.jwt || Date.now() >= this.expiresAt - TOKEN_EXPIRY_BUFFER_MS) {\n await this.refresh();\n }\n return { Authorization: `Bearer ${this.jwt}` };\n }\n\n public async refresh(): Promise<void> {\n if (this.refreshPromise) {\n await this.refreshPromise;\n return;\n }\n\n this.refreshPromise = this.fetchToken();\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n private async fetchToken(): Promise<void> {\n const response = await this.fetchFn(`${this.baseUrl}/v1/prediction-markets/tokens`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({ wallet_address: this.walletAddress }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new DimesError(\"auth_token_failed\", `Failed to obtain auth token (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as TokenResponse;\n this.jwt = data.token;\n this.expiresAt = new Date(data.expires_at).getTime();\n }\n}\n\nexport interface JwtAuthOptions {\n tokenUrl: string;\n fetch?: typeof globalThis.fetch;\n}\n\nexport class JwtAuth implements AuthProvider {\n private readonly fetchFn: typeof globalThis.fetch;\n\n private readonly tokenUrl: string;\n\n private jwt: string | null = null;\n\n private expiresAt = 0;\n\n private refreshPromise: Promise<void> | null = null;\n\n constructor(options: JwtAuthOptions) {\n this.tokenUrl = options.tokenUrl;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n public async getHeaders(): Promise<Record<string, string>> {\n const TOKEN_EXPIRY_BUFFER_MS = 30_000;\n if (!this.jwt || Date.now() >= this.expiresAt - TOKEN_EXPIRY_BUFFER_MS) {\n await this.refresh();\n }\n return { Authorization: `Bearer ${this.jwt}` };\n }\n\n public async refresh(): Promise<void> {\n if (this.refreshPromise) {\n await this.refreshPromise;\n return;\n }\n\n this.refreshPromise = this.fetchToken();\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n private async fetchToken(): Promise<void> {\n const response = await this.fetchFn(this.tokenUrl);\n\n if (!response.ok) {\n const text = await response.text();\n throw new DimesError(\n \"auth_token_failed\",\n `Failed to fetch token from ${this.tokenUrl} (${response.status}): ${text}`,\n );\n }\n\n const data = (await response.json()) as TokenResponse;\n this.jwt = data.token;\n this.expiresAt = new Date(data.expires_at).getTime();\n }\n}\n","import type { CamelizeKeys } from \"./camelize\";\nimport type { components } from \"./generated\";\n\ntype Raw = components[\"schemas\"];\n\nexport type Market = CamelizeKeys<Raw[\"CustomerMarket\"]>;\n\nexport type MarketLeverage = CamelizeKeys<Raw[\"CustomerLeverage\"]>;\n\nexport type MarketMaxLeveragePerNotional = CamelizeKeys<Raw[\"CustomerMaxMarketLeveragePerNotional\"]>;\n\nexport type MarketSidedMaxLeveragePerNotional = CamelizeKeys<Raw[\"CustomerSidedMaxMarketLeveragePerNotional\"]>;\n\nexport type MarketSidedEligibility = CamelizeKeys<Raw[\"CustomerSidedEligibility\"]>;\n\nexport type MarketFees = CamelizeKeys<Raw[\"CustomerFees\"]>;\n\nexport type MarketPrices = CamelizeKeys<Raw[\"CustomerMarketPrices\"]>;\n\nexport interface MarketPolymarket {\n conditionId: string | null;\n noTokenId: string;\n slug: string;\n yesTokenId: string;\n}\n\nexport type OriginationTier = CamelizeKeys<Raw[\"CustomerOriginationTier\"]>;\n\nexport type Offer = CamelizeKeys<Raw[\"CustomerOffer\"]>;\n\nexport type OpenPosition = CamelizeKeys<Raw[\"CustomerOpenPosition\"]>;\n\nexport type ClosedPosition = CamelizeKeys<Raw[\"CustomerClosedPosition\"]>;\n\nexport type Position = OpenPosition | ClosedPosition;\n\nexport type PositionEntry = CamelizeKeys<Raw[\"CustomerPositionEntry\"]>;\n\nexport type PositionCurrent = CamelizeKeys<Raw[\"CustomerPositionCurrent\"]>;\n\nexport type PositionRisk = CamelizeKeys<Raw[\"CustomerPositionRisk\"]>;\n\nexport type PositionOpenFees = CamelizeKeys<Raw[\"CustomerPositionOpenFees\"]>;\n\nexport type PositionClosedFees = CamelizeKeys<Raw[\"CustomerPositionClosedFees\"]>;\n\nexport type PositionResult = CamelizeKeys<Raw[\"CustomerPositionResult\"]>;\n\nexport type PositionTiming = CamelizeKeys<Raw[\"CustomerPositionTiming\"]>;\n\nexport type PositionFailure = CamelizeKeys<Raw[\"CustomerPositionFailure\"]>;\n\nexport type PositionUnwind = CamelizeKeys<Raw[\"CustomerPositionUnwind\"]>;\n\nexport type PositionUnwindList = CamelizeKeys<Raw[\"CustomerPositionUnwindList\"]>;\n\nexport type PositionTransactionEntry = CamelizeKeys<Raw[\"PositionTransactionEntry\"]>;\n\nexport type PositionTransactionGroup = CamelizeKeys<Raw[\"PositionTransactionGroup\"]>;\n\nexport type PositionTransactions = CamelizeKeys<Raw[\"PositionTransactions\"]>;\n\nexport type ContractInfo = CamelizeKeys<Raw[\"CustomerContractInfo\"]>;\n\nexport type CustomerLimit = CamelizeKeys<Raw[\"CustomerLimit\"]>;\n\nexport type CreateTokenResult = CamelizeKeys<Raw[\"CreateTokenResult\"]>;\n\nexport interface CreateOfferParams {\n marketTicker: string;\n effectiveSide: \"yes\" | \"no\";\n leverageBps: number;\n notionalAmountUsdPips: string;\n slippageBps: number;\n pmProvider?: \"polymarket\" | \"kalshi\";\n}\n\nexport function isOpenPosition(p: Position): p is OpenPosition {\n return \"current\" in p;\n}\n\nexport function isClosedPosition(p: Position): p is ClosedPosition {\n return \"result\" in p;\n}\n\nexport function leverageMaxBps(lev: MarketLeverage, side: \"yes\" | \"no\"): number {\n const perSide = side === \"yes\" ? lev.maxYesBps : lev.maxNoBps;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return perSide ?? lev.maxBps ?? lev.minBps;\n}\n","import type { Market } from \"../types/aliases\";\n\nexport type Side = \"yes\" | \"no\";\n\nexport interface SideEligibility {\n open: boolean;\n reasonCode: string | null;\n}\n\nexport interface SidedEligibility {\n yes: SideEligibility;\n no: SideEligibility;\n}\n\nexport function getSidedEligibility(market: Market): SidedEligibility {\n const sided = market.sidedEligibility;\n return {\n yes: {\n open: sided.yes.acceptingNewPositions,\n reasonCode: sided.yes.rejectionReasonCode ?? null,\n },\n no: {\n open: sided.no.acceptingNewPositions,\n reasonCode: sided.no.rejectionReasonCode ?? null,\n },\n };\n}\n\nexport function defaultSide(eligibility: SidedEligibility): Side | null {\n if (eligibility.yes.open && eligibility.no.open) {\n return \"yes\";\n }\n if (eligibility.yes.open) {\n return \"yes\";\n }\n if (eligibility.no.open) {\n return \"no\";\n }\n return null;\n}\n\nexport function isFullyOpen(eligibility: SidedEligibility): boolean {\n return eligibility.yes.open && eligibility.no.open;\n}\n\nexport function isFullyClosed(eligibility: SidedEligibility): boolean {\n return !eligibility.yes.open && !eligibility.no.open;\n}\n\nexport function rejectionReasonText(code: string | null | undefined): string {\n if (!code) {\n return \"Not eligible for new positions\";\n }\n const stripped = code\n .replace(/^quote_/i, \"\")\n .replaceAll(\"_\", \" \")\n .toLowerCase();\n return stripped.charAt(0).toUpperCase() + stripped.slice(1);\n}\n\nexport function rejectionReasonShort(code: string | null | undefined): string {\n if (!code) {\n return \"unavailable\";\n }\n const stripped = code\n .replace(/^quote_/i, \"\")\n .replace(/_exceeded$/i, \"\")\n .replace(/_too_(low|high)$/i, \"\")\n .replaceAll(\"_\", \" \")\n .toLowerCase();\n return stripped;\n}\n","import { type Market, type MarketMaxLeveragePerNotional, leverageMaxBps } from \"../types/aliases\";\nimport type { Side } from \"./eligibility\";\n\nconst USD_100 = 100;\nconst USD_500 = 500;\nconst USD_1K = 1_000;\nconst USD_10K = 10_000;\nconst BPS_PER_UNIT = 10_000;\n\nconst ANCHORS_USD = [USD_100, USD_500, USD_1K, USD_10K] as const;\n\ntype Anchor = readonly [usd: number, bps: number];\n\nfunction anchorsForSide(market: Market, side: Side): readonly Anchor[] {\n const sided = market.leverage.maxMarketLeveragePerNotional;\n const per: MarketMaxLeveragePerNotional = side === \"yes\" ? sided.yes : sided.no;\n return [\n [ANCHORS_USD[0], per.at100UsdBps],\n [ANCHORS_USD[1], per.at500UsdBps],\n [ANCHORS_USD[2], per.at1000UsdBps],\n [ANCHORS_USD[3], per.at10000UsdBps],\n ];\n}\n\nfunction snapDownToStep(bps: number, stepBps: number, minBps: number): number {\n if (stepBps <= 0) {\n return Math.max(minBps, bps);\n }\n const k = Math.floor((bps - minBps) / stepBps);\n return Math.max(minBps, minBps + Math.max(0, k) * stepBps);\n}\n\nfunction interpolateRawBps(anchors: readonly Anchor[], notionalUsd: number): number {\n const first = anchors[0];\n const last = anchors[anchors.length - 1];\n if (!first || !last) {\n return 0;\n }\n if (notionalUsd <= first[0]) {\n return first[1];\n }\n if (notionalUsd >= last[0]) {\n return last[1];\n }\n for (let i = 1; i < anchors.length; i++) {\n const hi = anchors[i];\n const lo = anchors[i - 1];\n if (!hi || !lo) {\n continue;\n }\n if (notionalUsd <= hi[0]) {\n const t = (notionalUsd - lo[0]) / (hi[0] - lo[0]);\n return lo[1] + (hi[1] - lo[1]) * t;\n }\n }\n return last[1];\n}\n\n/**\n * Maximum leverage in basis points the API will allow at a given notional, per side.\n * Piecewise-linear interpolation across the four anchor points ($100/$500/$1k/$10k).\n * Below $100 uses the $100 cap; above $10k uses the $10k cap. Result is clamped to\n * the absolute side max and rounded down to `stepBps`.\n */\nexport function maxLeverageBpsAtNotional(market: Market, side: Side, notionalUsd: number): number {\n const sideAbsMax = leverageMaxBps(market.leverage, side);\n if (!Number.isFinite(notionalUsd) || notionalUsd <= 0) {\n return sideAbsMax;\n }\n const anchors = anchorsForSide(market, side);\n const raw = interpolateRawBps(anchors, notionalUsd);\n const clamped = Math.min(sideAbsMax, raw);\n return snapDownToStep(clamped, market.leverage.stepBps, market.leverage.minBps);\n}\n\n/**\n * Largest leverage (bps) the user can pick for a given collateral such that the\n * resulting notional still satisfies the per-notional cap.\n *\n * Walks down from the absolute side max in `stepBps` increments and returns the\n * first leverage `lev` where `lev <= maxLeverageBpsAtNotional(collateral * lev / 1)`.\n */\nexport function maxViableLeverageBpsForCollateral(market: Market, side: Side, collateralUsd: number): number {\n const sideAbsMax = leverageMaxBps(market.leverage, side);\n if (!Number.isFinite(collateralUsd) || collateralUsd <= 0) {\n return sideAbsMax;\n }\n\n const step = Math.max(market.leverage.stepBps, 1);\n const minBps = market.leverage.minBps;\n const maxSteps = Math.max(0, Math.floor((sideAbsMax - minBps) / step));\n\n for (let i = maxSteps; i >= 0; i--) {\n const lev = minBps + i * step;\n const notionalUsd = collateralUsd * (lev / BPS_PER_UNIT);\n if (lev <= maxLeverageBpsAtNotional(market, side, notionalUsd)) {\n return lev;\n }\n }\n return minBps;\n}\n","import type { Position, PositionEntry } from \"../types/aliases\";\n\nexport interface OriginationFeeBreakdown {\n totalBps: number;\n totalUsd: number;\n protocolBps: number;\n protocolUsd: number;\n partnerBps: number;\n partnerUsd: number;\n}\n\nfunction getEntry(position: Position): PositionEntry {\n return position.entry;\n}\n\nexport function getOriginationFeeBreakdown(position: Position): OriginationFeeBreakdown {\n const entry = getEntry(position);\n const totalBps = entry.originationFeeBps;\n const totalUsd = Number(entry.originationFeeUsd) || 0;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const protocolBps = entry.protocolOriginationFeeBps ?? totalBps;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const partnerBps = entry.partnerOriginationFeeBps ?? 0;\n\n const share = totalBps > 0 ? protocolBps / totalBps : 1;\n const protocolUsd = totalUsd * share;\n const partnerUsd = totalUsd - protocolUsd;\n\n return {\n totalBps,\n totalUsd,\n protocolBps,\n protocolUsd,\n partnerBps,\n partnerUsd,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,sBAAsB;;;ACA/B,SAAS,oBAAoC;AAe7C,IAAM,oBAAoB;AAC1B,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB;AAC5B,IAAM,6BAA6B;AACnC,IAAM,yBAAyB;AAC/B,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AAEtB,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,kBAAkB,QAAuB,SAAyB;AACzE,QAAM,aAAa,yBAAyB,kBAAkB;AAC9D,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,OAAO,MAAM;AAC7B,MAAI,CAAC,OAAO,MAAM,OAAO,KAAK,WAAW,GAAG;AAC1C,WAAO,UAAU;AAAA,EACnB;AAEA,QAAM,SAAS,KAAK,MAAM,MAAM;AAChC,MAAI,CAAC,OAAO,MAAM,MAAM,GAAG;AACzB,WAAO,KAAK,IAAI,GAAG,SAAS,KAAK,IAAI,CAAC;AAAA,EACxC;AAEA,SAAO;AACT;AAGA,eAAe,kBAAkB,UAAoC;AACnE,QAAM,UAAU,MAAM,SAAS,KAAK;AACpC,MAAI;AACJ,MAAI;AACF,aAAS,UAAW,KAA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F;AACA,SAAO;AACT;;;ACzFA,SAAS,SAAS,UAAmC;AACnD,SAAO,SAAS;AAClB;AAEO,SAAS,2BAA2B,UAA6C;AACtF,QAAM,QAAQ,SAAS,QAAQ;AAC/B,QAAM,WAAW,MAAM;AACvB,QAAM,WAAW,OAAO,MAAM,iBAAiB,KAAK;AAGpD,QAAM,cAAc,MAAM,6BAA6B;AAEvD,QAAM,aAAa,MAAM,4BAA4B;AAErD,QAAM,QAAQ,WAAW,IAAI,cAAc,WAAW;AACtD,QAAM,cAAc,WAAW;AAC/B,QAAM,aAAa,WAAW;AAE9B,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/client/dimes-client.ts","../src/client/http.ts","../src/client/auth.ts","../src/types/aliases.ts","../src/utils/eligibility.ts","../src/utils/leverage.ts","../src/utils/fees.ts","../src/utils/max-gain.ts"],"sourcesContent":["import { decamelizeKeys } from \"humps\";\nimport type {\n ContractInfo,\n CreateOfferParams,\n CustomerLimit,\n FeeRates,\n FeeReport,\n FeeReportParams,\n Market,\n Offer,\n Paginated,\n Position,\n PositionTransactions,\n} from \"../types\";\nimport type { AuthProvider } from \"./auth\";\nimport { HttpClient } from \"./http\";\n\nexport interface DimesClientOptions {\n baseUrl?: string;\n auth: AuthProvider;\n fetch?: typeof globalThis.fetch;\n maxRetries?: number;\n maxRetryDelayMs?: number;\n}\n\nexport type MarketSort = \"ticker_asc\" | \"depth_desc\" | \"discovered_at_desc\";\n\nexport interface GetMarketsParams {\n cursor?: string;\n limit?: number;\n category?: string;\n status?: string;\n provider?: \"polymarket\" | \"kalshi\";\n sort?: MarketSort;\n}\n\nexport interface GetPositionsParams {\n cursor?: string;\n limit?: number;\n status?: \"open\" | \"closed\";\n}\n\nexport interface GetFeeRatesParams {\n ticker?: string;\n}\n\nfunction buildQueryFromEntries(entries: [string, unknown][]): string {\n const filtered = entries.filter(([, v]) => v !== undefined && v !== null);\n if (filtered.length === 0) {\n return \"\";\n }\n\n const search = new URLSearchParams();\n for (const [key, value] of filtered) {\n search.set(\n key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`),\n String(value),\n );\n }\n\n return `?${search.toString()}`;\n}\n\nexport class DimesClient {\n private readonly http: HttpClient;\n\n constructor(options: DimesClientOptions) {\n this.http = new HttpClient({\n baseUrl: options.baseUrl ?? \"https://api.dimes.fi\",\n auth: options.auth,\n fetch: options.fetch,\n maxRetries: options.maxRetries,\n maxRetryDelayMs: options.maxRetryDelayMs,\n });\n }\n\n public async getMarkets(params?: GetMarketsParams): Promise<Paginated<Market>> {\n const query = params ? buildQueryFromEntries(Object.entries(params)) : \"\";\n return this.http.request<Paginated<Market>>(`/v1/prediction-markets/markets${query}`);\n }\n\n public async getMarket(ticker: string): Promise<Market> {\n return this.http.request<Market>(`/v1/prediction-markets/markets/${encodeURIComponent(ticker)}`);\n }\n\n public async createDraftQuote(params: CreateOfferParams): Promise<Offer> {\n return this.http.request<Offer>(\"/v1/prediction-markets/draft-quotes\", {\n method: \"POST\",\n body: JSON.stringify(decamelizeKeys(params)),\n });\n }\n\n public async promoteDraftQuote(draftId: string): Promise<Offer> {\n return this.http.request<Offer>(`/v1/prediction-markets/promoted-quotes/${encodeURIComponent(draftId)}`, {\n method: \"POST\",\n });\n }\n\n public async createQuote(params: CreateOfferParams): Promise<Offer> {\n return this.http.request<Offer>(\"/v1/prediction-markets/quotes\", {\n method: \"POST\",\n body: JSON.stringify(decamelizeKeys(params)),\n });\n }\n\n public async getPositions(params?: GetPositionsParams): Promise<Position[]> {\n const query = params ? buildQueryFromEntries(Object.entries(params)) : \"\";\n return this.http.requestList<Position>(`/v1/prediction-markets/positions${query}`);\n }\n\n public async getPositionTransactions(positionId: string): Promise<PositionTransactions> {\n return this.http.request<PositionTransactions>(\n `/v1/prediction-markets/positions/${encodeURIComponent(positionId)}/transactions`,\n );\n }\n\n public async cancelPosition(positionId: string): Promise<void> {\n await this.http.request<unknown>(`/v1/prediction-markets/positions/${encodeURIComponent(positionId)}/cancel`, {\n method: \"POST\",\n });\n }\n\n public async getContractInfo(): Promise<ContractInfo> {\n return this.http.request<ContractInfo>(\"/v1/prediction-markets/contract-info\");\n }\n\n public async getLimits(): Promise<CustomerLimit> {\n return this.http.request<CustomerLimit>(\"/v1/prediction-markets/limits\");\n }\n\n public async getFeeRates(params?: GetFeeRatesParams): Promise<FeeRates> {\n const query = params ? buildQueryFromEntries(Object.entries(params)) : \"\";\n return this.http.request<FeeRates>(`/v1/prediction-markets/fee-rates${query}`);\n }\n\n public async getFeeReport(params: FeeReportParams): Promise<FeeReport> {\n return this.http.request<FeeReport>(\"/v1/prediction-markets/fee-reports\", {\n method: \"POST\",\n body: JSON.stringify(decamelizeKeys(params)),\n });\n }\n}\n","import { camelizeKeys, type Camelized } from \"humps\";\nimport { DimesApiError } from \"../errors/dimes-error\";\nimport type { AuthProvider } from \"./auth\";\n\nexport type { Camelized };\n\ninterface ApiErrorBody {\n error?: {\n type?: string;\n code?: string;\n message: string;\n params?: Record<string, unknown>;\n };\n}\n\nconst HTTP_UNAUTHORIZED = 401;\nconst HTTP_TOO_MANY_REQUESTS = 429;\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 60_000;\nconst DEFAULT_RETRY_DELAY_MS = 1000;\nconst BACKOFF_FACTOR = 2;\nconst MS_PER_SECOND = 1000;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction parseRetryAfterMs(header: string | null, attempt: number): number {\n const fallbackMs = DEFAULT_RETRY_DELAY_MS * BACKOFF_FACTOR ** attempt;\n if (!header) {\n return fallbackMs;\n }\n\n const seconds = Number(header);\n if (!Number.isNaN(seconds) && seconds >= 0) {\n return seconds * MS_PER_SECOND;\n }\n\n const dateMs = Date.parse(header);\n if (!Number.isNaN(dateMs)) {\n return Math.max(0, dateMs - Date.now());\n }\n\n return fallbackMs;\n}\n\n// eslint-disable-next-line complexity\nasync function throwFromResponse(response: Response): Promise<never> {\n const rawBody = await response.text();\n let parsed: ApiErrorBody | null;\n try {\n parsed = rawBody ? (JSON.parse(rawBody) as ApiErrorBody) : null;\n } catch {\n parsed = null;\n }\n\n const code = parsed?.error?.code ?? \"unknown_error\";\n const type = parsed?.error?.type ?? null;\n const message = parsed?.error?.message ?? `API error ${response.status}`;\n const rawParams = parsed?.error?.params;\n const params = rawParams ? (camelizeKeys(rawParams) as Record<string, unknown>) : null;\n\n throw new DimesApiError({ status: response.status, code, type, message, params });\n}\n\nexport interface HttpClientOptions {\n baseUrl: string;\n auth: AuthProvider;\n fetch?: typeof globalThis.fetch;\n maxRetries?: number;\n maxRetryDelayMs?: number;\n}\n\nexport class HttpClient {\n private readonly baseUrl: string;\n\n private readonly auth: AuthProvider;\n\n private readonly fetchFn: typeof globalThis.fetch;\n\n private readonly maxRetries: number;\n\n private readonly maxRetryDelayMs: number;\n\n constructor(options: HttpClientOptions) {\n this.baseUrl = options.baseUrl;\n this.auth = options.auth;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n this.maxRetryDelayMs = options.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n }\n\n public async request<T>(path: string, options?: RequestInit): Promise<T> {\n const authHeaders = await this.auth.getHeaders();\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...authHeaders,\n ...(options?.headers as Record<string, string> | undefined),\n };\n\n let response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers,\n });\n\n if (response.status === HTTP_UNAUTHORIZED && this.auth.refresh) {\n await this.auth.refresh();\n const retryHeaders = await this.auth.getHeaders();\n response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers: { ...headers, ...retryHeaders },\n });\n }\n\n for (let attempt = 0; response.status === HTTP_TOO_MANY_REQUESTS && attempt < this.maxRetries; attempt++) {\n const delayMs = parseRetryAfterMs(response.headers.get(\"retry-after\"), attempt);\n if (delayMs > this.maxRetryDelayMs) {\n break;\n }\n await sleep(delayMs);\n const freshAuth = await this.auth.getHeaders();\n response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers: { ...headers, ...freshAuth },\n });\n }\n\n if (!response.ok) {\n await throwFromResponse(response);\n }\n\n return camelizeKeys(await response.json()) as T;\n }\n\n public async requestList<T>(path: string, options?: RequestInit): Promise<T[]> {\n const result = await this.request<{ data: T[] }>(path, options);\n return result.data;\n }\n}\n","import { DimesError } from \"../errors/dimes-error\";\n\nexport interface AuthProvider {\n getHeaders(): Promise<Record<string, string>>;\n refresh?(): Promise<void>;\n}\n\ninterface TokenResponse {\n token: string;\n expires_at: string;\n}\n\nexport interface ApiKeyAuthOptions {\n apiKey: string;\n walletAddress: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n}\n\nexport class ApiKeyAuth implements AuthProvider {\n private jwt: string | null = null;\n\n private expiresAt = 0;\n\n private refreshPromise: Promise<void> | null = null;\n\n private readonly apiKey: string;\n\n private readonly walletAddress: string;\n\n private readonly baseUrl: string;\n\n private readonly fetchFn: typeof globalThis.fetch;\n\n constructor(options: ApiKeyAuthOptions) {\n this.apiKey = options.apiKey;\n this.walletAddress = options.walletAddress;\n this.baseUrl = options.baseUrl ?? \"https://api.dimes.fi\";\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n public async getHeaders(): Promise<Record<string, string>> {\n const TOKEN_EXPIRY_BUFFER_MS = 30_000;\n if (!this.jwt || Date.now() >= this.expiresAt - TOKEN_EXPIRY_BUFFER_MS) {\n await this.refresh();\n }\n return { Authorization: `Bearer ${this.jwt}` };\n }\n\n public async refresh(): Promise<void> {\n if (this.refreshPromise) {\n await this.refreshPromise;\n return;\n }\n\n this.refreshPromise = this.fetchToken();\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n private async fetchToken(): Promise<void> {\n const response = await this.fetchFn(`${this.baseUrl}/v1/prediction-markets/tokens`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({ wallet_address: this.walletAddress }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new DimesError(\"auth_token_failed\", `Failed to obtain auth token (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as TokenResponse;\n this.jwt = data.token;\n this.expiresAt = new Date(data.expires_at).getTime();\n }\n}\n\nexport interface JwtAuthOptions {\n tokenUrl: string;\n fetch?: typeof globalThis.fetch;\n}\n\nexport class JwtAuth implements AuthProvider {\n private readonly fetchFn: typeof globalThis.fetch;\n\n private readonly tokenUrl: string;\n\n private jwt: string | null = null;\n\n private expiresAt = 0;\n\n private refreshPromise: Promise<void> | null = null;\n\n constructor(options: JwtAuthOptions) {\n this.tokenUrl = options.tokenUrl;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n public async getHeaders(): Promise<Record<string, string>> {\n const TOKEN_EXPIRY_BUFFER_MS = 30_000;\n if (!this.jwt || Date.now() >= this.expiresAt - TOKEN_EXPIRY_BUFFER_MS) {\n await this.refresh();\n }\n return { Authorization: `Bearer ${this.jwt}` };\n }\n\n public async refresh(): Promise<void> {\n if (this.refreshPromise) {\n await this.refreshPromise;\n return;\n }\n\n this.refreshPromise = this.fetchToken();\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n private async fetchToken(): Promise<void> {\n const response = await this.fetchFn(this.tokenUrl);\n\n if (!response.ok) {\n const text = await response.text();\n throw new DimesError(\n \"auth_token_failed\",\n `Failed to fetch token from ${this.tokenUrl} (${response.status}): ${text}`,\n );\n }\n\n const data = (await response.json()) as TokenResponse;\n this.jwt = data.token;\n this.expiresAt = new Date(data.expires_at).getTime();\n }\n}\n","import type { CamelizeKeys } from \"./camelize\";\nimport type { components } from \"./generated\";\n\ntype Raw = components[\"schemas\"];\n\nexport type Market = CamelizeKeys<Raw[\"CustomerMarket\"]>;\n\nexport type MarketLeverage = CamelizeKeys<Raw[\"CustomerLeverage\"]>;\n\nexport type MarketMaxLeveragePerNotional = CamelizeKeys<Raw[\"CustomerMaxMarketLeveragePerNotional\"]>;\n\nexport type MarketSidedMaxLeveragePerNotional = CamelizeKeys<Raw[\"CustomerSidedMaxMarketLeveragePerNotional\"]>;\n\nexport type MarketSidedEligibility = CamelizeKeys<Raw[\"CustomerSidedEligibility\"]>;\n\nexport type MarketFees = CamelizeKeys<Raw[\"CustomerFees\"]>;\n\nexport type MarketPrices = CamelizeKeys<Raw[\"CustomerMarketPrices\"]>;\n\nexport interface MarketPolymarket {\n conditionId: string | null;\n noTokenId: string;\n slug: string;\n yesTokenId: string;\n}\n\nexport type OriginationTier = CamelizeKeys<Raw[\"CustomerOriginationTier\"]>;\n\nexport type Offer = CamelizeKeys<Raw[\"CustomerOffer\"]>;\n\nexport type OpenPosition = CamelizeKeys<Raw[\"CustomerOpenPosition\"]>;\n\nexport type ClosedPosition = CamelizeKeys<Raw[\"CustomerClosedPosition\"]>;\n\nexport type Position = OpenPosition | ClosedPosition;\n\nexport type PositionEntry = CamelizeKeys<Raw[\"CustomerPositionEntry\"]>;\n\nexport type PositionCurrent = CamelizeKeys<Raw[\"CustomerPositionCurrent\"]>;\n\nexport type PositionRisk = CamelizeKeys<Raw[\"CustomerPositionRisk\"]>;\n\nexport type PositionOpenFees = CamelizeKeys<Raw[\"CustomerPositionOpenFees\"]>;\n\nexport type PositionClosedFees = CamelizeKeys<Raw[\"CustomerPositionClosedFees\"]>;\n\nexport type PositionResult = CamelizeKeys<Raw[\"CustomerPositionResult\"]>;\n\nexport type PositionTiming = CamelizeKeys<Raw[\"CustomerPositionTiming\"]>;\n\nexport type PositionFailure = CamelizeKeys<Raw[\"CustomerPositionFailure\"]>;\n\nexport type CloseAttempt = CamelizeKeys<Raw[\"CustomerCloseAttempt\"]>;\n\nexport type PositionUnwind = CamelizeKeys<Raw[\"CustomerPositionUnwind\"]>;\n\nexport type PositionUnwindList = CamelizeKeys<Raw[\"CustomerPositionUnwindList\"]>;\n\nexport type PositionTransactionEntry = CamelizeKeys<Raw[\"PositionTransactionEntry\"]>;\n\nexport type PositionTransactionGroup = CamelizeKeys<Raw[\"PositionTransactionGroup\"]>;\n\nexport type PositionTransactions = CamelizeKeys<Raw[\"PositionTransactions\"]>;\n\nexport type ContractInfo = CamelizeKeys<Raw[\"CustomerContractInfo\"]>;\n\nexport type CustomerLimit = CamelizeKeys<Raw[\"CustomerLimit\"]>;\n\nexport type CreateTokenResult = CamelizeKeys<Raw[\"CreateTokenResult\"]>;\n\nexport type FeeRatesOriginationTier = CamelizeKeys<Raw[\"CustomerOriginationFeeTier\"]>;\n\nexport type FeeRatesMarket = CamelizeKeys<Raw[\"CustomerFeeRatesMarket\"]>;\n\nexport type FeeRates = CamelizeKeys<Raw[\"CustomerFeeRates\"]>;\n\nexport type FeeReport = CamelizeKeys<Raw[\"CustomerFeeReport\"]>;\n\nexport interface CreateOfferParams {\n marketTicker: string;\n effectiveSide: \"yes\" | \"no\";\n leverageBps: number;\n notionalAmountUsdPips: string;\n slippageBps: number;\n pmProvider?: \"polymarket\" | \"kalshi\";\n}\n\nexport interface FeeReportParams {\n marketTicker: string;\n effectiveSide: \"yes\" | \"no\";\n leverageBps: number;\n notionalAmountUsdPips: string;\n entryPriceUsdPips?: string;\n}\n\nexport function isOpenPosition(p: Position): p is OpenPosition {\n return \"current\" in p;\n}\n\nexport function isClosedPosition(p: Position): p is ClosedPosition {\n return \"result\" in p;\n}\n\nexport function leverageMaxBps(lev: MarketLeverage, side: \"yes\" | \"no\"): number {\n const perSide = side === \"yes\" ? lev.maxYesBps : lev.maxNoBps;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return perSide ?? lev.maxBps ?? lev.minBps;\n}\n","import type { Market } from \"../types/aliases\";\n\nexport type Side = \"yes\" | \"no\";\n\nexport interface SideEligibility {\n open: boolean;\n reasonCode: string | null;\n}\n\nexport interface SidedEligibility {\n yes: SideEligibility;\n no: SideEligibility;\n}\n\nexport function getSidedEligibility(market: Market): SidedEligibility {\n const sided = market.sidedEligibility;\n return {\n yes: {\n open: sided.yes.acceptingNewPositions,\n reasonCode: sided.yes.rejectionReasonCode ?? null,\n },\n no: {\n open: sided.no.acceptingNewPositions,\n reasonCode: sided.no.rejectionReasonCode ?? null,\n },\n };\n}\n\nexport function defaultSide(eligibility: SidedEligibility): Side | null {\n if (eligibility.yes.open && eligibility.no.open) {\n return \"yes\";\n }\n if (eligibility.yes.open) {\n return \"yes\";\n }\n if (eligibility.no.open) {\n return \"no\";\n }\n return null;\n}\n\nexport function isFullyOpen(eligibility: SidedEligibility): boolean {\n return eligibility.yes.open && eligibility.no.open;\n}\n\nexport function isFullyClosed(eligibility: SidedEligibility): boolean {\n return !eligibility.yes.open && !eligibility.no.open;\n}\n\nexport function rejectionReasonText(code: string | null | undefined): string {\n if (!code) {\n return \"Not eligible for new positions\";\n }\n const stripped = code\n .replace(/^quote_/i, \"\")\n .replaceAll(\"_\", \" \")\n .toLowerCase();\n return stripped.charAt(0).toUpperCase() + stripped.slice(1);\n}\n\nexport function rejectionReasonShort(code: string | null | undefined): string {\n if (!code) {\n return \"unavailable\";\n }\n const stripped = code\n .replace(/^quote_/i, \"\")\n .replace(/_exceeded$/i, \"\")\n .replace(/_too_(low|high)$/i, \"\")\n .replaceAll(\"_\", \" \")\n .toLowerCase();\n return stripped;\n}\n","import { type Market, type MarketMaxLeveragePerNotional, leverageMaxBps } from \"../types/aliases\";\nimport type { Side } from \"./eligibility\";\n\nconst USD_100 = 100;\nconst USD_500 = 500;\nconst USD_1K = 1_000;\nconst USD_10K = 10_000;\nconst BPS_PER_UNIT = 10_000;\n\nconst ANCHORS_USD = [USD_100, USD_500, USD_1K, USD_10K] as const;\n\ntype Anchor = readonly [usd: number, bps: number];\n\nfunction anchorsForSide(market: Market, side: Side): readonly Anchor[] {\n const sided = market.leverage.maxMarketLeveragePerNotional;\n const per: MarketMaxLeveragePerNotional = side === \"yes\" ? sided.yes : sided.no;\n return [\n [ANCHORS_USD[0], per.at100UsdBps],\n [ANCHORS_USD[1], per.at500UsdBps],\n [ANCHORS_USD[2], per.at1000UsdBps],\n [ANCHORS_USD[3], per.at10000UsdBps],\n ];\n}\n\nfunction snapDownToStep(bps: number, stepBps: number, minBps: number): number {\n if (stepBps <= 0) {\n return Math.max(minBps, bps);\n }\n const k = Math.floor((bps - minBps) / stepBps);\n return Math.max(minBps, minBps + Math.max(0, k) * stepBps);\n}\n\nfunction interpolateRawBps(anchors: readonly Anchor[], notionalUsd: number): number {\n const first = anchors[0];\n const last = anchors[anchors.length - 1];\n if (!first || !last) {\n return 0;\n }\n if (notionalUsd <= first[0]) {\n return first[1];\n }\n if (notionalUsd >= last[0]) {\n return last[1];\n }\n for (let i = 1; i < anchors.length; i++) {\n const hi = anchors[i];\n const lo = anchors[i - 1];\n if (!hi || !lo) {\n continue;\n }\n if (notionalUsd <= hi[0]) {\n const t = (notionalUsd - lo[0]) / (hi[0] - lo[0]);\n return lo[1] + (hi[1] - lo[1]) * t;\n }\n }\n return last[1];\n}\n\n/**\n * Maximum leverage in basis points the API will allow at a given notional, per side.\n * Piecewise-linear interpolation across the four anchor points ($100/$500/$1k/$10k).\n * Below $100 uses the $100 cap; above $10k uses the $10k cap. Result is clamped to\n * the absolute side max and rounded down to `stepBps`.\n */\nexport function maxLeverageBpsAtNotional(market: Market, side: Side, notionalUsd: number): number {\n const sideAbsMax = leverageMaxBps(market.leverage, side);\n if (!Number.isFinite(notionalUsd) || notionalUsd <= 0) {\n return sideAbsMax;\n }\n const anchors = anchorsForSide(market, side);\n const raw = interpolateRawBps(anchors, notionalUsd);\n const clamped = Math.min(sideAbsMax, raw);\n return snapDownToStep(clamped, market.leverage.stepBps, market.leverage.minBps);\n}\n\n/**\n * Largest leverage (bps) the user can pick for a given collateral such that the\n * resulting notional still satisfies the per-notional cap.\n *\n * Walks down from the absolute side max in `stepBps` increments and returns the\n * first leverage `lev` where `lev <= maxLeverageBpsAtNotional(collateral * lev / 1)`.\n */\nexport function maxViableLeverageBpsForCollateral(market: Market, side: Side, collateralUsd: number): number {\n const sideAbsMax = leverageMaxBps(market.leverage, side);\n if (!Number.isFinite(collateralUsd) || collateralUsd <= 0) {\n return sideAbsMax;\n }\n\n const step = Math.max(market.leverage.stepBps, 1);\n const minBps = market.leverage.minBps;\n const maxSteps = Math.max(0, Math.floor((sideAbsMax - minBps) / step));\n\n for (let i = maxSteps; i >= 0; i--) {\n const lev = minBps + i * step;\n const notionalUsd = collateralUsd * (lev / BPS_PER_UNIT);\n if (lev <= maxLeverageBpsAtNotional(market, side, notionalUsd)) {\n return lev;\n }\n }\n return minBps;\n}\n","import type { Position, PositionEntry } from \"../types/aliases\";\n\nconst BPS_DIVISOR = 10_000;\n\n/**\n * One leverage-tiered origination-fee rate. `maxLeverageBps` is the inclusive\n * upper bound (in basis points) of leverage covered by this tier; `feeBps` is\n * the protocol origination fee charged for any leverage at or below that bound.\n * Tiers must be supplied in ascending `maxLeverageBps` order; the final tier\n * acts as the catch-all for the highest leverages.\n */\nexport interface OriginationFeeTier {\n maxLeverageBps: number;\n feeBps: number;\n}\n\n/**\n * Resolve the protocol origination fee rate (bps) for a given leverage from an\n * ordered list of leverage tiers. Returns the `feeBps` of the first tier whose\n * `maxLeverageBps >= leverageBps`. If no tier matches (leverage exceeds every\n * bound) the last tier is used as the catch-all. The caller fetches the tiers\n * from the `fee-rates` API; the math is pure.\n *\n * Note: this returns the PROTOCOL rate only — add `partnerOriginationFeeBps`\n * separately (see {@link resolveOriginationFeeBps}).\n */\nexport function resolveProtocolOriginationFeeBps(tiers: readonly OriginationFeeTier[], leverageBps: number): number {\n const lastTier = tiers[tiers.length - 1];\n if (!lastTier) {\n return 0;\n }\n for (const tier of tiers) {\n if (leverageBps <= tier.maxLeverageBps) {\n return tier.feeBps;\n }\n }\n return lastTier.feeBps;\n}\n\n/**\n * Combined origination fee rate (bps) = protocol tier rate + partner add-on.\n * Mirrors the server: the protocol rate is leverage-tiered, the partner rate is\n * a flat add-on supplied by the partner's `fee-rates` config.\n */\nexport function resolveOriginationFeeBps(\n tiers: readonly OriginationFeeTier[],\n leverageBps: number,\n partnerOriginationFeeBps: number,\n): number {\n return resolveProtocolOriginationFeeBps(tiers, leverageBps) + partnerOriginationFeeBps;\n}\n\n/**\n * Origination fee in USDC units (1_000_000 = $1), floored, matching the server:\n * `floor(notionalUsdcUnits * combinedOriginationFeeBps / 10_000)`.\n */\nexport function computeOriginationFeeUsdcUnits(notionalUsdcUnits: number, combinedOriginationFeeBps: number): number {\n return Math.floor((notionalUsdcUnits * combinedOriginationFeeBps) / BPS_DIVISOR);\n}\n\nexport interface OriginationFeeBreakdown {\n totalBps: number;\n totalUsd: number;\n protocolBps: number;\n protocolUsd: number;\n partnerBps: number;\n partnerUsd: number;\n}\n\nfunction getEntry(position: Position): PositionEntry {\n return position.entry;\n}\n\nexport function getOriginationFeeBreakdown(position: Position): OriginationFeeBreakdown {\n const entry = getEntry(position);\n const totalBps = entry.originationFeeBps;\n const totalUsd = Number(entry.originationFeeUsd) || 0;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const protocolBps = entry.protocolOriginationFeeBps ?? totalBps;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const partnerBps = entry.partnerOriginationFeeBps ?? 0;\n\n const share = totalBps > 0 ? protocolBps / totalBps : 1;\n const protocolUsd = totalUsd * share;\n const partnerUsd = totalUsd - protocolUsd;\n\n return {\n totalBps,\n totalUsd,\n protocolBps,\n protocolUsd,\n partnerBps,\n partnerUsd,\n };\n}\n","const BPS_DIVISOR = 10_000;\nconst USDC_UNITS_PER_USD = 1_000_000;\nconst TOKEN_UNITS_PER_TOKEN = 1_000_000;\n\n/**\n * Inputs to the Polymarket trading-fee curve. All rates are basis points; the\n * caller fetches `feeRateBps`, `feeExponent`, and `builderTakerFeeRateBps` from\n * the `fee-rates` API (snapshotted server-side as `Offer.polymarketFeeRateBps`\n * / `polymarketFeeExponent` / `polymarketBuilderFeeRateBps`).\n */\nexport interface PolymarketTradingFeeInput {\n notionalUsdcUnits: number;\n priceUsd: number;\n feeRateBps: number;\n feeExponent?: number;\n builderTakerFeeRateBps?: number;\n}\n\n/**\n * Polymarket open/close trading fee in USDC units (1_000_000 = $1).\n *\n * Matches the canonical formula (docs: position-math/09-exchange-trading-fees):\n *\n * ```\n * protocol = feeRateBps / 10_000 * C * (p * (1 - p)) ^ feeExponent * 1e6\n * builder = builderTakerFeeRateBps / 10_000 * notionalUsdc\n * fee = ceil(protocol + builder)\n * ```\n *\n * where `C` = contracts = notionalUsd / p, `p` = price in dollars (0..1). The\n * curvature term peaks at p = 0.5 and is symmetric; the flat builder term does\n * not shrink at price extremes. `feeExponent` defaults to 1 (standard quadratic\n * curvature); some markets use 0 (flat `feeRate * C`). `builderTakerFeeRateBps`\n * defaults to 0 (Bloom's own operator builder code is always 0-fee).\n */\nexport function computePolymarketTradingFee(input: PolymarketTradingFeeInput): number {\n const { notionalUsdcUnits, priceUsd, feeRateBps } = input;\n const feeExponent = input.feeExponent ?? 1;\n const builderTakerFeeRateBps = input.builderTakerFeeRateBps ?? 0;\n\n if (priceUsd <= 0) {\n return 0;\n }\n\n const notionalUsd = notionalUsdcUnits / USDC_UNITS_PER_USD;\n const contracts = notionalUsd / priceUsd;\n const curvature = (priceUsd * (1 - priceUsd)) ** feeExponent;\n\n const protocolFeeUsdcUnits = (feeRateBps / BPS_DIVISOR) * contracts * curvature * USDC_UNITS_PER_USD;\n const builderFeeUsdcUnits = (builderTakerFeeRateBps / BPS_DIVISOR) * notionalUsdcUnits;\n\n return Math.ceil(protocolFeeUsdcUnits + builderFeeUsdcUnits);\n}\n\n/**\n * Expected position size in token units (1_000_000 = 1 whole token) for a given\n * notional and entry price, optionally discounted by slippage. A token redeems\n * at $1 on a win, so token units are numerically equal to USDC units.\n *\n * `tokens = notionalUsd / entryPrice`, then scaled down by `slippageBps`.\n * Floored to whole token units. This is an at-quote estimate of the offer's\n * `minExpectedPositionTokenUnits`; the server is authoritative.\n */\nexport function expectedPositionTokenUnits(notionalUsdcUnits: number, entryPriceUsd: number, slippageBps = 0): number {\n if (entryPriceUsd <= 0) {\n return 0;\n }\n const notionalUsd = notionalUsdcUnits / USDC_UNITS_PER_USD;\n const tokens = notionalUsd / entryPriceUsd;\n const slippageFactor = (BPS_DIVISOR - slippageBps) / BPS_DIVISOR;\n return Math.floor(tokens * slippageFactor * TOKEN_UNITS_PER_TOKEN);\n}\n\n/**\n * Estimated base liquidation price (deterministic, at-entry closed form).\n *\n * **This is an estimate, not the server's TWAP solver result.** It computes the\n * at-entry base liquidation price (F = 0, no safety margin) per the docs\n * (position-math/04-liquidation):\n *\n * ```\n * P_liq_base = entryPrice * (L - 1) / L * (1 + liquidationFeeBps / 10_000)\n * ```\n *\n * where `L = leverageBps / 10_000`. At 1x leverage the borrowed capital is zero\n * so the liquidation price is zero. `entryPriceUsd` is in dollars; the result is\n * in the same units. The live server liquidation price drifts above this as the\n * lifetime fee `F` accrues and includes a safety margin.\n */\nexport function estimateLiquidationPrice(\n entryPriceUsd: number,\n leverageBps: number,\n liquidationFeeBps: number,\n): number {\n const leverage = leverageBps / BPS_DIVISOR;\n if (leverage <= 1) {\n return 0;\n }\n const loanPerToken = entryPriceUsd * ((leverage - 1) / leverage);\n return loanPerToken * (1 + liquidationFeeBps / BPS_DIVISOR);\n}\n\n/**\n * Inputs for {@link computeMaxGain}. All amounts are in USDC units\n * (1_000_000 = $1) except `positionTokenUnits` (token units, 1_000_000 = 1\n * token) which is numerically equal to its settlement USDC value.\n */\nexport interface MaxGainInput {\n positionTokenUnits: number;\n notionalUsdcUnits: number;\n expectedOpenTradingFeeUsdcUnits: number;\n originationFeeUsdcUnits: number;\n}\n\n/**\n * Result of {@link computeMaxGain}. All amounts in USDC units (1_000_000 = $1).\n * Gains are profit OVER principal (notional = loan + collateral) and may be\n * negative — they are signed and never clamped.\n */\nexport interface MaxGainResult {\n fullValueOnWinUsdcUnits: number;\n grossMaxGainUsdcUnits: number;\n netMaxGainUsdcUnits: number;\n}\n\n/**\n * Maximum gain (gross and net) for a winning settlement exit — profit over\n * principal. On a win each position token redeems at $1 (CTF settlement), so\n * the full value equals `positionTokenUnits` and there is NO exit trading fee.\n *\n * ```\n * fullValueOnWin = positionTokenUnits\n * grossMaxGain = fullValueOnWin - notionalUsdcUnits\n * netMaxGain = grossMaxGain - expectedOpenTradingFee - originationFee\n * ```\n *\n * Lifetime fees are excluded, so net max gain is an upper bound (a position held\n * to settlement accrues lifetime fees that reduce realized profit). Gains are\n * signed — a position whose principal exceeds its winning redemption value\n * yields a negative max gain.\n */\nexport function computeMaxGain(input: MaxGainInput): MaxGainResult {\n const fullValueOnWinUsdcUnits = input.positionTokenUnits;\n const grossMaxGainUsdcUnits = fullValueOnWinUsdcUnits - input.notionalUsdcUnits;\n const netMaxGainUsdcUnits =\n grossMaxGainUsdcUnits - input.expectedOpenTradingFeeUsdcUnits - input.originationFeeUsdcUnits;\n\n return {\n fullValueOnWinUsdcUnits,\n grossMaxGainUsdcUnits,\n netMaxGainUsdcUnits,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,sBAAsB;;;ACA/B,SAAS,oBAAoC;AAe7C,IAAM,oBAAoB;AAC1B,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB;AAC5B,IAAM,6BAA6B;AACnC,IAAM,yBAAyB;AAC/B,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AAEtB,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,kBAAkB,QAAuB,SAAyB;AACzE,QAAM,aAAa,yBAAyB,kBAAkB;AAC9D,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AAEA,QAAM,UA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AAoBA;AACjD;AAyCO,SAAS,eAAe,OAAoC;AACjE,QAAM,0BAA0B,MAAM;AACtC,QAAM,wBAAwB,0BAA0B,MAAM;AAC9D,QAAM,sBACJ,wBAAwB,MAAM,kCAAkC,MAAM;AAExE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["BPS_DIVISOR"]}
@@ -1,5 +1,5 @@
1
- import { H as HintAdjustment } from './dimes-client-DsRQSCTw.js';
2
- import { O as Offer } from './aliases-Dtl19fcM.js';
1
+ import { H as HintAdjustment } from './dimes-client-CerC9mTr.js';
2
+ import { O as Offer } from './aliases-ByZ2DcA5.js';
3
3
 
4
4
  type Side = "yes" | "no";
5
5
  interface QuoteParams {
@@ -1,5 +1,5 @@
1
- import { H as HintAdjustment } from './dimes-client-Bd7DE-tr.cjs';
2
- import { O as Offer } from './aliases-Dtl19fcM.cjs';
1
+ import { H as HintAdjustment } from './dimes-client-B-thu7VQ.cjs';
2
+ import { O as Offer } from './aliases-ByZ2DcA5.cjs';
3
3
 
4
4
  type Side = "yes" | "no";
5
5
  interface QuoteParams {
@@ -1,9 +1,9 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
- var _chunkCOSLZ5TMcjs = require('../chunk-COSLZ5TM.cjs');
3
+ var _chunkY5WQ3UWFcjs = require('../chunk-Y5WQ3UWF.cjs');
4
4
 
5
5
 
6
- var _chunkDYPABUKCcjs = require('../chunk-DYPABUKC.cjs');
6
+ var _chunk72LTVPD2cjs = require('../chunk-72LTVPD2.cjs');
7
7
 
8
8
  // src/react/provider.tsx
9
9
  var _react = require('react');
@@ -15,7 +15,7 @@ function DimesProvider({ client, children }) {
15
15
  function useDimesClient() {
16
16
  const client = _react.useContext.call(void 0, DimesContext);
17
17
  if (!client) {
18
- throw new (0, _chunkDYPABUKCcjs.DimesError)("missing_provider", "useDimesClient must be used within a <DimesProvider>");
18
+ throw new (0, _chunk72LTVPD2cjs.DimesError)("missing_provider", "useDimesClient must be used within a <DimesProvider>");
19
19
  }
20
20
  return client;
21
21
  }
@@ -59,7 +59,7 @@ function useQuote() {
59
59
  async (params, options) => {
60
60
  dispatch({ type: "loading" });
61
61
  try {
62
- const result = await _chunkCOSLZ5TMcjs.executeQuote.call(void 0, client, params, {
62
+ const result = await _chunkY5WQ3UWFcjs.executeQuote.call(void 0, client, params, {
63
63
  ...options,
64
64
  onDraftReady: (draft) => {
65
65
  dispatch({ type: "draftReady", draft });
@@ -1,8 +1,8 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode } from 'react';
3
- import { D as DimesClient, H as HintAdjustment, G as GetMarketsParams, P as Paginated, d as GetPositionsParams } from '../dimes-client-Bd7DE-tr.cjs';
4
- import { O as Offer, M as Market, P as Position, c as ContractInfo, e as CustomerLimit } from '../aliases-Dtl19fcM.cjs';
5
- import { Q as QuoteParams, a as QuoteOptions, b as QuoteResult } from '../quote-IRF_hecL.cjs';
3
+ import { D as DimesClient, H as HintAdjustment, d as GetMarketsParams, P as Paginated, e as GetPositionsParams } from '../dimes-client-B-thu7VQ.cjs';
4
+ import { O as Offer, M as Market, P as Position, d as ContractInfo, f as CustomerLimit } from '../aliases-ByZ2DcA5.cjs';
5
+ import { Q as QuoteParams, a as QuoteOptions, b as QuoteResult } from '../quote-quIOosIv.cjs';
6
6
  import { UseQueryOptions, UseQueryResult, UseMutationOptions, UseMutationResult } from '@tanstack/react-query';
7
7
 
8
8
  interface DimesProviderProps {
@@ -1,8 +1,8 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode } from 'react';
3
- import { D as DimesClient, H as HintAdjustment, G as GetMarketsParams, P as Paginated, d as GetPositionsParams } from '../dimes-client-DsRQSCTw.js';
4
- import { O as Offer, M as Market, P as Position, c as ContractInfo, e as CustomerLimit } from '../aliases-Dtl19fcM.js';
5
- import { Q as QuoteParams, a as QuoteOptions, b as QuoteResult } from '../quote-BMw6RUjG.js';
3
+ import { D as DimesClient, H as HintAdjustment, d as GetMarketsParams, P as Paginated, e as GetPositionsParams } from '../dimes-client-CerC9mTr.js';
4
+ import { O as Offer, M as Market, P as Position, d as ContractInfo, f as CustomerLimit } from '../aliases-ByZ2DcA5.js';
5
+ import { Q as QuoteParams, a as QuoteOptions, b as QuoteResult } from '../quote-Czq3Selh.js';
6
6
  import { UseQueryOptions, UseQueryResult, UseMutationOptions, UseMutationResult } from '@tanstack/react-query';
7
7
 
8
8
  interface DimesProviderProps {
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  executeQuote
3
- } from "../chunk-SGA6OZEU.mjs";
3
+ } from "../chunk-3OPRSKCY.mjs";
4
4
  import {
5
5
  DimesError
6
- } from "../chunk-BVILILIV.mjs";
6
+ } from "../chunk-PZCBUVPD.mjs";
7
7
 
8
8
  // src/react/provider.tsx
9
9
  import { createContext, useContext } from "react";
@@ -1,4 +1,4 @@
1
- import { P as Position, M as Market, B as MarketPolymarket, g as MarketLeverage } from './aliases-Dtl19fcM.cjs';
1
+ import { P as Position, M as Market, I as MarketPolymarket, l as MarketLeverage } from './aliases-ByZ2DcA5.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.reverted", "position.settled"];
4
4
  type PositionEventType = (typeof positionEventTypes)[number];
@@ -1,4 +1,4 @@
1
- import { P as Position, M as Market, B as MarketPolymarket, g as MarketLeverage } from './aliases-Dtl19fcM.js';
1
+ import { P as Position, M as Market, I as MarketPolymarket, l as MarketLeverage } from './aliases-ByZ2DcA5.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.reverted", "position.settled"];
4
4
  type PositionEventType = (typeof positionEventTypes)[number];
@@ -1,6 +1,6 @@
1
- import { a as PositionEventType, P as PositionEvent, N as NotificationEvent, M as MarketEventType, b as MarketEvent } from '../types-DTgaOUUw.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-DTgaOUUw.cjs';
3
- import '../aliases-Dtl19fcM.cjs';
1
+ import { a as PositionEventType, P as PositionEvent, N as NotificationEvent, M as MarketEventType, b as MarketEvent } from '../types-2bGyrtqd.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-2bGyrtqd.cjs';
3
+ import '../aliases-ByZ2DcA5.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, M as MarketEventType, b as MarketEvent } from '../types-Ct7tufPh.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-Ct7tufPh.js';
3
- import '../aliases-Dtl19fcM.js';
1
+ import { a as PositionEventType, P as PositionEvent, N as NotificationEvent, M as MarketEventType, b as MarketEvent } from '../types-CAuPxEwO.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-CAuPxEwO.js';
3
+ import '../aliases-ByZ2DcA5.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": "1.4.2",
3
+ "version": "1.5.0",
4
4
  "description": "TypeScript SDK for the Dimes prediction market API",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -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 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_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 at the selected size.\",\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,IA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uBAAuB,MAAM,MAAM,KAAK,aAAa,IAAI;AAClE;;;ACxPO,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-COSLZ5TM.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,YA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A;AACH,MAAA;AACF,IAAA;AACE,MAAA;AACJ,EAAA;AACF;AAES;AACA,EAAA;AACT;AAES;AACD,EAAA;AACJ,IAAA;AACF,EAAA;AAEM,EAAA;AACJ,IAAA;AACD,EAAA;AAEK,EAAA;AACJ,IAAA;AACA,IAAA;AACA,IAAA;AACD,EAAA;AAEI,EAAA;AACH,IAAA;AACF,EAAA;AAEO,EAAA;AACT;AAGA;AAKQ,EAAA;AACA,EAAA;AACA,EAAA;AACF,EAAA;AAEA,EAAA;AACE,EAAA;AAEA,EAAA;AACN,kBAAA;AAEI,EAAA;AAEJ,EAAA;AACM,IAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACM,MAAA;AACF,QAAA;AACA,QAAA;AAEA,QAAA;AACE,UAAA;AACA,UAAA;AACA,UAAA;AACD,QAAA;AAED,QAAA;AACE,UAAA;AACF,QAAA;AAEA,QAAA;AACA,QAAA;AACF,MAAA;AAEI,MAAA;AACF,QAAA;AAEA,QAAA;AACE,UAAA;AACA,UAAA;AACE,YAAA;AACF,UAAA;AAEA,UAAA;AACA,UAAA;AAEA,UAAA;AACA,UAAA;AACF,QAAA;AACF,MAAA;AAEA,MAAA;AACF,IAAA;AACF,EAAA;AAEM,EAAA;AACR;AHsKU;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/alexemery/bl/dimes-sdk/dist/chunk-COSLZ5TM.cjs","sourcesContent":[null,"import type { CreateOfferParams } 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): CreateOfferParams {\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 };\n}\n","const pipsPerUsd = 10_000;\nconst bpsPerUnit = 10_000;\nconst bpsPerPct = 100;\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: \"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_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\";\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 | 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\nexport function hintAdjustment(\n hint: QuoteHint,\n current: { collateralUsd: number; leverageBps: number; slippageBps: 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 default:\n return null;\n }\n}\n","import { DimesApiError, DimesError } from \"../errors/dimes-error\";\nimport type { CreateOfferParams, Offer } 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: CreateOfferParams): Promise<Offer>;\n promoteDraftQuote(draftId: string): Promise<Offer>;\n createQuote(params: CreateOfferParams): Promise<Offer>;\n}\n\nconst DEFAULT_MAX_RETRIES = 3;\n\nfunction isMarketMovedError(err: unknown): boolean {\n return err instanceof DimesApiError && marketMovedCodes.has(err.code);\n}\n\nfunction applyAdjustment(\n params: CreateOfferParams,\n adj: NonNullable<HintAdjustment>,\n currentParams: QuoteParams,\n): CreateOfferParams {\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 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 });\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 offerParams = buildQuoteParams(params);\n const currentParams = { ...params };\n\n const draft = await client.createDraftQuote(offerParams);\n options?.onDraftReady?.(draft);\n\n let currentDraft: Offer = draft;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const promotedOffer = await client.promoteDraftQuote(currentDraft.id);\n return { offer: promotedOffer, corrections, retries };\n } catch (err) {\n if (handleMarketMoved(err, attempt, maxRetries)) {\n const newDraft = await client.createDraftQuote(offerParams);\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 offerParams = applyAdjustment(offerParams, correction.adj, currentParams);\n corrections.push(correction.adj);\n\n const correctedOffer = await client.createQuote(offerParams);\n return { offer: correctedOffer, 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":["/Users/alexemery/bl/dimes-sdk/dist/chunk-DYPABUKC.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,EAAA,GAAA,CAAI,OAAO,MAAA,IAAU,SAAA,GAAY,KAAA,CAAM,IAAA,CAAK,EAAA,IAAM,EAAA,EAAI;AACpD,IAAA,MAAM,OAAA,EAAS,MAAA,CAAO,KAAK,CAAA;AAC3B,IAAA,GAAA,CAAI,MAAA,CAAO,QAAA,CAAS,MAAM,CAAA,EAAG;AAC3B,MAAA,OAAO,MAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;AAEO,SAAS,QAAA,CAAS,KAAA,EAA+B;AACtD,EAAA,GAAA,CAAI,OAAO,MAAA,IAAU,QAA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EA,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;AJ4QU;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/alexemery/bl/dimes-sdk/dist/chunk-DYPABUKC.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 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_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 at the selected size.\",\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":["../src/quote/build-quote-params.ts","../src/quote/quote-error-hints.ts","../src/quote/quote.ts"],"sourcesContent":["import type { CreateOfferParams } 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): CreateOfferParams {\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 };\n}\n","const pipsPerUsd = 10_000;\nconst bpsPerUnit = 10_000;\nconst bpsPerPct = 100;\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: \"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_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\";\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 | 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\nexport function hintAdjustment(\n hint: QuoteHint,\n current: { collateralUsd: number; leverageBps: number; slippageBps: 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 default:\n return null;\n }\n}\n","import { DimesApiError, DimesError } from \"../errors/dimes-error\";\nimport type { CreateOfferParams, Offer } 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: CreateOfferParams): Promise<Offer>;\n promoteDraftQuote(draftId: string): Promise<Offer>;\n createQuote(params: CreateOfferParams): Promise<Offer>;\n}\n\nconst DEFAULT_MAX_RETRIES = 3;\n\nfunction isMarketMovedError(err: unknown): boolean {\n return err instanceof DimesApiError && marketMovedCodes.has(err.code);\n}\n\nfunction applyAdjustment(\n params: CreateOfferParams,\n adj: NonNullable<HintAdjustment>,\n currentParams: QuoteParams,\n): CreateOfferParams {\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 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 });\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 offerParams = buildQuoteParams(params);\n const currentParams = { ...params };\n\n const draft = await client.createDraftQuote(offerParams);\n options?.onDraftReady?.(draft);\n\n let currentDraft: Offer = draft;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const promotedOffer = await client.promoteDraftQuote(currentDraft.id);\n return { offer: promotedOffer, corrections, retries };\n } catch (err) {\n if (handleMarketMoved(err, attempt, maxRetries)) {\n const newDraft = await client.createDraftQuote(offerParams);\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 offerParams = applyAdjustment(offerParams, correction.adj, currentParams);\n corrections.push(correction.adj);\n\n const correctedOffer = await client.createQuote(offerParams);\n return { offer: correctedOffer, 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,cAAc,OAAO;AAAA,IACrB,eAAe,OAAO;AAAA,IACtB;AAAA,IACA,uBAAuB,gBAAgB,SAAS;AAAA,IAChD,aAAa,OAAO;AAAA,EACtB;AACF;;;AChBA,IAAM,aAAa;AACnB,IAAM,aAAa;AACnB,IAAM,YAAY;AAClB,IAAM,cAAc;AACpB,IAAM,gBAAgB;AAEf,IAAM,mBAAmB,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAcD,SAAS,IAAI,QAAgB,KAA4B;AACvD,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AACA,QAAM,MAAM,OAAO,GAAG;AACtB,MAAI,QAAQ,QAAQ,QAAQ,QAAW;AACrC,WAAO;AAAA,EACT;AAEA,QAAM,IAAI,OAAO,QAAQ,WAAW,OAAO,GAAG,IAAI,OAAO,QAAQ,WAAW,MAAM;AAClF,SAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AAClC;AAEA,SAAS,UAAU,MAAsB;AACvC,SAAO,OAAO;AAChB;AAEA,SAAS,4BAA4B,cAAsB,aAAoC;AAC7F,MAAI,CAAC,OAAO,SAAS,WAAW,KAAK,eAAe,GAAG;AACrD,WAAO;AAAA,EACT;AACA,SAAQ,eAAe,aAAc,cAAc;AACrD;AAEA,SAAS,mBACP,eACA,kBACA,kBACW;AACX,MAAI,kBAAkB,0BAA0B;AAC9C,WAAO,EAA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