@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
@@ -1,9 +1,17 @@
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; }
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
- var _chunkCOSLZ5TMcjs = require('../chunk-COSLZ5TM.cjs');
4
3
 
5
4
 
6
- var _chunkDYPABUKCcjs = require('../chunk-DYPABUKC.cjs');
5
+ var _chunkDIH3ORFAcjs = require('../chunk-DIH3ORFA.cjs');
6
+
7
+
8
+
9
+ var _chunk72LTVPD2cjs = require('../chunk-72LTVPD2.cjs');
10
+
11
+
12
+
13
+ var _chunkFAW2C5AMcjs = require('../chunk-FAW2C5AM.cjs');
14
+ require('../chunk-53U53KZ2.cjs');
7
15
 
8
16
  // src/react/provider.tsx
9
17
  var _react = require('react');
@@ -15,7 +23,7 @@ function DimesProvider({ client, children }) {
15
23
  function useDimesClient() {
16
24
  const client = _react.useContext.call(void 0, DimesContext);
17
25
  if (!client) {
18
- throw new (0, _chunkDYPABUKCcjs.DimesError)("missing_provider", "useDimesClient must be used within a <DimesProvider>");
26
+ throw new (0, _chunk72LTVPD2cjs.DimesError)("missing_provider", "useDimesClient must be used within a <DimesProvider>");
19
27
  }
20
28
  return client;
21
29
  }
@@ -35,7 +43,8 @@ function reducer(state, action) {
35
43
  case "done":
36
44
  return {
37
45
  phase: "promoted",
38
- offer: action.result.offer,
46
+ quote: action.result.quote,
47
+ offer: action.result.quote,
39
48
  corrections: action.result.corrections,
40
49
  retries: action.result.retries,
41
50
  draft: state.draft
@@ -59,7 +68,7 @@ function useQuote() {
59
68
  async (params, options) => {
60
69
  dispatch({ type: "loading" });
61
70
  try {
62
- const result = await _chunkCOSLZ5TMcjs.executeQuote.call(void 0, client, params, {
71
+ const result = await _chunkDIH3ORFAcjs.executeQuote.call(void 0, client, params, {
63
72
  ...options,
64
73
  onDraftReady: (draft) => {
65
74
  dispatch({ type: "draftReady", draft });
@@ -89,6 +98,125 @@ function useQuote() {
89
98
  return { state, execute, reset };
90
99
  }
91
100
 
101
+ // src/react/use-quote-machine.ts
102
+
103
+ var DEFAULT_MAX_RETRIES = 3;
104
+ function reducer2(_state, action) {
105
+ switch (action.type) {
106
+ case "loading":
107
+ return { phase: "loading-draft" };
108
+ case "draftReady":
109
+ return { phase: "draft-ready", draft: action.draft, quotedAt: action.quotedAt };
110
+ case "promoting":
111
+ return { phase: "promoting", draft: action.draft, quotedAt: action.quotedAt };
112
+ case "promoted":
113
+ return {
114
+ phase: "promoted",
115
+ draft: action.draft,
116
+ promotedQuote: action.promotedQuote,
117
+ correctedFrom: action.correctedFrom,
118
+ quotedAt: action.quotedAt
119
+ };
120
+ case "marketMoved":
121
+ return {
122
+ phase: "market-moved",
123
+ originalDraft: action.originalDraft,
124
+ newDraft: action.newDraft,
125
+ retryCount: action.retryCount,
126
+ quotedAt: action.quotedAt
127
+ };
128
+ case "error":
129
+ return { phase: "error", error: action.error, draft: action.draft };
130
+ case "reset":
131
+ return { phase: "idle" };
132
+ default:
133
+ return _state;
134
+ }
135
+ }
136
+ function useQuoteMachine(options) {
137
+ const client = useDimesClient();
138
+ const maxRetries = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _7 => _7.maxRetries]), () => ( DEFAULT_MAX_RETRIES));
139
+ const [state, dispatch] = _react.useReducer.call(void 0, reducer2, { phase: "idle" });
140
+ const lastParamsRef = _react.useRef.call(void 0, null);
141
+ const quotedAtRef = _react.useRef.call(void 0, 0);
142
+ const getDraft = _react.useCallback.call(void 0,
143
+ async (params) => {
144
+ dispatch({ type: "loading" });
145
+ const quoteParams = _chunkDIH3ORFAcjs.buildQuoteParams.call(void 0, params);
146
+ lastParamsRef.current = quoteParams;
147
+ try {
148
+ const draft = await client.createDraftQuote(quoteParams);
149
+ quotedAtRef.current = Date.now();
150
+ dispatch({ type: "draftReady", draft, quotedAt: quotedAtRef.current });
151
+ } catch (err) {
152
+ dispatch({ type: "error", error: err });
153
+ }
154
+ },
155
+ [client]
156
+ );
157
+ const promote = _react.useCallback.call(void 0,
158
+ async (draft, retryCount = 0) => {
159
+ const quotedAt = quotedAtRef.current;
160
+ dispatch({ type: "promoting", draft, quotedAt });
161
+ try {
162
+ const promotedQuote = await client.promoteDraftQuote(draft.id);
163
+ dispatch({ type: "promoted", draft, promotedQuote, quotedAt });
164
+ } catch (err) {
165
+ if (_chunkDIH3ORFAcjs.isMarketMovedError.call(void 0, err) && retryCount < maxRetries && lastParamsRef.current) {
166
+ try {
167
+ const newDraft = await client.createDraftQuote(lastParamsRef.current);
168
+ quotedAtRef.current = Date.now();
169
+ dispatch({
170
+ type: "marketMoved",
171
+ originalDraft: draft,
172
+ newDraft,
173
+ retryCount: retryCount + 1,
174
+ quotedAt: quotedAtRef.current
175
+ });
176
+ } catch (draftErr) {
177
+ dispatch({ type: "error", error: draftErr, draft });
178
+ }
179
+ } else {
180
+ dispatch({ type: "error", error: err, draft });
181
+ }
182
+ }
183
+ },
184
+ [client, maxRetries]
185
+ );
186
+ const acceptChanges = _react.useCallback.call(void 0,
187
+ async (newDraft, retryCount) => {
188
+ await promote(newDraft, retryCount);
189
+ },
190
+ [promote]
191
+ );
192
+ const correctAndPromote = _react.useCallback.call(void 0,
193
+ async (originalDraft, adjustedParams) => {
194
+ dispatch({ type: "promoting", draft: originalDraft, quotedAt: quotedAtRef.current });
195
+ lastParamsRef.current = adjustedParams;
196
+ try {
197
+ const promotedQuote = await client.createQuote(adjustedParams);
198
+ quotedAtRef.current = Date.now();
199
+ dispatch({
200
+ type: "promoted",
201
+ draft: promotedQuote,
202
+ promotedQuote,
203
+ correctedFrom: originalDraft,
204
+ quotedAt: quotedAtRef.current
205
+ });
206
+ } catch (err) {
207
+ dispatch({ type: "error", error: err });
208
+ }
209
+ },
210
+ [client]
211
+ );
212
+ const reset = _react.useCallback.call(void 0, () => {
213
+ dispatch({ type: "reset" });
214
+ lastParamsRef.current = null;
215
+ quotedAtRef.current = 0;
216
+ }, []);
217
+ return { state, getDraft, promote, acceptChanges, correctAndPromote, reset };
218
+ }
219
+
92
220
  // src/react/use-markets.ts
93
221
  var _reactquery = require('@tanstack/react-query');
94
222
  function useMarkets(params, queryOptions) {
@@ -99,6 +227,15 @@ function useMarkets(params, queryOptions) {
99
227
  ...queryOptions
100
228
  });
101
229
  }
230
+ function useSearchMarkets(params, queryOptions) {
231
+ const client = useDimesClient();
232
+ return _reactquery.useQuery.call(void 0, {
233
+ queryKey: ["dimes", "markets", "search", params],
234
+ queryFn: () => client.searchMarkets(params),
235
+ enabled: !!params.query,
236
+ ...queryOptions
237
+ });
238
+ }
102
239
  function useMarket(ticker, queryOptions) {
103
240
  const client = useDimesClient();
104
241
  return _reactquery.useQuery.call(void 0, {
@@ -111,15 +248,97 @@ function useMarket(ticker, queryOptions) {
111
248
 
112
249
  // src/react/use-positions.ts
113
250
 
114
- function usePositions(params, queryOptions) {
115
- const client = useDimesClient();
116
- return _reactquery.useQuery.call(void 0, {
117
- queryKey: ["dimes", "positions", params],
118
- queryFn: () => client.getPositions(params),
119
- ...queryOptions
251
+
252
+ // src/react/ws-reconcile.ts
253
+ var positionsQueryKey = ["dimes", "positions"];
254
+ var marketsQueryKey = ["dimes", "markets"];
255
+ var defaultReconciliationWindowMs = 12e3;
256
+ var transientPositionStatuses = /* @__PURE__ */ new Set(["pending", "closing", "settling", "unwinding"]);
257
+ var wsPositionTimestamps = /* @__PURE__ */ new Map();
258
+ function mergePositionEvent(queryClient, event, now) {
259
+ const position = event.data;
260
+ queryClient.setQueriesData({ queryKey: positionsQueryKey }, (old) => {
261
+ if (!old) {
262
+ return old;
263
+ }
264
+ const idx = old.findIndex((p) => p.id === position.id);
265
+ if (idx >= 0) {
266
+ const next = [...old];
267
+ next[idx] = position;
268
+ return next;
269
+ }
270
+ if (event.type === "position.created") {
271
+ return [position, ...old];
272
+ }
273
+ return old;
274
+ });
275
+ wsPositionTimestamps.set(position.id, now);
276
+ }
277
+ function reconcilePolledPositions(oldData, newData, windowMs, now) {
278
+ if (!oldData) {
279
+ return newData;
280
+ }
281
+ return newData.map((polled) => {
282
+ const wsTime = wsPositionTimestamps.get(polled.id);
283
+ if (wsTime !== void 0 && now - wsTime < windowMs) {
284
+ const fresher = oldData.find((p) => p.id === polled.id);
285
+ return _nullishCoalesce(fresher, () => ( polled));
286
+ }
287
+ if (wsTime !== void 0) {
288
+ wsPositionTimestamps.delete(polled.id);
289
+ }
290
+ return polled;
291
+ });
292
+ }
293
+ function mergeMarket(prev, delta) {
294
+ return {
295
+ ...prev,
296
+ ...delta,
297
+ leverage: delta.leverage ? { ...prev.leverage, ...delta.leverage } : prev.leverage
298
+ };
299
+ }
300
+ function mergeMarketDeltas(queryClient, deltas) {
301
+ queryClient.setQueriesData({ queryKey: marketsQueryKey }, (old) => {
302
+ if (!old) {
303
+ return old;
304
+ }
305
+ const data = old.data.map((market) => {
306
+ const delta = deltas.find((d) => d.id === market.id);
307
+ return delta ? mergeMarket(market, delta) : market;
308
+ });
309
+ const changed = data.some((market, i) => market !== old.data[i]);
310
+ return changed ? { ...old, data } : old;
120
311
  });
121
312
  }
122
313
 
314
+ // src/react/use-positions.ts
315
+ var DEFAULT_FAST_POLL_MS = 5e3;
316
+ var DEFAULT_SLOW_POLL_MS = 15e3;
317
+ function adaptiveRefetchInterval(adaptive) {
318
+ const fastMs = typeof adaptive === "object" ? _nullishCoalesce(adaptive.fastMs, () => ( DEFAULT_FAST_POLL_MS)) : DEFAULT_FAST_POLL_MS;
319
+ const slowMs = typeof adaptive === "object" ? _nullishCoalesce(adaptive.slowMs, () => ( DEFAULT_SLOW_POLL_MS)) : DEFAULT_SLOW_POLL_MS;
320
+ return (query) => _optionalChain([query, 'access', _8 => _8.state, 'access', _9 => _9.data, 'optionalAccess', _10 => _10.some, 'call', _11 => _11((p) => transientPositionStatuses.has(p.status))]) ? fastMs : slowMs;
321
+ }
322
+ function reconcileStructuralSharing(reconcile) {
323
+ const windowMs = typeof reconcile === "number" ? reconcile : defaultReconciliationWindowMs;
324
+ return (oldData, newData) => reconcilePolledPositions(oldData, newData, windowMs, Date.now());
325
+ }
326
+ function usePositions(params, queryOptions, options) {
327
+ const client = useDimesClient();
328
+ const queryKey = _optionalChain([options, 'optionalAccess', _12 => _12.scope]) !== void 0 ? ["dimes", "positions", params, options.scope] : ["dimes", "positions", params];
329
+ const config = {
330
+ queryKey,
331
+ queryFn: () => client.getPositions(params)
332
+ };
333
+ if (_optionalChain([options, 'optionalAccess', _13 => _13.adaptivePolling])) {
334
+ config.refetchInterval = adaptiveRefetchInterval(options.adaptivePolling);
335
+ }
336
+ if (_optionalChain([options, 'optionalAccess', _14 => _14.reconcile])) {
337
+ config.structuralSharing = reconcileStructuralSharing(options.reconcile);
338
+ }
339
+ return _reactquery.useQuery.call(void 0, { ...config, ...queryOptions });
340
+ }
341
+
123
342
  // src/react/use-contract-info.ts
124
343
 
125
344
  function useContractInfo(queryOptions) {
@@ -134,25 +353,204 @@ function useContractInfo(queryOptions) {
134
353
 
135
354
  // src/react/use-limits.ts
136
355
 
137
- function useLimits(queryOptions) {
356
+ function useUserLimits(queryOptions) {
357
+ const client = useDimesClient();
358
+ return _reactquery.useQuery.call(void 0, {
359
+ queryKey: ["dimes", "user-limits"],
360
+ queryFn: () => client.getUserLimits(),
361
+ ...queryOptions
362
+ });
363
+ }
364
+ function usePartnerLimits(queryOptions) {
138
365
  const client = useDimesClient();
139
366
  return _reactquery.useQuery.call(void 0, {
140
- queryKey: ["dimes", "limits"],
141
- queryFn: () => client.getLimits(),
367
+ queryKey: ["dimes", "partner-limits"],
368
+ queryFn: () => client.getPartnerLimits(),
142
369
  ...queryOptions
143
370
  });
144
371
  }
372
+ function useLimits(queryOptions) {
373
+ return useUserLimits(queryOptions);
374
+ }
145
375
 
146
376
  // src/react/use-cancel-position.ts
147
377
 
148
- function useCancelPosition(mutationOptions) {
378
+ var HTTP_CONFLICT = 409;
379
+ function useCancelPosition(mutationOptions, options) {
149
380
  const client = useDimesClient();
381
+ const treatConflictAsAlreadyCancelling = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _15 => _15.treatConflictAsAlreadyCancelling]), () => ( false));
150
382
  return _reactquery.useMutation.call(void 0, {
151
- mutationFn: (positionId) => client.cancelPosition(positionId),
383
+ mutationFn: async (positionId) => {
384
+ try {
385
+ await client.cancelPosition(positionId);
386
+ return "cancelled";
387
+ } catch (err) {
388
+ if (treatConflictAsAlreadyCancelling && err instanceof _chunk72LTVPD2cjs.DimesApiError && err.status === HTTP_CONFLICT) {
389
+ return "already_cancelling";
390
+ }
391
+ throw err;
392
+ }
393
+ },
152
394
  ...mutationOptions
153
395
  });
154
396
  }
155
397
 
398
+ // src/react/use-position-stream.ts
399
+
400
+
401
+ function usePositionStream(options) {
402
+ const client = useDimesClient();
403
+ const queryClient = _reactquery.useQueryClient.call(void 0, );
404
+ const socketRef = _react.useRef.call(void 0, null);
405
+ const [connected, setConnected] = _react.useState.call(void 0, false);
406
+ const enabled = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _16 => _16.enabled]), () => ( true));
407
+ const mode = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _17 => _17.mode]), () => ( "reconcile"));
408
+ const pauseOnHidden = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _18 => _18.pauseOnHidden]), () => ( true));
409
+ const invalidateOnReconnect = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _19 => _19.invalidateOnReconnect]), () => ( true));
410
+ const optionsRef = _react.useRef.call(void 0, options);
411
+ optionsRef.current = options;
412
+ _react.useEffect.call(void 0, () => {
413
+ if (!enabled) {
414
+ return void 0;
415
+ }
416
+ const socket = new (0, _chunkFAW2C5AMcjs.PositionSocket)({
417
+ baseUrl: client.baseUrl,
418
+ getToken: () => client.getToken()
419
+ });
420
+ socketRef.current = socket;
421
+ const unsubEvent = socket.on("*", (event) => {
422
+ if (mode === "reconcile") {
423
+ mergePositionEvent(queryClient, event, Date.now());
424
+ }
425
+ _optionalChain([optionsRef, 'access', _20 => _20.current, 'optionalAccess', _21 => _21.onEvent, 'optionalCall', _22 => _22(event)]);
426
+ });
427
+ const unsubNotification = socket.onNotification((event) => {
428
+ _optionalChain([optionsRef, 'access', _23 => _23.current, 'optionalAccess', _24 => _24.onNotification, 'optionalCall', _25 => _25(event)]);
429
+ });
430
+ let firstConnect = true;
431
+ const unsubConnect = socket.onConnect(() => {
432
+ setConnected(true);
433
+ if (firstConnect) {
434
+ firstConnect = false;
435
+ } else if (mode === "reconcile" && invalidateOnReconnect) {
436
+ void queryClient.invalidateQueries({ queryKey: positionsQueryKey });
437
+ }
438
+ _optionalChain([optionsRef, 'access', _26 => _26.current, 'optionalAccess', _27 => _27.onConnect, 'optionalCall', _28 => _28()]);
439
+ });
440
+ const unsubDisconnect = socket.onDisconnect(() => {
441
+ setConnected(false);
442
+ _optionalChain([optionsRef, 'access', _29 => _29.current, 'optionalAccess', _30 => _30.onDisconnect, 'optionalCall', _31 => _31()]);
443
+ });
444
+ const unsubError = socket.onError((error) => {
445
+ _optionalChain([optionsRef, 'access', _32 => _32.current, 'optionalAccess', _33 => _33.onError, 'optionalCall', _34 => _34(error)]);
446
+ });
447
+ const handleVisibility = pauseOnHidden && typeof document !== "undefined" ? () => {
448
+ if (document.hidden) {
449
+ socket.disconnect();
450
+ } else {
451
+ socket.connect();
452
+ }
453
+ } : null;
454
+ if (handleVisibility) {
455
+ document.addEventListener("visibilitychange", handleVisibility);
456
+ }
457
+ socket.connect();
458
+ return () => {
459
+ if (handleVisibility) {
460
+ document.removeEventListener("visibilitychange", handleVisibility);
461
+ }
462
+ unsubEvent();
463
+ unsubNotification();
464
+ unsubConnect();
465
+ unsubDisconnect();
466
+ unsubError();
467
+ socket.disconnect();
468
+ socketRef.current = null;
469
+ setConnected(false);
470
+ };
471
+ }, [client, queryClient, enabled, mode, pauseOnHidden, invalidateOnReconnect]);
472
+ return { socket: socketRef.current, connected };
473
+ }
474
+
475
+ // src/react/use-market-stream.ts
476
+
477
+
478
+ function useMarketStream(options) {
479
+ const client = useDimesClient();
480
+ const queryClient = _reactquery.useQueryClient.call(void 0, );
481
+ const socketRef = _react.useRef.call(void 0, null);
482
+ const [connected, setConnected] = _react.useState.call(void 0, false);
483
+ const enabled = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _35 => _35.enabled]), () => ( true));
484
+ const mode = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _36 => _36.mode]), () => ( "reconcile"));
485
+ const pauseOnHidden = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _37 => _37.pauseOnHidden]), () => ( true));
486
+ const invalidateOnReconnect = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _38 => _38.invalidateOnReconnect]), () => ( true));
487
+ const optionsRef = _react.useRef.call(void 0, options);
488
+ optionsRef.current = options;
489
+ _react.useEffect.call(void 0, () => {
490
+ if (!enabled) {
491
+ return void 0;
492
+ }
493
+ const socket = new (0, _chunkFAW2C5AMcjs.MarketSocket)({
494
+ baseUrl: client.baseUrl,
495
+ getToken: () => client.getToken()
496
+ });
497
+ socketRef.current = socket;
498
+ const unsubEvent = socket.on("*", (event) => {
499
+ if (mode === "reconcile" && event.type !== "market.discovered") {
500
+ mergeMarketDeltas(queryClient, event.data);
501
+ }
502
+ _optionalChain([optionsRef, 'access', _39 => _39.current, 'optionalAccess', _40 => _40.onEvent, 'optionalCall', _41 => _41(event)]);
503
+ });
504
+ let firstConnect = true;
505
+ const unsubConnect = socket.onConnect(() => {
506
+ setConnected(true);
507
+ if (firstConnect) {
508
+ firstConnect = false;
509
+ } else if (mode === "reconcile" && invalidateOnReconnect) {
510
+ void queryClient.invalidateQueries({ queryKey: marketsQueryKey });
511
+ }
512
+ _optionalChain([optionsRef, 'access', _42 => _42.current, 'optionalAccess', _43 => _43.onConnect, 'optionalCall', _44 => _44()]);
513
+ });
514
+ const unsubDisconnect = socket.onDisconnect(() => {
515
+ setConnected(false);
516
+ _optionalChain([optionsRef, 'access', _45 => _45.current, 'optionalAccess', _46 => _46.onDisconnect, 'optionalCall', _47 => _47()]);
517
+ });
518
+ const unsubError = socket.onError((error) => {
519
+ _optionalChain([optionsRef, 'access', _48 => _48.current, 'optionalAccess', _49 => _49.onError, 'optionalCall', _50 => _50(error)]);
520
+ });
521
+ const handleVisibility = pauseOnHidden && typeof document !== "undefined" ? () => {
522
+ if (document.hidden) {
523
+ socket.disconnect();
524
+ } else {
525
+ socket.connect();
526
+ }
527
+ } : null;
528
+ if (handleVisibility) {
529
+ document.addEventListener("visibilitychange", handleVisibility);
530
+ }
531
+ socket.connect();
532
+ return () => {
533
+ if (handleVisibility) {
534
+ document.removeEventListener("visibilitychange", handleVisibility);
535
+ }
536
+ unsubEvent();
537
+ unsubConnect();
538
+ unsubDisconnect();
539
+ unsubError();
540
+ socket.disconnect();
541
+ socketRef.current = null;
542
+ setConnected(false);
543
+ };
544
+ }, [client, queryClient, enabled, mode, pauseOnHidden, invalidateOnReconnect]);
545
+ return { socket: socketRef.current, connected };
546
+ }
547
+
548
+
549
+
550
+
551
+
552
+
553
+
156
554
 
157
555
 
158
556
 
@@ -162,5 +560,5 @@ function useCancelPosition(mutationOptions) {
162
560
 
163
561
 
164
562
 
165
- exports.DimesProvider = DimesProvider; exports.useCancelPosition = useCancelPosition; exports.useContractInfo = useContractInfo; exports.useDimesClient = useDimesClient; exports.useLimits = useLimits; exports.useMarket = useMarket; exports.useMarkets = useMarkets; exports.usePositions = usePositions; exports.useQuote = useQuote;
563
+ exports.DimesProvider = DimesProvider; exports.useCancelPosition = useCancelPosition; exports.useContractInfo = useContractInfo; exports.useDimesClient = useDimesClient; exports.useLimits = useLimits; exports.useMarket = useMarket; exports.useMarketStream = useMarketStream; exports.useMarkets = useMarkets; exports.usePartnerLimits = usePartnerLimits; exports.usePositionStream = usePositionStream; exports.usePositions = usePositions; exports.useQuote = useQuote; exports.useQuoteMachine = useQuoteMachine; exports.useSearchMarkets = useSearchMarkets; exports.useUserLimits = useUserLimits;
166
564
  //# sourceMappingURL=index.cjs.map