@dimes-dot-fi/sdk 1.4.3 → 2.0.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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +88 -19
  3. package/dist/{aliases-C2l_JZX_.d.cts → aliases-BJyM8ydu.d.cts} +288 -4
  4. package/dist/{aliases-C2l_JZX_.d.ts → aliases-BJyM8ydu.d.ts} +288 -4
  5. package/dist/{chunk-UHQZSMUD.cjs → chunk-53U53KZ2.cjs} +5 -1
  6. package/dist/chunk-53U53KZ2.cjs.map +1 -0
  7. package/dist/chunk-5VHDXPRV.mjs +240 -0
  8. package/dist/chunk-5VHDXPRV.mjs.map +1 -0
  9. package/dist/{chunk-DYPABUKC.cjs → chunk-72LTVPD2.cjs} +16 -1
  10. package/dist/chunk-72LTVPD2.cjs.map +1 -0
  11. package/dist/{chunk-COSLZ5TM.cjs → chunk-DIH3ORFA.cjs} +38 -16
  12. package/dist/chunk-DIH3ORFA.cjs.map +1 -0
  13. package/dist/chunk-FAW2C5AM.cjs +240 -0
  14. package/dist/chunk-FAW2C5AM.cjs.map +1 -0
  15. package/dist/{chunk-SGA6OZEU.mjs → chunk-NHAIL4SN.mjs} +34 -12
  16. package/dist/chunk-NHAIL4SN.mjs.map +1 -0
  17. package/dist/{chunk-4MO3HKMS.mjs → chunk-PK2PRTQW.mjs} +5 -1
  18. package/dist/chunk-PK2PRTQW.mjs.map +1 -0
  19. package/dist/{chunk-BVILILIV.mjs → chunk-PZCBUVPD.mjs} +16 -1
  20. package/dist/chunk-PZCBUVPD.mjs.map +1 -0
  21. package/dist/contract/index.cjs +5534 -305
  22. package/dist/contract/index.cjs.map +1 -1
  23. package/dist/contract/index.d.cts +68 -10
  24. package/dist/contract/index.d.ts +68 -10
  25. package/dist/contract/index.mjs +5524 -295
  26. package/dist/contract/index.mjs.map +1 -1
  27. package/dist/{dimes-client-ty6xwk0b.d.cts → dimes-client-DYFvnZUx.d.ts} +57 -10
  28. package/dist/{dimes-client-u5wLYVfp.d.ts → dimes-client-DZPhU1CG.d.cts} +57 -10
  29. package/dist/{dimes-error-5ldDx2_G.d.cts → dimes-error-BlQWPqhQ.d.cts} +2 -2
  30. package/dist/{dimes-error-D2RVknPr.d.ts → dimes-error-DBKV5bfr.d.ts} +2 -2
  31. package/dist/index.cjs +164 -12
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +151 -12
  34. package/dist/index.d.ts +151 -12
  35. package/dist/index.mjs +161 -9
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/quote-BFNgVsY-.d.ts +39 -0
  38. package/dist/quote-CanwfT9m.d.cts +39 -0
  39. package/dist/react/index.cjs +416 -18
  40. package/dist/react/index.cjs.map +1 -1
  41. package/dist/react/index.d.cts +165 -8
  42. package/dist/react/index.d.ts +165 -8
  43. package/dist/react/index.mjs +414 -16
  44. package/dist/react/index.mjs.map +1 -1
  45. package/dist/{types-CM14Dx5b.d.cts → types-ClHQbIcY.d.ts} +3 -3
  46. package/dist/{types-CVcrVq0A.d.ts → types-Co-2bQSi.d.cts} +3 -3
  47. package/dist/ws/index.cjs +4 -230
  48. package/dist/ws/index.cjs.map +1 -1
  49. package/dist/ws/index.d.cts +3 -3
  50. package/dist/ws/index.d.ts +3 -3
  51. package/dist/ws/index.mjs +5 -231
  52. package/dist/ws/index.mjs.map +1 -1
  53. package/package.json +43 -4
  54. package/dist/chunk-4MO3HKMS.mjs.map +0 -1
  55. package/dist/chunk-BVILILIV.mjs.map +0 -1
  56. package/dist/chunk-COSLZ5TM.cjs.map +0 -1
  57. package/dist/chunk-DYPABUKC.cjs.map +0 -1
  58. package/dist/chunk-SGA6OZEU.mjs.map +0 -1
  59. package/dist/chunk-UHQZSMUD.cjs.map +0 -1
  60. package/dist/quote-DoRJUXld.d.cts +0 -30
  61. package/dist/quote-GCNVcEoo.d.ts +0 -30
@@ -71,6 +71,7 @@ function formatPipsUsd(value) {
71
71
  }
72
72
 
73
73
  // src/errors/error-messages.ts
74
+ var minFillBpsMaxForMessage = 5e3;
74
75
  var friendlyByCode = {
75
76
  invalid_evm_address: "Invalid EVM address.",
76
77
  invalid_solana_address: "Invalid Solana address.",
@@ -237,6 +238,20 @@ var friendlyByCode = {
237
238
  const tolerance = formatBpsPct(getParam(params, "minTolerancePctBps"));
238
239
  return tolerance ? `Liquidation price is too close to entry (minimum buffer ${tolerance}). Reduce leverage.` : "Liquidation price is not viable at this leverage. Reduce leverage.";
239
240
  },
241
+ quote_min_fill_bps_requires_fak: "Partial-fill request was malformed. Please re-quote.",
242
+ quote_min_fill_bps_out_of_range: "Minimum fill must be between 20% and 50%.",
243
+ quote_min_fill_bps_step_invalid: "Minimum fill must be set in 5% steps.",
244
+ quote_min_fill_bps_below_floor: (params) => {
245
+ const floorRaw = getParam(params, "floorMinFillBps");
246
+ const floorPct = formatBpsPct(floorRaw);
247
+ const limit = getParam(params, "boundBy") === "notional" ? "minimum order size" : "minimum collateral";
248
+ const floorBeyondMax = typeof floorRaw === "number" && floorRaw > minFillBpsMaxForMessage;
249
+ if (floorBeyondMax || !floorPct) {
250
+ return `This trade is too small for a partial fill without falling below the ${limit}. Increase your trade size, or turn off partial fill to open atomically.`;
251
+ }
252
+ return `This trade is too small for that minimum fill \u2014 a partial fill could fall below the ${limit}. Raise the minimum fill to at least ${floorPct}, or increase your trade size.`;
253
+ },
254
+ quote_fak_order_type_disabled: "Partial fills are temporarily unavailable. Turn off partial fill to continue.",
240
255
  quote_market_not_active: "Market is not active.",
241
256
  quote_market_not_eligible: "Market is not eligible for leveraged trading.",
242
257
  quote_market_not_ready: "Market is not ready yet. Try again shortly.",
@@ -322,4 +337,4 @@ var DimesContractError = class extends DimesError {
322
337
 
323
338
 
324
339
  exports.resolveFriendlyMessage = resolveFriendlyMessage; exports.formatErrorMessage = formatErrorMessage; exports.DimesError = DimesError; exports.DimesApiError = DimesApiError; exports.DimesContractError = DimesContractError;
325
- //# sourceMappingURL=chunk-DYPABUKC.cjs.map
340
+ //# sourceMappingURL=chunk-72LTVPD2.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/alexemery/bl/dimes-sdk/dist/chunk-72LTVPD2.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,QAAA,EAAU;AAC7B,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,GAAA,CAAI,OAAO,MAAA,IAAU,SAAA,GAAY,SAAA,CAAU,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,CAAC,CAAA,EAAG;AAC7D,IAAA,OAAO,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,CAAC,CAAA;AAAA,EAC5B;AACA,EAAA,GAAA,CAAI,OAAO,MAAA,IAAU,SAAA,GAAY,MAAA,CAAO,SAAA,CAAU,KAAK,CAAA,EAAG;AACxD,IAAA,OAAO,MAAA,CAAO,KAAK,CAAA;AAAA,EACrB;AACA,EAAA,OAAO,IAAA;AACT;AAEO,SAAS,QAAA,CAAS,MAAA,EAAgB,GAAA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ACQ,IAAA;AACA,IAAA;AACF,IAAA;AACF,MAAA;AACF,IAAA;AACI,IAAA;AACF,MAAA;AACF,IAAA;AACA,IAAA;AACF,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACQ,IAAA;AACN,IAAA;AAGF,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACQ,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,IAAA;AACF,MAAA;AACF,IAAA;AACA,IAAA;AACF,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AAEA,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACF;AAES;AACD,EAAA;AACC,EAAA;AACT;AAEgB;AACR,EAAA;AACF,EAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAEgB;AACP,EAAA;AACT;AH8BU;AACA;AIxSG;AACK,EAAA;AAEhB,EAAA;AACQ,IAAA;AACD,IAAA;AACA,IAAA;AACP,EAAA;AACF;AAEa;AACK,EAAA;AAEA,EAAA;AAEA,EAAA;AAEA,EAAA;AAEA,EAAA;AAEhB,EAAA;AAQQ,IAAA;AACA,IAAA;AACD,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACP,EAAA;AACF;AAEa;AACX,EAAA;AACQ,IAAA;AACD,IAAA;AACP,EAAA;AACF;AJ2RU;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/alexemery/bl/dimes-sdk/dist/chunk-72LTVPD2.cjs","sourcesContent":[null,"export type Params = Record<string, unknown> | null;\n\nexport function asNumber(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) {\n return parsed;\n }\n }\n return null;\n}\n\nexport function asBigInt(value: unknown): bigint | null {\n if (typeof value === \"bigint\") {\n return value;\n }\n if (typeof value === \"string\" && /^-?\\d+$/.test(value.trim())) {\n return BigInt(value.trim());\n }\n if (typeof value === \"number\" && Number.isInteger(value)) {\n return BigInt(value);\n }\n return null;\n}\n\nexport function getParam(params: Params, key: string): unknown {\n return params ? params[key] : undefined;\n}\n","import { asNumber, asBigInt } from \"./parse\";\n\nconst BPS_PER_UNIT = 10_000;\nconst BPS_PER_PCT = 100;\nconst FRACTION_TO_PCT = 100;\nconst PIPS_PER_USD = 1_000_000n;\nconst ROUNDING_OFFSET = 5_000n;\nconst CENTS_DIVISOR = 10_000n;\nconst CENTS_PAD = 2;\n\nexport function formatLeverage(value: unknown): string | null {\n const n = asNumber(value);\n if (n === null) {\n return null;\n }\n return `${(n / BPS_PER_UNIT).toLocaleString(undefined, { maximumFractionDigits: 2 })}x`;\n}\n\nexport function formatBpsPct(value: unknown): string | null {\n const n = asNumber(value);\n if (n === null) {\n return null;\n }\n return `${(n / BPS_PER_PCT).toLocaleString(undefined, { maximumFractionDigits: 2 })}%`;\n}\n\nexport function formatFractionPct(value: unknown): string | null {\n const n = asNumber(value);\n if (n === null) {\n return null;\n }\n return `${(n * FRACTION_TO_PCT).toLocaleString(undefined, { maximumFractionDigits: 1 })}%`;\n}\n\nexport function formatPipsUsd(value: unknown): string | null {\n const big = asBigInt(value);\n if (big === null) {\n return null;\n }\n const negative = big < 0n;\n const absUnits = negative ? -big : big;\n const whole = absUnits / PIPS_PER_USD;\n const frac = absUnits % PIPS_PER_USD;\n const cents = (frac + ROUNDING_OFFSET) / CENTS_DIVISOR;\n const formatted = `$${whole.toLocaleString()}.${cents.toString().padStart(CENTS_PAD, \"0\")}`;\n return negative ? `-${formatted}` : formatted;\n}\n","import { formatLeverage, formatBpsPct, formatFractionPct, formatPipsUsd } from \"../utils/format\";\nimport { type Params, getParam } from \"../utils/parse\";\n\ntype FriendlyEntry = string | ((params: Params) => string);\n\nconst minFillBpsMaxForMessage = 5_000;\n\nconst friendlyByCode: Record<string, FriendlyEntry> = {\n invalid_evm_address: \"Invalid EVM address.\",\n invalid_solana_address: \"Invalid Solana address.\",\n invalid_string_for_chain_address: \"Invalid wallet address for the selected chain.\",\n invalid_wallet_address: \"Invalid wallet address.\",\n customer_auth_invalid_wallet_address: \"Invalid wallet address.\",\n\n unauthorized: \"Session expired. Please reconnect your wallet.\",\n forbidden: \"You do not have access to this resource.\",\n\n array_out_of_bounds: \"Internal indexing error. Please try again.\",\n batch_compute_not_available: \"Cached pricing is temporarily unavailable. Try again shortly.\",\n internal_server_error: \"Something went wrong on our side. Please try again.\",\n unexpected_error: \"Something went wrong. Please try again.\",\n provider_not_available: \"Upstream provider is unavailable. Try again shortly.\",\n request_already_in_progress: \"A previous request is still in flight. Wait for it to complete and try again.\",\n math_error: \"A numeric calculation failed. Please try again.\",\n invalid_number: \"Invalid numeric value in request.\",\n invalid_message: \"Received an invalid upstream message.\",\n invalid_filter_combination: \"That combination of filters is not supported.\",\n\n cancel_position_delay_not_elapsed: \"Cancel delay has not elapsed yet. Try again shortly.\",\n cancel_position_transaction_failed: \"Cancel transaction failed on-chain.\",\n cancel_position_not_found: \"Position not found.\",\n cancel_position_not_in_created_state: \"This position can only be cancelled before it has filled.\",\n cancel_position_not_on_polygon: \"Cancel is only supported for Polygon positions.\",\n customer_cancel_position_evm_only: \"Cancel is only supported for EVM positions.\",\n customer_cancel_position_not_cancellable: \"This position can no longer be cancelled.\",\n customer_cancel_position_not_owner: \"You do not own this position.\",\n customer_cancel_position_not_found: \"Position not found.\",\n\n circuit_breaker_price_divergence_tripped: \"Trading is temporarily paused due to price divergence. Try again shortly.\",\n\n customer_market_not_found: \"Market not found.\",\n customer_position_not_found: \"Position not found.\",\n customer_position_transactions_not_found: \"Position not found.\",\n\n close_position_transaction_failed: \"Close transaction failed on-chain.\",\n close_position_transaction_not_found: \"Close transaction not found.\",\n finalize_close_transaction_failed: \"Finalising the close transaction failed.\",\n close_no_open_position_transaction: \"No open transaction found for this position.\",\n close_no_request_close_transaction: \"No close request found for this position.\",\n close_polymarket_order_failed: \"Polymarket close order failed.\",\n close_polymarket_order_retry_failed: \"Polymarket close order failed after retries.\",\n close_position_already_closed: \"This position is already closed.\",\n close_position_has_no_tokens: \"This position has no tokens to close.\",\n close_position_not_found: \"Position not found.\",\n close_position_not_originated: \"Position has not been originated yet — nothing to close.\",\n\n exchange_order_submission_locked: \"Order submission is temporarily locked. Try again shortly.\",\n\n quote_partner_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `Partner position limit reached. Remaining capacity: ${available}.`\n : \"Partner position limit reached. Try a smaller size.\";\n },\n quote_user_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `You have reached your position limit on this market. Remaining capacity: ${available}.`\n : \"You have reached your position limit on this market.\";\n },\n quote_market_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `This market has reached its open-interest cap. Remaining capacity: ${available}.`\n : \"This market has reached its open-interest cap. Try a smaller size or another market.\";\n },\n quote_global_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `Global position limit reached. Remaining capacity: ${available}.`\n : \"Global position limit reached. Try again shortly.\";\n },\n quote_side_position_limit_exceeded: (params) => {\n const available = formatPipsUsd(getParam(params, \"availableCapacityUsdPips\"));\n return available\n ? `This side of the market is at its position limit. Remaining capacity: ${available}.`\n : \"This side of the market is at its position limit. Try the other side or a smaller size.\";\n },\n quote_side_capacity_exceeded: (params) => {\n const maxCollateral = formatPipsUsd(getParam(params, \"maxSupportedCollateralUsdPips\"));\n return maxCollateral\n ? `Not enough capacity on this side of the market. Max supported collateral at this size: ${maxCollateral}.`\n : \"Not enough capacity on this side of the market for that size.\";\n },\n quote_position_limit_exceeded: \"Position limit reached for this request.\",\n\n quote_insufficient_liquidity: \"Not enough liquidity on the order book to fill this size.\",\n quote_slippage_too_high: (params) => {\n const max = formatBpsPct(getParam(params, \"maxSlippageBps\"));\n const current = formatBpsPct(getParam(params, \"currentSlippageBps\"));\n if (max && current) {\n return `Required slippage ${current} exceeds your tolerance (${max}). Reduce size or raise tolerance.`;\n }\n if (max) {\n return `Required slippage exceeds your tolerance (${max}). Reduce size or raise tolerance.`;\n }\n return \"Price would move too far to fill this order. Reduce size or raise your slippage tolerance.\";\n },\n quote_event_not_started: \"This event has not started yet. Trading opens at the scheduled start time.\",\n quote_entry_bid_depth_too_low: \"Order book depth on the entry side is too thin to open this position safely.\",\n quote_entry_capacity_exceeded: \"Entry size exceeds the market's available capacity.\",\n quote_entry_depth_too_low: \"Order book depth is too thin to open this position safely.\",\n quote_entry_spread_too_wide: \"Bid/ask spread is too wide to open right now. Try again shortly.\",\n quote_entry_order_book_stale: \"Order book data is stale. Refresh and try again.\",\n quote_entry_price_stale: \"Price data is stale. Refresh and try again.\",\n quote_entry_crypto_price_stale: \"Crypto price data is stale. Refresh and try again.\",\n quote_entry_sport_data_stale: \"Sport event data is stale. Refresh and try again.\",\n quote_entry_volume_too_low: \"Recent traded volume on this market is too low to open new positions.\",\n quote_entry_top_holder_too_high: \"A single trader holds too much of this market. Opening here is restricted.\",\n quote_entry_price_out_of_range: \"Current price is outside the range we can open at. Try again shortly.\",\n quote_entry_exit_drop_too_high: \"Exit liquidity is too thin to safely open this size.\",\n quote_entry_market_too_elapsed: (params) => {\n const elapsed = formatFractionPct(getParam(params, \"pctElapsed\"));\n const max = formatFractionPct(getParam(params, \"maxPctElapsed\"));\n if (elapsed && max) {\n return `Market is ${elapsed} elapsed (max ${max}). Too close to resolution to open new positions.`;\n }\n return \"Market is too close to resolution to open new positions.\";\n },\n quote_entry_excluded_market_type: \"This market type is not supported for leveraged positions.\",\n quote_entry_excluded_sport: \"This sport is not supported for leveraged positions.\",\n quote_price_too_low: \"Underlying price is too low to open a leveraged position.\",\n quote_open_interest_unavailable: \"Open-interest data is unavailable right now. Try again shortly.\",\n\n quote_leverage_below_minimum: (params) => {\n const min = formatLeverage(getParam(params, \"minLeverageBps\"));\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n if (min && current) {\n return `Leverage ${current} is below the minimum allowed (${min}).`;\n }\n if (min) {\n return `Leverage is below the minimum allowed (${min}).`;\n }\n return \"Leverage is below the minimum allowed for this market.\";\n },\n quote_leverage_exceeds_maximum: (params) => {\n const max = formatLeverage(getParam(params, \"maxLeverageBps\"));\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n if (max && current) {\n return `Leverage ${current} is above the maximum allowed (${max}).`;\n }\n if (max) {\n return `Leverage is above the maximum allowed (${max}).`;\n }\n return \"Leverage is above the maximum allowed for this market.\";\n },\n quote_leverage_exceeds_collateral_floor: (params) => {\n const min = formatPipsUsd(getParam(params, \"minCollateralUsdPips\"));\n const current = formatPipsUsd(getParam(params, \"currentCollateralUsdPips\"));\n if (min && current) {\n return `Collateral ${current} is below the minimum ${min} required at this leverage. Raise collateral to at least ${min}.`;\n }\n if (min) {\n return `Collateral is below the minimum ${min} required at this leverage. Raise collateral to at least ${min}.`;\n }\n return \"Collateral is below the minimum required at this leverage. Raise collateral.\";\n },\n quote_leverage_exceeds_model_max: (params) => {\n const max = formatLeverage(getParam(params, \"maxLeverageBps\"));\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n if (max && current) {\n return `Leverage ${current} exceeds the risk-model limit (${max}) for this market.`;\n }\n if (max) {\n return `Leverage exceeds the risk-model limit (${max}) for this market.`;\n }\n return \"Leverage exceeds the risk-model limit for this market.\";\n },\n quote_leverage_too_high_for_price: (params) => {\n const current = formatLeverage(getParam(params, \"currentLeverageBps\"));\n const max = formatLeverage(getParam(params, \"maxAcceptableLeverageBps\"));\n if (current && max) {\n return `Leverage ${current} is too high for the current price. Maximum is ${max}.`;\n }\n if (current) {\n return `Leverage ${current} is too high for the current price. Reduce leverage.`;\n }\n return \"Leverage is too high for the current price. Reduce leverage.\";\n },\n quote_trading_window_closing: \"Trading window is closing. Reduce leverage.\",\n quote_hard_exit_too_close: \"Trading window is closing. Reduce leverage.\",\n quote_liquidation_not_viable: (params) => {\n const tolerance = formatBpsPct(getParam(params, \"minTolerancePctBps\"));\n return tolerance\n ? `Liquidation price is too close to entry (minimum buffer ${tolerance}). Reduce leverage.`\n : \"Liquidation price is not viable at this leverage. Reduce leverage.\";\n },\n\n quote_min_fill_bps_requires_fak: \"Partial-fill request was malformed. Please re-quote.\",\n quote_min_fill_bps_out_of_range: \"Minimum fill must be between 20% and 50%.\",\n quote_min_fill_bps_step_invalid: \"Minimum fill must be set in 5% steps.\",\n quote_min_fill_bps_below_floor: (params) => {\n const floorRaw = getParam(params, \"floorMinFillBps\");\n const floorPct = formatBpsPct(floorRaw);\n const limit = getParam(params, \"boundBy\") === \"notional\" ? \"minimum order size\" : \"minimum collateral\";\n const floorBeyondMax = typeof floorRaw === \"number\" && floorRaw > minFillBpsMaxForMessage;\n if (floorBeyondMax || !floorPct) {\n return `This trade is too small for a partial fill without falling below the ${limit}. Increase your trade size, or turn off partial fill to open atomically.`;\n }\n return `This trade is too small for that minimum fill — a partial fill could fall below the ${limit}. Raise the minimum fill to at least ${floorPct}, or increase your trade size.`;\n },\n quote_fak_order_type_disabled: \"Partial fills are temporarily unavailable. Turn off partial fill to continue.\",\n\n quote_market_not_active: \"Market is not active.\",\n quote_market_not_eligible: \"Market is not eligible for leveraged trading.\",\n quote_market_not_ready: \"Market is not ready yet. Try again shortly.\",\n quote_market_not_found: \"Market not found.\",\n quote_market_risk_too_high: \"Market risk is too high right now. Try again later.\",\n quote_market_unsupported_category: \"This market category is not supported.\",\n quote_market_no_prices: \"No price data available for this market.\",\n quote_market_missing_polymarket_condition_id: \"This market is missing required Polymarket data.\",\n\n quote_polymarket_market_closed: \"This Polymarket market is closed and not accepting new positions.\",\n quote_polymarket_market_inactive: \"This Polymarket market is inactive and not accepting new positions.\",\n quote_polymarket_market_not_accepting_orders:\n \"Polymarket is not accepting orders on this market right now. Try again shortly or pick another market.\",\n quote_polymarket_missing_token: \"This Polymarket market is missing a tradable outcome token.\",\n quote_invalid_polymarket_wallet_address: \"Invalid Polymarket wallet address.\",\n quote_invalid_kalshi_wallet_address: \"Invalid Kalshi wallet address.\",\n\n kalshi_quote_market_closed: \"This Kalshi market is closed.\",\n\n quote_draft_not_found: \"This quote has expired or does not exist. Please request a new quote.\",\n\n quote_twap_data_stale: \"Reference price (TWAP) is stale. Try again shortly.\",\n quote_twap_data_unavailable: \"Reference price (TWAP) is unavailable for this market.\",\n quote_revision_required: \"Quote needs to be refreshed before submitting.\",\n quote_price_provider_not_found: \"No price provider configured for this market.\",\n\n notional_selector_insufficient_liquidity: \"Not enough liquidity 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,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } 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
3
 
4
- var _chunkDYPABUKCcjs = require('./chunk-DYPABUKC.cjs');
4
+ var _chunk72LTVPD2cjs = require('./chunk-72LTVPD2.cjs');
5
5
 
6
6
  // src/quote/build-quote-params.ts
7
7
  var DEFAULT_LEVERAGE_STEP_BPS = 2500;
@@ -13,7 +13,9 @@ function buildQuoteParams(params, stepBps = DEFAULT_LEVERAGE_STEP_BPS) {
13
13
  effectiveSide: params.side,
14
14
  leverageBps,
15
15
  notionalAmountUsdPips: notionalUsdPips.toString(),
16
- slippageBps: params.slippageBps
16
+ slippageBps: params.slippageBps,
17
+ ...params.allowPartialFill !== void 0 ? { allowPartialFill: params.allowPartialFill } : {},
18
+ ...params.minFillBps !== void 0 ? { minFillBps: params.minFillBps } : {}
17
19
  };
18
20
  }
19
21
 
@@ -21,6 +23,7 @@ function buildQuoteParams(params, stepBps = DEFAULT_LEVERAGE_STEP_BPS) {
21
23
  var pipsPerUsd = 1e4;
22
24
  var bpsPerUnit = 1e4;
23
25
  var bpsPerPct = 100;
26
+ var minFillBpsMax = 5e3;
24
27
  var centsFactor = 100;
25
28
  var decimalPlaces = 2;
26
29
  var marketMovedCodes = /* @__PURE__ */ new Set([
@@ -118,6 +121,13 @@ function quoteErrorHint(code, params, context) {
118
121
  }
119
122
  return { kind: "raise-leverage", minLeverageBps };
120
123
  }
124
+ case "quote_min_fill_bps_below_floor": {
125
+ const floorMinFillBps = num(params, "floorMinFillBps");
126
+ if (floorMinFillBps === null || floorMinFillBps > minFillBpsMax) {
127
+ return null;
128
+ }
129
+ return { kind: "raise-min-fill", minFillBps: floorMinFillBps };
130
+ }
121
131
  case "quote_slippage_too_high": {
122
132
  const currentSlippageBps = num(params, "currentSlippageBps");
123
133
  const maxSlippageBps = num(params, "maxSlippageBps");
@@ -200,6 +210,14 @@ function hintAdjustment(hint, current) {
200
210
  toLabel: `${(hint.maxSlippageBps / bpsPerPct).toFixed(decimalPlaces).replace(/\.?0+$/, "")}%`,
201
211
  reason: "raise-slippage"
202
212
  };
213
+ case "raise-min-fill":
214
+ return {
215
+ field: "minFill",
216
+ fromValue: _nullishCoalesce(current.minFillBps, () => ( 0)),
217
+ toValue: hint.minFillBps,
218
+ toLabel: `${(hint.minFillBps / bpsPerPct).toFixed(decimalPlaces).replace(/\.?0+$/, "")}%`,
219
+ reason: "raise-min-fill"
220
+ };
203
221
  default:
204
222
  return null;
205
223
  }
@@ -208,7 +226,7 @@ function hintAdjustment(hint, current) {
208
226
  // src/quote/quote.ts
209
227
  var DEFAULT_MAX_RETRIES = 3;
210
228
  function isMarketMovedError(err) {
211
- return err instanceof _chunkDYPABUKCcjs.DimesApiError && marketMovedCodes.has(err.code);
229
+ return err instanceof _chunk72LTVPD2cjs.DimesApiError && marketMovedCodes.has(err.code);
212
230
  }
213
231
  function applyAdjustment(params, adj, currentParams) {
214
232
  switch (adj.field) {
@@ -226,6 +244,8 @@ function applyAdjustment(params, adj, currentParams) {
226
244
  }
227
245
  case "slippage":
228
246
  return { ...params, slippageBps: adj.toValue };
247
+ case "minFill":
248
+ return { ...params, allowPartialFill: true, minFillBps: adj.toValue };
229
249
  default:
230
250
  return params;
231
251
  }
@@ -234,7 +254,7 @@ function handleMarketMoved(err, attempt, maxRetries) {
234
254
  return isMarketMovedError(err) && attempt < maxRetries;
235
255
  }
236
256
  function handleCorrection(err, currentParams) {
237
- if (!(err instanceof _chunkDYPABUKCcjs.DimesApiError)) {
257
+ if (!(err instanceof _chunk72LTVPD2cjs.DimesApiError)) {
238
258
  return null;
239
259
  }
240
260
  const hint = quoteErrorHint(err.code, err.params, {
@@ -243,7 +263,8 @@ function handleCorrection(err, currentParams) {
243
263
  const adj = hintAdjustment(hint, {
244
264
  collateralUsd: currentParams.collateralUsd,
245
265
  leverageBps: currentParams.leverageBps,
246
- slippageBps: currentParams.slippageBps
266
+ slippageBps: currentParams.slippageBps,
267
+ minFillBps: currentParams.minFillBps
247
268
  });
248
269
  if (!adj) {
249
270
  return null;
@@ -255,18 +276,18 @@ async function executeQuote(client, params, options) {
255
276
  const autoCorrect = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _2 => _2.autoCorrect]), () => ( true));
256
277
  const corrections = [];
257
278
  let retries = 0;
258
- let offerParams = buildQuoteParams(params);
279
+ let quoteParams = buildQuoteParams(params);
259
280
  const currentParams = { ...params };
260
- const draft = await client.createDraftQuote(offerParams);
281
+ const draft = await client.createDraftQuote(quoteParams);
261
282
  _optionalChain([options, 'optionalAccess', _3 => _3.onDraftReady, 'optionalCall', _4 => _4(draft)]);
262
283
  let currentDraft = draft;
263
284
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
264
285
  try {
265
- const promotedOffer = await client.promoteDraftQuote(currentDraft.id);
266
- return { offer: promotedOffer, corrections, retries };
286
+ const promotedQuote = await client.promoteDraftQuote(currentDraft.id);
287
+ return { quote: promotedQuote, offer: promotedQuote, corrections, retries };
267
288
  } catch (err) {
268
289
  if (handleMarketMoved(err, attempt, maxRetries)) {
269
- const newDraft = await client.createDraftQuote(offerParams);
290
+ const newDraft = await client.createDraftQuote(quoteParams);
270
291
  retries++;
271
292
  const callbackResult = _optionalChain([options, 'optionalAccess', _5 => _5.onMarketMoved, 'optionalCall', _6 => _6({
272
293
  originalDraft: currentDraft,
@@ -286,16 +307,16 @@ async function executeQuote(client, params, options) {
286
307
  if (callbackResult === false) {
287
308
  throw err;
288
309
  }
289
- offerParams = applyAdjustment(offerParams, correction.adj, currentParams);
310
+ quoteParams = applyAdjustment(quoteParams, correction.adj, currentParams);
290
311
  corrections.push(correction.adj);
291
- const correctedOffer = await client.createQuote(offerParams);
292
- return { offer: correctedOffer, corrections, retries };
312
+ const correctedQuote = await client.createQuote(quoteParams);
313
+ return { quote: correctedQuote, offer: correctedQuote, corrections, retries };
293
314
  }
294
315
  }
295
316
  throw err;
296
317
  }
297
318
  }
298
- throw new (0, _chunkDYPABUKCcjs.DimesError)("market_moved_retries_exhausted", "Exhausted market-moved retries");
319
+ throw new (0, _chunk72LTVPD2cjs.DimesError)("market_moved_retries_exhausted", "Exhausted market-moved retries");
299
320
  }
300
321
 
301
322
 
@@ -304,5 +325,6 @@ async function executeQuote(client, params, options) {
304
325
 
305
326
 
306
327
 
307
- exports.buildQuoteParams = buildQuoteParams; exports.marketMovedCodes = marketMovedCodes; exports.quoteErrorHint = quoteErrorHint; exports.hintAdjustment = hintAdjustment; exports.executeQuote = executeQuote;
308
- //# sourceMappingURL=chunk-COSLZ5TM.cjs.map
328
+
329
+ exports.buildQuoteParams = buildQuoteParams; exports.marketMovedCodes = marketMovedCodes; exports.quoteErrorHint = quoteErrorHint; exports.hintAdjustment = hintAdjustment; exports.isMarketMovedError = isMarketMovedError; exports.executeQuote = executeQuote;
330
+ //# sourceMappingURL=chunk-DIH3ORFA.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/alexemery/bl/dimes-sdk/dist/chunk-DIH3ORFA.cjs","../src/quote/build-quote-params.ts","../src/quote/quote-error-hints.ts","../src/quote/quote.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACFA,IAAM,0BAAA,EAA4B,IAAA;AAE3B,SAAS,gBAAA,CAAiB,MAAA,EAAqB,QAAA,EAAkB,yBAAA,EAA8C;AACpH,EAAA,MAAM,YAAA,EAAc,IAAA,CAAK,KAAA,CAAM,MAAA,CAAO,YAAA,EAAc,OAAO,EAAA,EAAI,OAAA;AAC/D,EAAA,MAAM,gBAAA,EAAkB,IAAA,CAAK,KAAA,CAAM,MAAA,CAAO,cAAA,EAAgB,WAAW,CAAA;AAErE,EAAA,OAAO;AAAA,IACL,YAAA,EAAc,MAAA,CAAO,YAAA;AAAA,IACrB,aAAA,EAAe,MAAA,CAAO,IAAA;AAAA,IACtB,WAAA;AAAA,IACA,qBAAA,EAAuB,eAAA,CAAgB,QAAA,CAAS,CAAA;AAAA,IAChD,WAAA,EAAa,MAAA,CAAO,WAAA;AAAA,IACpB,GAAI,MAAA,CAAO,iBAAA,IAAqB,KAAA,EAAA,EAAY,EAAE,gBAAA,EAAkB,MAAA,CAAO,iBAAiB,EAAA,EAAI,CAAC,CAAA;AAAA,IAC7F,GAAI,MAAA,CAAO,WAAA,IAAe,KAAA,EAAA,EAAY,EAAE,UAAA,EAAY,MAAA,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,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACF,IAAA;AACE,MAAA;AACJ,EAAA;AACF;AFhEU;AACA;AGrNJ;AAEU;AACP,EAAA;AACT;AAES;AAKC,EAAA;AACD,IAAA;AACH,MAAA;AACA,MAAA;AACF,IAAA;AACK,IAAA;AACH,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACF,IAAA;AACK,IAAA;AACH,MAAA;AACG,IAAA;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;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;AHwLU;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/alexemery/bl/dimes-sdk/dist/chunk-DIH3ORFA.cjs","sourcesContent":[null,"import type { CreateQuoteParams } from \"../types\";\nimport type { QuoteParams } from \"../types/quote\";\n\nconst DEFAULT_LEVERAGE_STEP_BPS = 2500;\n\nexport function buildQuoteParams(params: QuoteParams, stepBps: number = DEFAULT_LEVERAGE_STEP_BPS): CreateQuoteParams {\n const leverageBps = Math.round(params.leverageBps / stepBps) * stepBps;\n const notionalUsdPips = Math.round(params.collateralUsd * leverageBps);\n\n return {\n marketTicker: params.marketTicker,\n effectiveSide: params.side,\n leverageBps,\n notionalAmountUsdPips: notionalUsdPips.toString(),\n slippageBps: params.slippageBps,\n ...(params.allowPartialFill !== undefined ? { allowPartialFill: params.allowPartialFill } : {}),\n ...(params.minFillBps !== undefined ? { minFillBps: params.minFillBps } : {}),\n };\n}\n","const pipsPerUsd = 10_000;\nconst bpsPerUnit = 10_000;\nconst bpsPerPct = 100;\nconst minFillBpsMax = 5_000;\nconst centsFactor = 100;\nconst decimalPlaces = 2;\n\nexport const marketMovedCodes = new Set([\n \"quote_slippage_too_high\",\n \"quote_insufficient_liquidity\",\n \"quote_entry_price_out_of_range\",\n \"quote_entry_bid_depth_too_low\",\n \"quote_entry_depth_too_low\",\n \"quote_entry_spread_too_wide\",\n]);\n\nexport type QuoteHint =\n | { kind: \"use-max-collateral\"; maxCollateralUsd: number; minCollateralUsd: number }\n | { kind: \"raise-collateral\"; minCollateralUsd: number }\n | { kind: \"clamp-leverage\"; maxLeverageBps?: number }\n | { kind: \"raise-leverage\"; minLeverageBps: number }\n | { kind: \"raise-slippage\"; currentSlippageBps: number; maxSlippageBps: number }\n | { kind: \"raise-min-fill\"; minFillBps: number }\n | { kind: \"market-full\" }\n | { kind: \"insufficient-liquidity\"; maxCollateralUsd: number; minCollateralUsd: number }\n | null;\n\ntype Params = Record<string, unknown> | null | undefined;\n\nfunction num(params: Params, key: string): number | null {\n if (!params) {\n return null;\n }\n const raw = params[key];\n if (raw === null || raw === undefined) {\n return null;\n }\n // eslint-disable-next-line no-restricted-syntax\n const n = typeof raw === \"string\" ? Number(raw) : typeof raw === \"number\" ? raw : NaN;\n return Number.isFinite(n) ? n : null;\n}\n\nfunction pipsToUsd(pips: number): number {\n return pips / pipsPerUsd;\n}\n\nfunction notionalPipsToCollateralUsd(notionalPips: number, leverageBps: number): number | null {\n if (!Number.isFinite(leverageBps) || leverageBps <= 0) {\n return null;\n }\n return (notionalPips * bpsPerUnit) / leverageBps / pipsPerUsd;\n}\n\nfunction buildExhaustedHint(\n exhaustedKind: \"market-full\" | \"insufficient-liquidity\",\n maxCollateralUsd: number,\n minCollateralUsd: number,\n): QuoteHint {\n if (exhaustedKind === \"insufficient-liquidity\") {\n return { kind: \"insufficient-liquidity\", maxCollateralUsd, minCollateralUsd };\n }\n return { kind: \"market-full\" };\n}\n\nfunction resolveMaxCollateralHint(\n params: Params,\n context: { leverageBps: number },\n capacityKey: string,\n exhaustedKind: \"market-full\" | \"insufficient-liquidity\",\n): QuoteHint {\n const serverMaxCollateralPips = num(params, \"maxSupportedCollateralUsdPips\");\n const capacityPips = num(params, capacityKey);\n const minNotionalPips = num(params, \"minNotionalUsdPips\");\n\n const fromServer = serverMaxCollateralPips !== null ? pipsToUsd(serverMaxCollateralPips) : null;\n const fromCapacity = capacityPips !== null ? notionalPipsToCollateralUsd(capacityPips, context.leverageBps) : null;\n const maxCollateralUsd =\n fromServer !== null && fromCapacity !== null ? Math.min(fromServer, fromCapacity) : (fromServer ?? fromCapacity);\n\n const minCollateralUsd =\n minNotionalPips !== null ? notionalPipsToCollateralUsd(minNotionalPips, context.leverageBps) : null;\n\n if (maxCollateralUsd === null || minCollateralUsd === null) {\n return null;\n }\n if (maxCollateralUsd < minCollateralUsd) {\n return buildExhaustedHint(exhaustedKind, maxCollateralUsd, minCollateralUsd);\n }\n return { kind: \"use-max-collateral\", maxCollateralUsd, minCollateralUsd };\n}\n\n// eslint-disable-next-line complexity\nexport function quoteErrorHint(code: string | null, params: Params, context: { leverageBps: number }): QuoteHint {\n if (!code) {\n return null;\n }\n\n switch (code) {\n case \"quote_side_capacity_exceeded\":\n case \"quote_user_position_limit_exceeded\":\n case \"quote_market_position_limit_exceeded\":\n case \"quote_side_position_limit_exceeded\":\n case \"quote_global_position_limit_exceeded\":\n case \"quote_partner_position_limit_exceeded\":\n return resolveMaxCollateralHint(params, context, \"availableCapacityUsdPips\", \"market-full\");\n\n case \"quote_insufficient_liquidity\":\n return resolveMaxCollateralHint(params, context, \"slippageMaxUsdPips\", \"market-full\");\n\n case \"notional_selector_insufficient_liquidity\":\n return resolveMaxCollateralHint(params, context, \"slippageMaxUsdPips\", \"insufficient-liquidity\");\n\n case \"quote_leverage_exceeds_collateral_floor\": {\n const minCollateralPips = num(params, \"minCollateralUsdPips\");\n if (minCollateralPips === null) {\n return null;\n }\n return { kind: \"raise-collateral\", minCollateralUsd: pipsToUsd(minCollateralPips) };\n }\n\n case \"quote_leverage_exceeds_maximum\":\n case \"quote_leverage_exceeds_model_max\": {\n const maxLeverageBps = num(params, \"maxLeverageBps\");\n if (maxLeverageBps === null) {\n return null;\n }\n return { kind: \"clamp-leverage\", maxLeverageBps };\n }\n\n case \"quote_leverage_too_high_for_price\": {\n const maxLeverageBps = num(params, \"maxAcceptableLeverageBps\");\n if (maxLeverageBps === null) {\n return null;\n }\n return { kind: \"clamp-leverage\", maxLeverageBps };\n }\n\n case \"quote_leverage_below_minimum\": {\n const minLeverageBps = num(params, \"minLeverageBps\");\n if (minLeverageBps === null) {\n return null;\n }\n return { kind: \"raise-leverage\", minLeverageBps };\n }\n\n case \"quote_min_fill_bps_below_floor\": {\n const floorMinFillBps = num(params, \"floorMinFillBps\");\n if (floorMinFillBps === null || floorMinFillBps > minFillBpsMax) {\n return null;\n }\n return { kind: \"raise-min-fill\", minFillBps: floorMinFillBps };\n }\n\n case \"quote_slippage_too_high\": {\n const currentSlippageBps = num(params, \"currentSlippageBps\");\n const maxSlippageBps = num(params, \"maxSlippageBps\");\n if (currentSlippageBps === null || maxSlippageBps === null) {\n return null;\n }\n return { kind: \"raise-slippage\", currentSlippageBps, maxSlippageBps };\n }\n\n default:\n return null;\n }\n}\n\nexport type CorrectedField = \"collateral\" | \"leverage\" | \"slippage\" | \"minFill\";\n\nexport type HintAdjustment =\n | {\n field: \"collateral\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"max-collateral\" | \"min-collateral\";\n }\n | {\n field: \"leverage\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"clamp-max\" | \"raise-min\";\n }\n | {\n field: \"slippage\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"raise-slippage\";\n }\n | {\n field: \"minFill\";\n fromValue: number;\n toValue: number;\n toLabel: string;\n reason: \"raise-min-fill\";\n }\n | null;\n\nfunction formatUsd(value: number): string {\n return new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n }).format(value);\n}\n\nfunction bpsToMultiplier(bps: number): string {\n return `${(bps / bpsPerUnit).toFixed(1).replace(/\\.0$/, \"\")}x`;\n}\n\n// eslint-disable-next-line complexity\nexport function hintAdjustment(\n hint: QuoteHint,\n current: { collateralUsd: number; leverageBps: number; slippageBps: number; minFillBps?: number },\n): HintAdjustment {\n if (!hint) {\n return null;\n }\n\n switch (hint.kind) {\n case \"use-max-collateral\": {\n const to = Math.max(0, Math.floor(hint.maxCollateralUsd * centsFactor) / centsFactor);\n if (to <= 0) {\n return null;\n }\n return {\n field: \"collateral\",\n fromValue: current.collateralUsd,\n toValue: to,\n toLabel: formatUsd(to),\n reason: \"max-collateral\",\n };\n }\n case \"raise-collateral\": {\n const to = Math.ceil(hint.minCollateralUsd * centsFactor) / centsFactor;\n if (to <= 0) {\n return null;\n }\n return {\n field: \"collateral\",\n fromValue: current.collateralUsd,\n toValue: to,\n toLabel: formatUsd(to),\n reason: \"min-collateral\",\n };\n }\n case \"clamp-leverage\": {\n if (hint.maxLeverageBps === undefined) {\n return null;\n }\n return {\n field: \"leverage\",\n fromValue: current.leverageBps,\n toValue: hint.maxLeverageBps,\n toLabel: bpsToMultiplier(hint.maxLeverageBps),\n reason: \"clamp-max\",\n };\n }\n case \"raise-leverage\":\n return {\n field: \"leverage\",\n fromValue: current.leverageBps,\n toValue: hint.minLeverageBps,\n toLabel: bpsToMultiplier(hint.minLeverageBps),\n reason: \"raise-min\",\n };\n case \"raise-slippage\":\n return {\n field: \"slippage\",\n fromValue: hint.currentSlippageBps,\n toValue: hint.maxSlippageBps,\n toLabel: `${(hint.maxSlippageBps / bpsPerPct).toFixed(decimalPlaces).replace(/\\.?0+$/, \"\")}%`,\n reason: \"raise-slippage\",\n };\n case \"raise-min-fill\":\n return {\n field: \"minFill\",\n fromValue: current.minFillBps ?? 0,\n toValue: hint.minFillBps,\n toLabel: `${(hint.minFillBps / bpsPerPct).toFixed(decimalPlaces).replace(/\\.?0+$/, \"\")}%`,\n reason: \"raise-min-fill\",\n };\n default:\n return null;\n }\n}\n","import { DimesApiError, DimesError } from \"../errors/dimes-error\";\nimport type { CreateQuoteParams, Quote } from \"../types\";\nimport type { QuoteOptions, QuoteParams, QuoteResult } from \"../types/quote\";\nimport { buildQuoteParams } from \"./build-quote-params\";\nimport { type HintAdjustment, hintAdjustment, marketMovedCodes, quoteErrorHint } from \"./quote-error-hints\";\n\nexport interface QuoteClient {\n createDraftQuote(params: CreateQuoteParams): Promise<Quote>;\n promoteDraftQuote(draftId: string): Promise<Quote>;\n createQuote(params: CreateQuoteParams): Promise<Quote>;\n}\n\nconst DEFAULT_MAX_RETRIES = 3;\n\nexport function isMarketMovedError(err: unknown): boolean {\n return err instanceof DimesApiError && marketMovedCodes.has(err.code);\n}\n\nfunction applyAdjustment(\n params: CreateQuoteParams,\n adj: NonNullable<HintAdjustment>,\n currentParams: QuoteParams,\n): CreateQuoteParams {\n switch (adj.field) {\n case \"collateral\": {\n const notionalUsdPips = Math.round(adj.toValue * params.leverageBps);\n return { ...params, notionalAmountUsdPips: notionalUsdPips.toString() };\n }\n case \"leverage\": {\n const notionalUsdPips = Math.round(currentParams.collateralUsd * adj.toValue);\n return {\n ...params,\n leverageBps: adj.toValue,\n notionalAmountUsdPips: notionalUsdPips.toString(),\n };\n }\n case \"slippage\":\n return { ...params, slippageBps: adj.toValue };\n case \"minFill\":\n return { ...params, allowPartialFill: true, minFillBps: adj.toValue };\n default:\n return params;\n }\n}\n\nfunction handleMarketMoved(err: unknown, attempt: number, maxRetries: number): boolean {\n return isMarketMovedError(err) && attempt < maxRetries;\n}\n\nfunction handleCorrection(err: unknown, currentParams: QuoteParams): { adj: NonNullable<HintAdjustment> } | null {\n if (!(err instanceof DimesApiError)) {\n return null;\n }\n\n const hint = quoteErrorHint(err.code, err.params, {\n leverageBps: currentParams.leverageBps,\n });\n\n const adj = hintAdjustment(hint, {\n collateralUsd: currentParams.collateralUsd,\n leverageBps: currentParams.leverageBps,\n slippageBps: currentParams.slippageBps,\n minFillBps: currentParams.minFillBps,\n });\n\n if (!adj) {\n return null;\n }\n\n return { adj };\n}\n\n// eslint-disable-next-line complexity\nexport async function executeQuote(\n client: QuoteClient,\n params: QuoteParams,\n options?: QuoteOptions,\n): Promise<QuoteResult> {\n const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n const autoCorrect = options?.autoCorrect ?? true;\n const corrections: NonNullable<HintAdjustment>[] = [];\n let retries = 0;\n\n let quoteParams = buildQuoteParams(params);\n const currentParams = { ...params };\n\n const draft = await client.createDraftQuote(quoteParams);\n options?.onDraftReady?.(draft);\n\n let currentDraft: Quote = draft;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const promotedQuote = await client.promoteDraftQuote(currentDraft.id);\n return { quote: promotedQuote, offer: promotedQuote, corrections, retries };\n } catch (err) {\n if (handleMarketMoved(err, attempt, maxRetries)) {\n const newDraft = await client.createDraftQuote(quoteParams);\n retries++;\n\n const callbackResult = options?.onMarketMoved?.({\n originalDraft: currentDraft,\n newDraft,\n retryCount: retries,\n });\n\n if (callbackResult === false) {\n throw err;\n }\n\n currentDraft = newDraft;\n continue;\n }\n\n if (autoCorrect) {\n const correction = handleCorrection(err, currentParams);\n\n if (correction) {\n const callbackResult = options?.onCorrection?.(correction.adj);\n if (callbackResult === false) {\n throw err;\n }\n\n quoteParams = applyAdjustment(quoteParams, correction.adj, currentParams);\n corrections.push(correction.adj);\n\n const correctedQuote = await client.createQuote(quoteParams);\n return { quote: correctedQuote, offer: correctedQuote, corrections, retries };\n }\n }\n\n throw err;\n }\n }\n\n throw new DimesError(\"market_moved_retries_exhausted\", \"Exhausted market-moved retries\");\n}\n"]}
@@ -0,0 +1,240 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } 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; } var _class; var _class2;
2
+
3
+
4
+ var _chunk53U53KZ2cjs = require('./chunk-53U53KZ2.cjs');
5
+
6
+ // src/ws/position-socket.ts
7
+ var _humps = require('humps');
8
+ var _socketioclient = require('socket.io-client');
9
+ var wsNamespace = "/v1/ws/prediction-markets/user-positions";
10
+ function camelizeEnvelope(envelope) {
11
+ return {
12
+ id: envelope.id,
13
+ type: envelope.type,
14
+ createdAt: envelope.created_at,
15
+ data: _humps.camelizeKeys.call(void 0, envelope.data)
16
+ };
17
+ }
18
+ var PositionSocket = (_class = class {
19
+ __init() {this.socket = null}
20
+
21
+
22
+ __init2() {this.eventListeners = /* @__PURE__ */ new Map()}
23
+ __init3() {this.connectListeners = /* @__PURE__ */ new Set()}
24
+ __init4() {this.disconnectListeners = /* @__PURE__ */ new Set()}
25
+ __init5() {this.errorListeners = /* @__PURE__ */ new Set()}
26
+ __init6() {this.notificationListeners = /* @__PURE__ */ new Set()}
27
+ constructor(options) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);_class.prototype.__init5.call(this);_class.prototype.__init6.call(this);
28
+ this.baseUrl = _nullishCoalesce(options.baseUrl, () => ( "https://api.dimes.fi"));
29
+ this.getToken = options.getToken;
30
+ }
31
+ get connected() {
32
+ return _nullishCoalesce(_optionalChain([this, 'access', _ => _.socket, 'optionalAccess', _2 => _2.connected]), () => ( false));
33
+ }
34
+ connect() {
35
+ if (_optionalChain([this, 'access', _3 => _3.socket, 'optionalAccess', _4 => _4.connected])) {
36
+ return;
37
+ }
38
+ _optionalChain([this, 'access', _5 => _5.socket, 'optionalAccess', _6 => _6.disconnect, 'call', _7 => _7()]);
39
+ const token = this.getToken();
40
+ if (!token) {
41
+ return;
42
+ }
43
+ const getToken = this.getToken;
44
+ this.socket = _socketioclient.io.call(void 0, `${this.baseUrl}${wsNamespace}`, {
45
+ auth: (cb) => cb({ token: getToken() }),
46
+ transports: ["websocket"],
47
+ reconnection: true,
48
+ reconnectionDelay: 1e3,
49
+ reconnectionDelayMax: 3e4
50
+ });
51
+ this.socket.on("connect", () => {
52
+ for (const cb of this.connectListeners) {
53
+ cb();
54
+ }
55
+ });
56
+ this.socket.on("disconnect", () => {
57
+ for (const cb of this.disconnectListeners) {
58
+ cb();
59
+ }
60
+ });
61
+ this.socket.on("error", (err) => {
62
+ for (const cb of this.errorListeners) {
63
+ cb(err);
64
+ }
65
+ });
66
+ for (const eventType of _chunk53U53KZ2cjs.positionEventTypes) {
67
+ this.socket.on(eventType, (envelope) => {
68
+ const event = camelizeEnvelope(envelope);
69
+ this.emit(eventType, event);
70
+ this.emit("*", event);
71
+ });
72
+ }
73
+ this.socket.on("notification", (envelope) => {
74
+ const event = {
75
+ id: envelope.id,
76
+ type: "notification",
77
+ createdAt: envelope.created_at,
78
+ data: envelope.data
79
+ };
80
+ for (const cb of this.notificationListeners) {
81
+ cb(event);
82
+ }
83
+ });
84
+ }
85
+ disconnect() {
86
+ _optionalChain([this, 'access', _8 => _8.socket, 'optionalAccess', _9 => _9.disconnect, 'call', _10 => _10()]);
87
+ this.socket = null;
88
+ }
89
+ reconnectWithToken() {
90
+ this.disconnect();
91
+ this.connect();
92
+ }
93
+ on(event, cb) {
94
+ let set = this.eventListeners.get(event);
95
+ if (!set) {
96
+ set = /* @__PURE__ */ new Set();
97
+ this.eventListeners.set(event, set);
98
+ }
99
+ set.add(cb);
100
+ return () => set.delete(cb);
101
+ }
102
+ onConnect(cb) {
103
+ this.connectListeners.add(cb);
104
+ return () => this.connectListeners.delete(cb);
105
+ }
106
+ onDisconnect(cb) {
107
+ this.disconnectListeners.add(cb);
108
+ return () => this.disconnectListeners.delete(cb);
109
+ }
110
+ onError(cb) {
111
+ this.errorListeners.add(cb);
112
+ return () => this.errorListeners.delete(cb);
113
+ }
114
+ onNotification(cb) {
115
+ this.notificationListeners.add(cb);
116
+ return () => this.notificationListeners.delete(cb);
117
+ }
118
+ emit(event, data) {
119
+ const set = this.eventListeners.get(event);
120
+ if (!set) {
121
+ return;
122
+ }
123
+ for (const cb of set) {
124
+ cb(data);
125
+ }
126
+ }
127
+ }, _class);
128
+
129
+ // src/ws/market-socket.ts
130
+
131
+
132
+ var wsNamespace2 = "/v1/ws/prediction-markets/user-markets";
133
+ function camelizeEnvelope2(envelope) {
134
+ return {
135
+ id: envelope.id,
136
+ type: envelope.type,
137
+ createdAt: envelope.created_at,
138
+ data: envelope.data.map((item) => _humps.camelizeKeys.call(void 0, item))
139
+ };
140
+ }
141
+ var MarketSocket = (_class2 = class {
142
+ __init7() {this.socket = null}
143
+
144
+
145
+ __init8() {this.eventListeners = /* @__PURE__ */ new Map()}
146
+ __init9() {this.connectListeners = /* @__PURE__ */ new Set()}
147
+ __init10() {this.disconnectListeners = /* @__PURE__ */ new Set()}
148
+ __init11() {this.errorListeners = /* @__PURE__ */ new Set()}
149
+ constructor(options) {;_class2.prototype.__init7.call(this);_class2.prototype.__init8.call(this);_class2.prototype.__init9.call(this);_class2.prototype.__init10.call(this);_class2.prototype.__init11.call(this);
150
+ this.baseUrl = _nullishCoalesce(options.baseUrl, () => ( "https://api.dimes.fi"));
151
+ this.getToken = options.getToken;
152
+ }
153
+ get connected() {
154
+ return _nullishCoalesce(_optionalChain([this, 'access', _11 => _11.socket, 'optionalAccess', _12 => _12.connected]), () => ( false));
155
+ }
156
+ connect() {
157
+ if (_optionalChain([this, 'access', _13 => _13.socket, 'optionalAccess', _14 => _14.connected])) {
158
+ return;
159
+ }
160
+ _optionalChain([this, 'access', _15 => _15.socket, 'optionalAccess', _16 => _16.disconnect, 'call', _17 => _17()]);
161
+ const token = this.getToken();
162
+ if (!token) {
163
+ return;
164
+ }
165
+ const getToken = this.getToken;
166
+ this.socket = _socketioclient.io.call(void 0, `${this.baseUrl}${wsNamespace2}`, {
167
+ auth: (cb) => cb({ token: getToken() }),
168
+ transports: ["websocket"],
169
+ reconnection: true,
170
+ reconnectionDelay: 1e3,
171
+ reconnectionDelayMax: 3e4
172
+ });
173
+ this.socket.on("connect", () => {
174
+ for (const cb of this.connectListeners) {
175
+ cb();
176
+ }
177
+ });
178
+ this.socket.on("disconnect", () => {
179
+ for (const cb of this.disconnectListeners) {
180
+ cb();
181
+ }
182
+ });
183
+ this.socket.on("error", (err) => {
184
+ for (const cb of this.errorListeners) {
185
+ cb(err);
186
+ }
187
+ });
188
+ for (const eventType of _chunk53U53KZ2cjs.marketEventTypes) {
189
+ this.socket.on(eventType, (envelope) => {
190
+ const event = camelizeEnvelope2(envelope);
191
+ this.emit(eventType, event);
192
+ this.emit("*", event);
193
+ });
194
+ }
195
+ }
196
+ disconnect() {
197
+ _optionalChain([this, 'access', _18 => _18.socket, 'optionalAccess', _19 => _19.disconnect, 'call', _20 => _20()]);
198
+ this.socket = null;
199
+ }
200
+ reconnectWithToken() {
201
+ this.disconnect();
202
+ this.connect();
203
+ }
204
+ on(event, cb) {
205
+ let set = this.eventListeners.get(event);
206
+ if (!set) {
207
+ set = /* @__PURE__ */ new Set();
208
+ this.eventListeners.set(event, set);
209
+ }
210
+ set.add(cb);
211
+ return () => set.delete(cb);
212
+ }
213
+ onConnect(cb) {
214
+ this.connectListeners.add(cb);
215
+ return () => this.connectListeners.delete(cb);
216
+ }
217
+ onDisconnect(cb) {
218
+ this.disconnectListeners.add(cb);
219
+ return () => this.disconnectListeners.delete(cb);
220
+ }
221
+ onError(cb) {
222
+ this.errorListeners.add(cb);
223
+ return () => this.errorListeners.delete(cb);
224
+ }
225
+ emit(event, data) {
226
+ const set = this.eventListeners.get(event);
227
+ if (!set) {
228
+ return;
229
+ }
230
+ for (const cb of set) {
231
+ cb(data);
232
+ }
233
+ }
234
+ }, _class2);
235
+
236
+
237
+
238
+
239
+ exports.PositionSocket = PositionSocket; exports.MarketSocket = MarketSocket;
240
+ //# sourceMappingURL=chunk-FAW2C5AM.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/alexemery/bl/dimes-sdk/dist/chunk-FAW2C5AM.cjs","../src/ws/position-socket.ts","../src/ws/market-socket.ts"],"names":["io","camelizeEnvelope"],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACLA,8BAA6B;AAC7B,kDAAgC;AAqBhC,IAAM,YAAA,EAAc,0CAAA;AAEpB,SAAS,gBAAA,CAAiB,QAAA,EAAgD;AACxE,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,QAAA,CAAS,EAAA;AAAA,IACb,IAAA,EAAM,QAAA,CAAS,IAAA;AAAA,IACf,SAAA,EAAW,QAAA,CAAS,UAAA;AAAA,IACpB,IAAA,EAAM,iCAAA,QAAa,CAAS,IAAI;AAAA,EAClC,CAAA;AACF;AAEO,IAAM,eAAA,YAAN,MAAqB;AAAA,iBAClB,OAAA,EAAwB,KAAA;AAAA,EAEf;AAAA,EAEA;AAAA,kBAEA,eAAA,kBAAiB,IAAI,GAAA,CAAgC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MAAA;AACD,IAAA;AAEc,IAAA;AACF,MAAA;AACH,QAAA;AACR,MAAA;AACD,IAAA;AAEU,IAAA;AACM,MAAA;AACCA,QAAAA;AACJ,QAAA;AACA,QAAA;AACX,MAAA;AACH,IAAA;AACF,EAAA;AAE0B,EAAA;AACX,oBAAA;AACC,IAAA;AAChB,EAAA;AAEO,EAAA;AACW,IAAA;AACH,IAAA;AACf,EAAA;AAEuE,EAAA;AACtD,IAAA;AACL,IAAA;AACF,MAAA;AACD,MAAA;AACP,IAAA;AACU,IAAA;AACO,IAAA;AACnB,EAAA;AAEqD,EAAA;AAC9C,IAAA;AACa,IAAA;AACpB,EAAA;AAEwD,EAAA;AACjD,IAAA;AACa,IAAA;AACpB,EAAA;AAE8C,EAAA;AACvC,IAAA;AACa,IAAA;AACpB,EAAA;AAEqD,EAAA;AAClC,IAAA;AACP,IAAA;AACR,MAAA;AACF,IAAA;AACiB,IAAA;AACR,MAAA;AACT,IAAA;AACF,EAAA;AACF;AFuFsB;AACA;AACA;AACA;AACA","file":"/Users/alexemery/bl/dimes-sdk/dist/chunk-FAW2C5AM.cjs","sourcesContent":[null,"import { camelizeKeys } from \"humps\";\nimport { io, type Socket } from \"socket.io-client\";\nimport type { Position } from \"../types\";\nimport {\n positionEventTypes,\n type NotificationEvent,\n type NotificationEventEnvelope,\n type PositionEvent,\n type PositionEventEnvelope,\n type PositionEventType,\n} from \"./types\";\n\nexport interface PositionSocketOptions {\n baseUrl?: string;\n getToken: () => string | null;\n}\n\ntype EventCallback = (event: PositionEvent) => void;\ntype NotificationCallback = (event: NotificationEvent) => void;\ntype ConnectionCallback = () => void;\ntype ErrorCallback = (error: unknown) => void;\n\nconst wsNamespace = \"/v1/ws/prediction-markets/user-positions\";\n\nfunction camelizeEnvelope(envelope: PositionEventEnvelope): PositionEvent {\n return {\n id: envelope.id,\n type: envelope.type,\n createdAt: envelope.created_at,\n data: camelizeKeys(envelope.data) as unknown as Position,\n };\n}\n\nexport class PositionSocket {\n private socket: Socket | null = null;\n\n private readonly baseUrl: string;\n\n private readonly getToken: () => string | null;\n\n private readonly eventListeners = new Map<string, Set<EventCallback>>();\n\n private readonly connectListeners = new Set<ConnectionCallback>();\n\n private readonly disconnectListeners = new Set<ConnectionCallback>();\n\n private readonly errorListeners = new Set<ErrorCallback>();\n\n private readonly notificationListeners = new Set<NotificationCallback>();\n\n constructor(options: PositionSocketOptions) {\n this.baseUrl = options.baseUrl ?? \"https://api.dimes.fi\";\n this.getToken = options.getToken;\n }\n\n public get connected(): boolean {\n return this.socket?.connected ?? false;\n }\n\n public connect(): void {\n if (this.socket?.connected) {\n return;\n }\n\n this.socket?.disconnect();\n\n const token = this.getToken();\n if (!token) {\n return;\n }\n\n const getToken = this.getToken;\n this.socket = io(`${this.baseUrl}${wsNamespace}`, {\n auth: (cb) => cb({ token: getToken() }),\n transports: [\"websocket\"],\n reconnection: true,\n reconnectionDelay: 1000,\n reconnectionDelayMax: 30000,\n });\n\n this.socket.on(\"connect\", () => {\n for (const cb of this.connectListeners) {\n cb();\n }\n });\n\n this.socket.on(\"disconnect\", () => {\n for (const cb of this.disconnectListeners) {\n cb();\n }\n });\n\n this.socket.on(\"error\", (err: unknown) => {\n for (const cb of this.errorListeners) {\n cb(err);\n }\n });\n\n for (const eventType of positionEventTypes) {\n this.socket.on(eventType, (envelope: PositionEventEnvelope) => {\n const event = camelizeEnvelope(envelope);\n this.emit(eventType, event);\n this.emit(\"*\", event);\n });\n }\n\n this.socket.on(\"notification\", (envelope: NotificationEventEnvelope) => {\n const event: NotificationEvent = {\n id: envelope.id,\n type: \"notification\",\n createdAt: envelope.created_at,\n data: envelope.data,\n };\n for (const cb of this.notificationListeners) {\n cb(event);\n }\n });\n }\n\n public disconnect(): void {\n this.socket?.disconnect();\n this.socket = null;\n }\n\n public reconnectWithToken(): void {\n this.disconnect();\n this.connect();\n }\n\n public on(event: PositionEventType | \"*\", cb: EventCallback): () => void {\n let set = this.eventListeners.get(event);\n if (!set) {\n set = new Set();\n this.eventListeners.set(event, set);\n }\n set.add(cb);\n return () => set.delete(cb);\n }\n\n public onConnect(cb: ConnectionCallback): () => void {\n this.connectListeners.add(cb);\n return () => this.connectListeners.delete(cb);\n }\n\n public onDisconnect(cb: ConnectionCallback): () => void {\n this.disconnectListeners.add(cb);\n return () => this.disconnectListeners.delete(cb);\n }\n\n public onError(cb: ErrorCallback): () => void {\n this.errorListeners.add(cb);\n return () => this.errorListeners.delete(cb);\n }\n\n public onNotification(cb: NotificationCallback): () => void {\n this.notificationListeners.add(cb);\n return () => this.notificationListeners.delete(cb);\n }\n\n private emit(event: string, data: PositionEvent): void {\n const set = this.eventListeners.get(event);\n if (!set) {\n return;\n }\n for (const cb of set) {\n cb(data);\n }\n }\n}\n","import { camelizeKeys } from \"humps\";\nimport { io, type Socket } from \"socket.io-client\";\nimport type { Market } from \"../types\";\nimport {\n marketEventTypes,\n type MarketDelta,\n type MarketEvent,\n type MarketEventEnvelope,\n type MarketEventType,\n} from \"./types\";\n\nexport interface MarketSocketOptions {\n baseUrl?: string;\n getToken: () => string | null;\n}\n\ntype EventCallback = (event: MarketEvent) => void;\ntype ConnectionCallback = () => void;\ntype ErrorCallback = (error: unknown) => void;\n\nconst wsNamespace = \"/v1/ws/prediction-markets/user-markets\";\n\nfunction camelizeEnvelope(envelope: MarketEventEnvelope): MarketEvent {\n return {\n id: envelope.id,\n type: envelope.type,\n createdAt: envelope.created_at,\n data: envelope.data.map((item) => camelizeKeys(item)) as unknown as Market[] | MarketDelta[],\n };\n}\n\nexport class MarketSocket {\n private socket: Socket | null = null;\n\n private readonly baseUrl: string;\n\n private readonly getToken: () => string | null;\n\n private readonly eventListeners = new Map<string, Set<EventCallback>>();\n\n private readonly connectListeners = new Set<ConnectionCallback>();\n\n private readonly disconnectListeners = new Set<ConnectionCallback>();\n\n private readonly errorListeners = new Set<ErrorCallback>();\n\n constructor(options: MarketSocketOptions) {\n this.baseUrl = options.baseUrl ?? \"https://api.dimes.fi\";\n this.getToken = options.getToken;\n }\n\n public get connected(): boolean {\n return this.socket?.connected ?? false;\n }\n\n public connect(): void {\n if (this.socket?.connected) {\n return;\n }\n\n this.socket?.disconnect();\n\n const token = this.getToken();\n if (!token) {\n return;\n }\n\n const getToken = this.getToken;\n this.socket = io(`${this.baseUrl}${wsNamespace}`, {\n auth: (cb) => cb({ token: getToken() }),\n transports: [\"websocket\"],\n reconnection: true,\n reconnectionDelay: 1000,\n reconnectionDelayMax: 30000,\n });\n\n this.socket.on(\"connect\", () => {\n for (const cb of this.connectListeners) {\n cb();\n }\n });\n\n this.socket.on(\"disconnect\", () => {\n for (const cb of this.disconnectListeners) {\n cb();\n }\n });\n\n this.socket.on(\"error\", (err: unknown) => {\n for (const cb of this.errorListeners) {\n cb(err);\n }\n });\n\n for (const eventType of marketEventTypes) {\n this.socket.on(eventType, (envelope: MarketEventEnvelope) => {\n const event = camelizeEnvelope(envelope);\n this.emit(eventType, event);\n this.emit(\"*\", event);\n });\n }\n }\n\n public disconnect(): void {\n this.socket?.disconnect();\n this.socket = null;\n }\n\n public reconnectWithToken(): void {\n this.disconnect();\n this.connect();\n }\n\n public on(event: MarketEventType | \"*\", cb: EventCallback): () => void {\n let set = this.eventListeners.get(event);\n if (!set) {\n set = new Set();\n this.eventListeners.set(event, set);\n }\n set.add(cb);\n return () => set.delete(cb);\n }\n\n public onConnect(cb: ConnectionCallback): () => void {\n this.connectListeners.add(cb);\n return () => this.connectListeners.delete(cb);\n }\n\n public onDisconnect(cb: ConnectionCallback): () => void {\n this.disconnectListeners.add(cb);\n return () => this.disconnectListeners.delete(cb);\n }\n\n public onError(cb: ErrorCallback): () => void {\n this.errorListeners.add(cb);\n return () => this.errorListeners.delete(cb);\n }\n\n private emit(event: string, data: MarketEvent): void {\n const set = this.eventListeners.get(event);\n if (!set) {\n return;\n }\n for (const cb of set) {\n cb(data);\n }\n }\n}\n"]}