@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.
- package/LICENSE +21 -0
- package/README.md +88 -19
- package/dist/{aliases-C2l_JZX_.d.cts → aliases-BJyM8ydu.d.cts} +288 -4
- package/dist/{aliases-C2l_JZX_.d.ts → aliases-BJyM8ydu.d.ts} +288 -4
- package/dist/{chunk-UHQZSMUD.cjs → chunk-53U53KZ2.cjs} +5 -1
- package/dist/chunk-53U53KZ2.cjs.map +1 -0
- package/dist/chunk-5VHDXPRV.mjs +240 -0
- package/dist/chunk-5VHDXPRV.mjs.map +1 -0
- package/dist/{chunk-DYPABUKC.cjs → chunk-72LTVPD2.cjs} +16 -1
- package/dist/chunk-72LTVPD2.cjs.map +1 -0
- package/dist/{chunk-COSLZ5TM.cjs → chunk-DIH3ORFA.cjs} +38 -16
- package/dist/chunk-DIH3ORFA.cjs.map +1 -0
- package/dist/chunk-FAW2C5AM.cjs +240 -0
- package/dist/chunk-FAW2C5AM.cjs.map +1 -0
- package/dist/{chunk-SGA6OZEU.mjs → chunk-NHAIL4SN.mjs} +34 -12
- package/dist/chunk-NHAIL4SN.mjs.map +1 -0
- package/dist/{chunk-4MO3HKMS.mjs → chunk-PK2PRTQW.mjs} +5 -1
- package/dist/chunk-PK2PRTQW.mjs.map +1 -0
- package/dist/{chunk-BVILILIV.mjs → chunk-PZCBUVPD.mjs} +16 -1
- package/dist/chunk-PZCBUVPD.mjs.map +1 -0
- package/dist/contract/index.cjs +5534 -305
- package/dist/contract/index.cjs.map +1 -1
- package/dist/contract/index.d.cts +68 -10
- package/dist/contract/index.d.ts +68 -10
- package/dist/contract/index.mjs +5524 -295
- package/dist/contract/index.mjs.map +1 -1
- package/dist/{dimes-client-ty6xwk0b.d.cts → dimes-client-DYFvnZUx.d.ts} +57 -10
- package/dist/{dimes-client-u5wLYVfp.d.ts → dimes-client-DZPhU1CG.d.cts} +57 -10
- package/dist/{dimes-error-5ldDx2_G.d.cts → dimes-error-BlQWPqhQ.d.cts} +2 -2
- package/dist/{dimes-error-D2RVknPr.d.ts → dimes-error-DBKV5bfr.d.ts} +2 -2
- package/dist/index.cjs +164 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +151 -12
- package/dist/index.d.ts +151 -12
- package/dist/index.mjs +161 -9
- package/dist/index.mjs.map +1 -1
- package/dist/quote-BFNgVsY-.d.ts +39 -0
- package/dist/quote-CanwfT9m.d.cts +39 -0
- package/dist/react/index.cjs +416 -18
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +165 -8
- package/dist/react/index.d.ts +165 -8
- package/dist/react/index.mjs +414 -16
- package/dist/react/index.mjs.map +1 -1
- package/dist/{types-CM14Dx5b.d.cts → types-ClHQbIcY.d.ts} +3 -3
- package/dist/{types-CVcrVq0A.d.ts → types-Co-2bQSi.d.cts} +3 -3
- package/dist/ws/index.cjs +4 -230
- package/dist/ws/index.cjs.map +1 -1
- package/dist/ws/index.d.cts +3 -3
- package/dist/ws/index.d.ts +3 -3
- package/dist/ws/index.mjs +5 -231
- package/dist/ws/index.mjs.map +1 -1
- package/package.json +43 -4
- package/dist/chunk-4MO3HKMS.mjs.map +0 -1
- package/dist/chunk-BVILILIV.mjs.map +0 -1
- package/dist/chunk-COSLZ5TM.cjs.map +0 -1
- package/dist/chunk-DYPABUKC.cjs.map +0 -1
- package/dist/chunk-SGA6OZEU.mjs.map +0 -1
- package/dist/chunk-UHQZSMUD.cjs.map +0 -1
- package/dist/quote-DoRJUXld.d.cts +0 -30
- package/dist/quote-GCNVcEoo.d.ts +0 -30
package/dist/react/index.mjs
CHANGED
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
buildQuoteParams,
|
|
3
|
+
executeQuote,
|
|
4
|
+
isMarketMovedError
|
|
5
|
+
} from "../chunk-NHAIL4SN.mjs";
|
|
4
6
|
import {
|
|
7
|
+
DimesApiError,
|
|
5
8
|
DimesError
|
|
6
|
-
} from "../chunk-
|
|
9
|
+
} from "../chunk-PZCBUVPD.mjs";
|
|
10
|
+
import {
|
|
11
|
+
MarketSocket,
|
|
12
|
+
PositionSocket
|
|
13
|
+
} from "../chunk-5VHDXPRV.mjs";
|
|
14
|
+
import "../chunk-PK2PRTQW.mjs";
|
|
7
15
|
|
|
8
16
|
// src/react/provider.tsx
|
|
9
17
|
import { createContext, useContext } from "react";
|
|
@@ -35,7 +43,8 @@ function reducer(state, action) {
|
|
|
35
43
|
case "done":
|
|
36
44
|
return {
|
|
37
45
|
phase: "promoted",
|
|
38
|
-
|
|
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
|
|
@@ -89,6 +98,125 @@ function useQuote() {
|
|
|
89
98
|
return { state, execute, reset };
|
|
90
99
|
}
|
|
91
100
|
|
|
101
|
+
// src/react/use-quote-machine.ts
|
|
102
|
+
import { useCallback as useCallback2, useReducer as useReducer2, useRef } from "react";
|
|
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 = options?.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
139
|
+
const [state, dispatch] = useReducer2(reducer2, { phase: "idle" });
|
|
140
|
+
const lastParamsRef = useRef(null);
|
|
141
|
+
const quotedAtRef = useRef(0);
|
|
142
|
+
const getDraft = useCallback2(
|
|
143
|
+
async (params) => {
|
|
144
|
+
dispatch({ type: "loading" });
|
|
145
|
+
const quoteParams = buildQuoteParams(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 = useCallback2(
|
|
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 (isMarketMovedError(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 = useCallback2(
|
|
187
|
+
async (newDraft, retryCount) => {
|
|
188
|
+
await promote(newDraft, retryCount);
|
|
189
|
+
},
|
|
190
|
+
[promote]
|
|
191
|
+
);
|
|
192
|
+
const correctAndPromote = useCallback2(
|
|
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 = useCallback2(() => {
|
|
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
|
import { useQuery } from "@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 useQuery({
|
|
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 useQuery({
|
|
@@ -111,15 +248,97 @@ function useMarket(ticker, queryOptions) {
|
|
|
111
248
|
|
|
112
249
|
// src/react/use-positions.ts
|
|
113
250
|
import { useQuery as useQuery2 } from "@tanstack/react-query";
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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 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" ? adaptive.fastMs ?? DEFAULT_FAST_POLL_MS : DEFAULT_FAST_POLL_MS;
|
|
319
|
+
const slowMs = typeof adaptive === "object" ? adaptive.slowMs ?? DEFAULT_SLOW_POLL_MS : DEFAULT_SLOW_POLL_MS;
|
|
320
|
+
return (query) => query.state.data?.some((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 = options?.scope !== void 0 ? ["dimes", "positions", params, options.scope] : ["dimes", "positions", params];
|
|
329
|
+
const config = {
|
|
330
|
+
queryKey,
|
|
331
|
+
queryFn: () => client.getPositions(params)
|
|
332
|
+
};
|
|
333
|
+
if (options?.adaptivePolling) {
|
|
334
|
+
config.refetchInterval = adaptiveRefetchInterval(options.adaptivePolling);
|
|
335
|
+
}
|
|
336
|
+
if (options?.reconcile) {
|
|
337
|
+
config.structuralSharing = reconcileStructuralSharing(options.reconcile);
|
|
338
|
+
}
|
|
339
|
+
return useQuery2({ ...config, ...queryOptions });
|
|
340
|
+
}
|
|
341
|
+
|
|
123
342
|
// src/react/use-contract-info.ts
|
|
124
343
|
import { useQuery as useQuery3 } from "@tanstack/react-query";
|
|
125
344
|
function useContractInfo(queryOptions) {
|
|
@@ -134,24 +353,197 @@ function useContractInfo(queryOptions) {
|
|
|
134
353
|
|
|
135
354
|
// src/react/use-limits.ts
|
|
136
355
|
import { useQuery as useQuery4 } from "@tanstack/react-query";
|
|
137
|
-
function
|
|
356
|
+
function useUserLimits(queryOptions) {
|
|
138
357
|
const client = useDimesClient();
|
|
139
358
|
return useQuery4({
|
|
140
|
-
queryKey: ["dimes", "limits"],
|
|
141
|
-
queryFn: () => client.
|
|
359
|
+
queryKey: ["dimes", "user-limits"],
|
|
360
|
+
queryFn: () => client.getUserLimits(),
|
|
142
361
|
...queryOptions
|
|
143
362
|
});
|
|
144
363
|
}
|
|
364
|
+
function usePartnerLimits(queryOptions) {
|
|
365
|
+
const client = useDimesClient();
|
|
366
|
+
return useQuery4({
|
|
367
|
+
queryKey: ["dimes", "partner-limits"],
|
|
368
|
+
queryFn: () => client.getPartnerLimits(),
|
|
369
|
+
...queryOptions
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
function useLimits(queryOptions) {
|
|
373
|
+
return useUserLimits(queryOptions);
|
|
374
|
+
}
|
|
145
375
|
|
|
146
376
|
// src/react/use-cancel-position.ts
|
|
147
377
|
import { useMutation } from "@tanstack/react-query";
|
|
148
|
-
|
|
378
|
+
var HTTP_CONFLICT = 409;
|
|
379
|
+
function useCancelPosition(mutationOptions, options) {
|
|
149
380
|
const client = useDimesClient();
|
|
381
|
+
const treatConflictAsAlreadyCancelling = options?.treatConflictAsAlreadyCancelling ?? false;
|
|
150
382
|
return useMutation({
|
|
151
|
-
mutationFn: (positionId) =>
|
|
383
|
+
mutationFn: async (positionId) => {
|
|
384
|
+
try {
|
|
385
|
+
await client.cancelPosition(positionId);
|
|
386
|
+
return "cancelled";
|
|
387
|
+
} catch (err) {
|
|
388
|
+
if (treatConflictAsAlreadyCancelling && err instanceof DimesApiError && err.status === HTTP_CONFLICT) {
|
|
389
|
+
return "already_cancelling";
|
|
390
|
+
}
|
|
391
|
+
throw err;
|
|
392
|
+
}
|
|
393
|
+
},
|
|
152
394
|
...mutationOptions
|
|
153
395
|
});
|
|
154
396
|
}
|
|
397
|
+
|
|
398
|
+
// src/react/use-position-stream.ts
|
|
399
|
+
import { useQueryClient } from "@tanstack/react-query";
|
|
400
|
+
import { useEffect, useRef as useRef2, useState } from "react";
|
|
401
|
+
function usePositionStream(options) {
|
|
402
|
+
const client = useDimesClient();
|
|
403
|
+
const queryClient = useQueryClient();
|
|
404
|
+
const socketRef = useRef2(null);
|
|
405
|
+
const [connected, setConnected] = useState(false);
|
|
406
|
+
const enabled = options?.enabled ?? true;
|
|
407
|
+
const mode = options?.mode ?? "reconcile";
|
|
408
|
+
const pauseOnHidden = options?.pauseOnHidden ?? true;
|
|
409
|
+
const invalidateOnReconnect = options?.invalidateOnReconnect ?? true;
|
|
410
|
+
const optionsRef = useRef2(options);
|
|
411
|
+
optionsRef.current = options;
|
|
412
|
+
useEffect(() => {
|
|
413
|
+
if (!enabled) {
|
|
414
|
+
return void 0;
|
|
415
|
+
}
|
|
416
|
+
const socket = new 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
|
+
optionsRef.current?.onEvent?.(event);
|
|
426
|
+
});
|
|
427
|
+
const unsubNotification = socket.onNotification((event) => {
|
|
428
|
+
optionsRef.current?.onNotification?.(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
|
+
optionsRef.current?.onConnect?.();
|
|
439
|
+
});
|
|
440
|
+
const unsubDisconnect = socket.onDisconnect(() => {
|
|
441
|
+
setConnected(false);
|
|
442
|
+
optionsRef.current?.onDisconnect?.();
|
|
443
|
+
});
|
|
444
|
+
const unsubError = socket.onError((error) => {
|
|
445
|
+
optionsRef.current?.onError?.(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
|
+
import { useQueryClient as useQueryClient2 } from "@tanstack/react-query";
|
|
477
|
+
import { useEffect as useEffect2, useRef as useRef3, useState as useState2 } from "react";
|
|
478
|
+
function useMarketStream(options) {
|
|
479
|
+
const client = useDimesClient();
|
|
480
|
+
const queryClient = useQueryClient2();
|
|
481
|
+
const socketRef = useRef3(null);
|
|
482
|
+
const [connected, setConnected] = useState2(false);
|
|
483
|
+
const enabled = options?.enabled ?? true;
|
|
484
|
+
const mode = options?.mode ?? "reconcile";
|
|
485
|
+
const pauseOnHidden = options?.pauseOnHidden ?? true;
|
|
486
|
+
const invalidateOnReconnect = options?.invalidateOnReconnect ?? true;
|
|
487
|
+
const optionsRef = useRef3(options);
|
|
488
|
+
optionsRef.current = options;
|
|
489
|
+
useEffect2(() => {
|
|
490
|
+
if (!enabled) {
|
|
491
|
+
return void 0;
|
|
492
|
+
}
|
|
493
|
+
const socket = new 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
|
+
optionsRef.current?.onEvent?.(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
|
+
optionsRef.current?.onConnect?.();
|
|
513
|
+
});
|
|
514
|
+
const unsubDisconnect = socket.onDisconnect(() => {
|
|
515
|
+
setConnected(false);
|
|
516
|
+
optionsRef.current?.onDisconnect?.();
|
|
517
|
+
});
|
|
518
|
+
const unsubError = socket.onError((error) => {
|
|
519
|
+
optionsRef.current?.onError?.(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
|
+
}
|
|
155
547
|
export {
|
|
156
548
|
DimesProvider,
|
|
157
549
|
useCancelPosition,
|
|
@@ -159,8 +551,14 @@ export {
|
|
|
159
551
|
useDimesClient,
|
|
160
552
|
useLimits,
|
|
161
553
|
useMarket,
|
|
554
|
+
useMarketStream,
|
|
162
555
|
useMarkets,
|
|
556
|
+
usePartnerLimits,
|
|
557
|
+
usePositionStream,
|
|
163
558
|
usePositions,
|
|
164
|
-
useQuote
|
|
559
|
+
useQuote,
|
|
560
|
+
useQuoteMachine,
|
|
561
|
+
useSearchMarkets,
|
|
562
|
+
useUserLimits
|
|
165
563
|
};
|
|
166
564
|
//# sourceMappingURL=index.mjs.map
|
package/dist/react/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/react/provider.tsx","../../src/react/use-quote.ts","../../src/react/use-markets.ts","../../src/react/use-positions.ts","../../src/react/use-contract-info.ts","../../src/react/use-limits.ts","../../src/react/use-cancel-position.ts"],"sourcesContent":["import { createContext, useContext, type ReactNode } from \"react\";\nimport type { DimesClient } from \"../client/dimes-client\";\nimport { DimesError } from \"../errors/dimes-error\";\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst DimesContext = createContext<DimesClient | null>(null);\n\nexport interface DimesProviderProps {\n client: DimesClient;\n children: ReactNode;\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/explicit-function-return-type\nexport function DimesProvider({ client, children }: DimesProviderProps) {\n return <DimesContext.Provider value={client}>{children}</DimesContext.Provider>;\n}\n\nexport function useDimesClient(): DimesClient {\n const client = useContext(DimesContext);\n if (!client) {\n throw new DimesError(\"missing_provider\", \"useDimesClient must be used within a <DimesProvider>\");\n }\n return client;\n}\n","import { useCallback, useReducer } from \"react\";\nimport { executeQuote } from \"../quote/quote\";\nimport type { HintAdjustment } from \"../quote/quote-error-hints\";\nimport type { Offer } from \"../types\";\nimport type { QuoteOptions, QuoteParams, QuoteResult } from \"../types/quote\";\nimport { useDimesClient } from \"./provider\";\n\nexport type QuotePhase = \"idle\" | \"loading-draft\" | \"draft-ready\" | \"promoting\" | \"promoted\" | \"market-moved\" | \"error\";\n\nexport interface QuoteState {\n phase: QuotePhase;\n draft?: Offer;\n offer?: Offer;\n corrections: HintAdjustment[];\n retries: number;\n error?: unknown;\n}\n\ntype Action =\n | { type: \"loading\" }\n | { type: \"draftReady\"; draft: Offer }\n | { type: \"promoting\" }\n | { type: \"marketMoved\" }\n | { type: \"done\"; result: QuoteResult }\n | { type: \"error\"; error: unknown }\n | { type: \"reset\" };\n\nfunction reducer(state: QuoteState, action: Action): QuoteState {\n switch (action.type) {\n case \"loading\":\n return { phase: \"loading-draft\", corrections: [], retries: 0 };\n case \"draftReady\":\n return { ...state, phase: \"draft-ready\", draft: action.draft };\n case \"promoting\":\n return { ...state, phase: \"promoting\" };\n case \"marketMoved\":\n return { ...state, phase: \"market-moved\" };\n case \"done\":\n return {\n phase: \"promoted\",\n offer: action.result.offer,\n corrections: action.result.corrections,\n retries: action.result.retries,\n draft: state.draft,\n };\n case \"error\":\n return { ...state, phase: \"error\", error: action.error };\n case \"reset\":\n return { phase: \"idle\", corrections: [], retries: 0 };\n default:\n return state;\n }\n}\n\nexport interface UseQuoteReturn {\n state: QuoteState;\n execute: (params: QuoteParams, options?: QuoteOptions) => Promise<QuoteResult>;\n reset: () => void;\n}\n\nexport function useQuote(): UseQuoteReturn {\n const client = useDimesClient();\n const [state, dispatch] = useReducer(reducer, {\n phase: \"idle\",\n corrections: [],\n retries: 0,\n });\n\n const execute = useCallback(\n async (params: QuoteParams, options?: QuoteOptions): Promise<QuoteResult> => {\n dispatch({ type: \"loading\" });\n\n try {\n const result = await executeQuote(client, params, {\n ...options,\n onDraftReady: (draft) => {\n dispatch({ type: \"draftReady\", draft });\n dispatch({ type: \"promoting\" });\n options?.onDraftReady?.(draft);\n },\n onMarketMoved: (event) => {\n dispatch({ type: \"marketMoved\" });\n return options?.onMarketMoved?.(event);\n },\n onCorrection: (adj) => {\n return options?.onCorrection?.(adj);\n },\n });\n\n dispatch({ type: \"done\", result });\n return result;\n } catch (err) {\n dispatch({ type: \"error\", error: err });\n throw err;\n }\n },\n [client],\n );\n\n const reset = useCallback(() => {\n dispatch({ type: \"reset\" });\n }, []);\n\n return { state, execute, reset };\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { GetMarketsParams } from \"../client/dimes-client\";\nimport type { Market, Paginated } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function useMarkets(\n params?: GetMarketsParams,\n queryOptions?: Partial<UseQueryOptions<Paginated<Market>>>,\n): UseQueryResult<Paginated<Market>> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"markets\", params],\n queryFn: () => client.getMarkets(params),\n ...queryOptions,\n });\n}\n\nexport function useMarket(ticker: string, queryOptions?: Partial<UseQueryOptions<Market>>): UseQueryResult<Market> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"market\", ticker],\n queryFn: () => client.getMarket(ticker),\n enabled: !!ticker,\n ...queryOptions,\n });\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { GetPositionsParams } from \"../client/dimes-client\";\nimport type { Position } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function usePositions(\n params?: GetPositionsParams,\n queryOptions?: Partial<UseQueryOptions<Position[]>>,\n): UseQueryResult<Position[]> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"positions\", params],\n queryFn: () => client.getPositions(params),\n ...queryOptions,\n });\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { ContractInfo } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function useContractInfo(queryOptions?: Partial<UseQueryOptions<ContractInfo>>): UseQueryResult<ContractInfo> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"contractInfo\"],\n queryFn: () => client.getContractInfo(),\n staleTime: Infinity,\n ...queryOptions,\n });\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { CustomerLimit } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function useLimits(queryOptions?: Partial<UseQueryOptions<CustomerLimit>>): UseQueryResult<CustomerLimit> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"limits\"],\n queryFn: () => client.getLimits(),\n ...queryOptions,\n });\n}\n","import { useMutation, type UseMutationOptions, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useDimesClient } from \"./provider\";\n\nexport function useCancelPosition(\n mutationOptions?: Partial<UseMutationOptions<void, Error, string>>,\n): UseMutationResult<void, Error, string> {\n const client = useDimesClient();\n\n return useMutation({\n mutationFn: (positionId: string) => client.cancelPosition(positionId),\n ...mutationOptions,\n });\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,eAAe,kBAAkC;AAcjD;AATT,IAAM,eAAe,cAAkC,IAAI;AAQpD,SAAS,cAAc,EAAE,QAAQ,SAAS,GAAuB;AACtE,SAAO,oBAAC,aAAa,UAAb,EAAsB,OAAO,QAAS,UAAS;AACzD;AAEO,SAAS,iBAA8B;AAC5C,QAAM,SAAS,WAAW,YAAY;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OAAO,aAAa,MAAM;AAAA,IACzC,GAAG;AAAA,EACL,CAAC;AACH;;;AChBA,SAAS,YAAAC,iBAA2D;AAI7D,SAAS,gBAAgB,cAAqF;AACnH,QAAM,SAAS,eAAe;AAE9B,SAAOC,UAAS;AAAA,IACd,UAAU,CAAC,SAAS,cAAc;AAAA,IAClC,SAAS,MAAM,OAAO,gBAAgB;AAAA,IACtC,WAAW;AAAA,IACX,GAAG;AAAA,EACL,CAAC;AACH;;;ACbA,SAAS,YAAAC,iBAA2D;AAI7D,SAAS,UAAU,cAAuF;AAC/G,QAAM,SAAS,eAAe;AAE9B,SAAOC,UAAS;AAAA,IACd,UAAU,CAAC,SAAS,QAAQ;AAAA,IAC5B,SAAS,MAAM,OAAO,UAAU;AAAA,IAChC,GAAG;AAAA,EACL,CAAC;AACH;;;ACZA,SAAS,mBAAoE;AAGtE,SAAS,kBACd,iBACwC;AACxC,QAAM,SAAS,eAAe;AAE9B,SAAO,YAAY;AAAA,IACjB,YAAY,CAAC,eAAuB,OAAO,eAAe,UAAU;AAAA,IACpE,GAAG;AAAA,EACL,CAAC;AACH;","names":["useQuery","useQuery","useQuery","useQuery","useQuery","useQuery"]}
|
|
1
|
+
{"version":3,"sources":["../../src/react/provider.tsx","../../src/react/use-quote.ts","../../src/react/use-quote-machine.ts","../../src/react/use-markets.ts","../../src/react/use-positions.ts","../../src/react/ws-reconcile.ts","../../src/react/use-contract-info.ts","../../src/react/use-limits.ts","../../src/react/use-cancel-position.ts","../../src/react/use-position-stream.ts","../../src/react/use-market-stream.ts"],"sourcesContent":["import { createContext, useContext, type ReactNode } from \"react\";\nimport type { DimesClient } from \"../client/dimes-client\";\nimport { DimesError } from \"../errors/dimes-error\";\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst DimesContext = createContext<DimesClient | null>(null);\n\nexport interface DimesProviderProps {\n client: DimesClient;\n children: ReactNode;\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/explicit-function-return-type\nexport function DimesProvider({ client, children }: DimesProviderProps) {\n return <DimesContext.Provider value={client}>{children}</DimesContext.Provider>;\n}\n\nexport function useDimesClient(): DimesClient {\n const client = useContext(DimesContext);\n if (!client) {\n throw new DimesError(\"missing_provider\", \"useDimesClient must be used within a <DimesProvider>\");\n }\n return client;\n}\n","import { useCallback, useReducer } from \"react\";\nimport { executeQuote } from \"../quote/quote\";\nimport type { HintAdjustment } from \"../quote/quote-error-hints\";\nimport type { Quote } from \"../types\";\nimport type { QuoteOptions, QuoteParams, QuoteResult } from \"../types/quote\";\nimport { useDimesClient } from \"./provider\";\n\nexport type QuotePhase = \"idle\" | \"loading-draft\" | \"draft-ready\" | \"promoting\" | \"promoted\" | \"market-moved\" | \"error\";\n\nexport interface QuoteState {\n phase: QuotePhase;\n draft?: Quote;\n quote?: Quote;\n /** @deprecated Renamed to {@link QuoteState.quote}. Still populated for backward compatibility. */\n // eslint-disable-next-line no-restricted-syntax -- intentional deprecated alias field\n offer?: Quote;\n corrections: HintAdjustment[];\n retries: number;\n error?: unknown;\n}\n\ntype Action =\n | { type: \"loading\" }\n | { type: \"draftReady\"; draft: Quote }\n | { type: \"promoting\" }\n | { type: \"marketMoved\" }\n | { type: \"done\"; result: QuoteResult }\n | { type: \"error\"; error: unknown }\n | { type: \"reset\" };\n\nfunction reducer(state: QuoteState, action: Action): QuoteState {\n switch (action.type) {\n case \"loading\":\n return { phase: \"loading-draft\", corrections: [], retries: 0 };\n case \"draftReady\":\n return { ...state, phase: \"draft-ready\", draft: action.draft };\n case \"promoting\":\n return { ...state, phase: \"promoting\" };\n case \"marketMoved\":\n return { ...state, phase: \"market-moved\" };\n case \"done\":\n return {\n phase: \"promoted\",\n quote: action.result.quote,\n offer: action.result.quote,\n corrections: action.result.corrections,\n retries: action.result.retries,\n draft: state.draft,\n };\n case \"error\":\n return { ...state, phase: \"error\", error: action.error };\n case \"reset\":\n return { phase: \"idle\", corrections: [], retries: 0 };\n default:\n return state;\n }\n}\n\nexport interface UseQuoteReturn {\n state: QuoteState;\n execute: (params: QuoteParams, options?: QuoteOptions) => Promise<QuoteResult>;\n reset: () => void;\n}\n\nexport function useQuote(): UseQuoteReturn {\n const client = useDimesClient();\n const [state, dispatch] = useReducer(reducer, {\n phase: \"idle\",\n corrections: [],\n retries: 0,\n });\n\n const execute = useCallback(\n async (params: QuoteParams, options?: QuoteOptions): Promise<QuoteResult> => {\n dispatch({ type: \"loading\" });\n\n try {\n const result = await executeQuote(client, params, {\n ...options,\n onDraftReady: (draft) => {\n dispatch({ type: \"draftReady\", draft });\n dispatch({ type: \"promoting\" });\n options?.onDraftReady?.(draft);\n },\n onMarketMoved: (event) => {\n dispatch({ type: \"marketMoved\" });\n return options?.onMarketMoved?.(event);\n },\n onCorrection: (adj) => {\n return options?.onCorrection?.(adj);\n },\n });\n\n dispatch({ type: \"done\", result });\n return result;\n } catch (err) {\n dispatch({ type: \"error\", error: err });\n throw err;\n }\n },\n [client],\n );\n\n const reset = useCallback(() => {\n dispatch({ type: \"reset\" });\n }, []);\n\n return { state, execute, reset };\n}\n","import { useCallback, useReducer, useRef } from \"react\";\nimport { buildQuoteParams } from \"../quote/build-quote-params\";\nimport { isMarketMovedError } from \"../quote/quote\";\nimport type { CreateQuoteParams, Quote } from \"../types\";\nimport type { QuoteParams } from \"../types/quote\";\nimport { useDimesClient } from \"./provider\";\n\nconst DEFAULT_MAX_RETRIES = 3;\n\n/**\n * Interactive, user-in-the-loop quote flow: draft → review → promote, pausing\n * across renders so the UI can show each step. This is the granular companion\n * to `useQuote`/`executeQuote` (which run draft→promote in one call). The steps\n * map directly onto the SDK client (`createDraftQuote`/`promoteDraftQuote`/\n * `createQuote`); on a market-moved promote failure it re-drafts and surfaces a\n * `market-moved` state so the user can review and accept the new draft.\n */\nexport type QuoteMachineState =\n | { phase: \"idle\" }\n | { phase: \"loading-draft\" }\n | { phase: \"draft-ready\"; draft: Quote; quotedAt: number }\n | { phase: \"promoting\"; draft: Quote; quotedAt: number }\n | { phase: \"promoted\"; draft: Quote; promotedQuote: Quote; correctedFrom?: Quote; quotedAt: number }\n | { phase: \"market-moved\"; originalDraft: Quote; newDraft: Quote; retryCount: number; quotedAt: number }\n | { phase: \"error\"; error: unknown; draft?: Quote };\n\ntype Action =\n | { type: \"loading\" }\n | { type: \"draftReady\"; draft: Quote; quotedAt: number }\n | { type: \"promoting\"; draft: Quote; quotedAt: number }\n | { type: \"promoted\"; draft: Quote; promotedQuote: Quote; correctedFrom?: Quote; quotedAt: number }\n | { type: \"marketMoved\"; originalDraft: Quote; newDraft: Quote; retryCount: number; quotedAt: number }\n | { type: \"error\"; error: unknown; draft?: Quote }\n | { type: \"reset\" };\n\nfunction reducer(_state: QuoteMachineState, action: Action): QuoteMachineState {\n switch (action.type) {\n case \"loading\":\n return { phase: \"loading-draft\" };\n case \"draftReady\":\n return { phase: \"draft-ready\", draft: action.draft, quotedAt: action.quotedAt };\n case \"promoting\":\n return { phase: \"promoting\", draft: action.draft, quotedAt: action.quotedAt };\n case \"promoted\":\n return {\n phase: \"promoted\",\n draft: action.draft,\n promotedQuote: action.promotedQuote,\n correctedFrom: action.correctedFrom,\n quotedAt: action.quotedAt,\n };\n case \"marketMoved\":\n return {\n phase: \"market-moved\",\n originalDraft: action.originalDraft,\n newDraft: action.newDraft,\n retryCount: action.retryCount,\n quotedAt: action.quotedAt,\n };\n case \"error\":\n return { phase: \"error\", error: action.error, draft: action.draft };\n case \"reset\":\n return { phase: \"idle\" };\n default:\n return _state;\n }\n}\n\nexport interface UseQuoteMachineOptions {\n /** Maximum number of re-draft attempts on a market-moved promote failure. Default 3. */\n maxRetries?: number;\n}\n\nexport interface UseQuoteMachineReturn {\n state: QuoteMachineState;\n /** Build params from a `QuoteParams` and fetch a draft quote. Moves to `draft-ready`. */\n getDraft: (params: QuoteParams) => Promise<void>;\n /** Promote a reviewed draft into a signed quote. On market-moved, re-drafts and surfaces `market-moved`. */\n promote: (draft: Quote, retryCount?: number) => Promise<void>;\n /** Accept a re-drafted quote after a `market-moved` and promote it. */\n acceptChanges: (newDraft: Quote, retryCount: number) => Promise<void>;\n /** Promote pre-adjusted params directly via `createQuote` (e.g. after applying a correction hint). */\n correctAndPromote: (originalDraft: Quote, adjustedParams: CreateQuoteParams) => Promise<void>;\n reset: () => void;\n}\n\nexport function useQuoteMachine(options?: UseQuoteMachineOptions): UseQuoteMachineReturn {\n const client = useDimesClient();\n const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n const [state, dispatch] = useReducer(reducer, { phase: \"idle\" } as QuoteMachineState);\n const lastParamsRef = useRef<CreateQuoteParams | null>(null);\n const quotedAtRef = useRef(0);\n\n const getDraft = useCallback(\n async (params: QuoteParams): Promise<void> => {\n dispatch({ type: \"loading\" });\n const quoteParams = buildQuoteParams(params);\n lastParamsRef.current = quoteParams;\n try {\n const draft = await client.createDraftQuote(quoteParams);\n\n quotedAtRef.current = Date.now();\n dispatch({ type: \"draftReady\", draft, quotedAt: quotedAtRef.current });\n } catch (err) {\n dispatch({ type: \"error\", error: err });\n }\n },\n [client],\n );\n\n const promote = useCallback(\n async (draft: Quote, retryCount = 0): Promise<void> => {\n const quotedAt = quotedAtRef.current;\n dispatch({ type: \"promoting\", draft, quotedAt });\n try {\n const promotedQuote = await client.promoteDraftQuote(draft.id);\n dispatch({ type: \"promoted\", draft, promotedQuote, quotedAt });\n } catch (err) {\n if (isMarketMovedError(err) && retryCount < maxRetries && lastParamsRef.current) {\n try {\n const newDraft = await client.createDraftQuote(lastParamsRef.current);\n // eslint-disable-next-line require-atomic-updates -- timestamp ref, no contended state\n quotedAtRef.current = Date.now();\n dispatch({\n type: \"marketMoved\",\n originalDraft: draft,\n newDraft,\n retryCount: retryCount + 1,\n quotedAt: quotedAtRef.current,\n });\n } catch (draftErr) {\n dispatch({ type: \"error\", error: draftErr, draft });\n }\n } else {\n dispatch({ type: \"error\", error: err, draft });\n }\n }\n },\n [client, maxRetries],\n );\n\n const acceptChanges = useCallback(\n async (newDraft: Quote, retryCount: number): Promise<void> => {\n await promote(newDraft, retryCount);\n },\n [promote],\n );\n\n const correctAndPromote = useCallback(\n async (originalDraft: Quote, adjustedParams: CreateQuoteParams): Promise<void> => {\n dispatch({ type: \"promoting\", draft: originalDraft, quotedAt: quotedAtRef.current });\n lastParamsRef.current = adjustedParams;\n try {\n const promotedQuote = await client.createQuote(adjustedParams);\n // eslint-disable-next-line require-atomic-updates -- timestamp ref, no contended state\n quotedAtRef.current = Date.now();\n dispatch({\n type: \"promoted\",\n draft: promotedQuote,\n promotedQuote,\n correctedFrom: originalDraft,\n quotedAt: quotedAtRef.current,\n });\n } catch (err) {\n dispatch({ type: \"error\", error: err });\n }\n },\n [client],\n );\n\n const reset = useCallback((): void => {\n dispatch({ type: \"reset\" });\n lastParamsRef.current = null;\n quotedAtRef.current = 0;\n }, []);\n\n return { state, getDraft, promote, acceptChanges, correctAndPromote, reset };\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { GetMarketsParams, SearchMarketsParams } from \"../client/dimes-client\";\nimport type { Market, Paginated } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function useMarkets(\n params?: GetMarketsParams,\n queryOptions?: Partial<UseQueryOptions<Paginated<Market>>>,\n): UseQueryResult<Paginated<Market>> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"markets\", params],\n queryFn: () => client.getMarkets(params),\n ...queryOptions,\n });\n}\n\nexport function useSearchMarkets(\n params: SearchMarketsParams,\n queryOptions?: Partial<UseQueryOptions<Paginated<Market>>>,\n): UseQueryResult<Paginated<Market>> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"markets\", \"search\", params],\n queryFn: () => client.searchMarkets(params),\n enabled: !!params.query,\n ...queryOptions,\n });\n}\n\nexport function useMarket(ticker: string, queryOptions?: Partial<UseQueryOptions<Market>>): UseQueryResult<Market> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"market\", ticker],\n queryFn: () => client.getMarket(ticker),\n enabled: !!ticker,\n ...queryOptions,\n });\n}\n","import { useQuery, type Query, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { GetPositionsParams } from \"../client/dimes-client\";\nimport type { Position } from \"../types\";\nimport { useDimesClient } from \"./provider\";\nimport { defaultReconciliationWindowMs, reconcilePolledPositions, transientPositionStatuses } from \"./ws-reconcile\";\n\nconst DEFAULT_FAST_POLL_MS = 5_000;\nconst DEFAULT_SLOW_POLL_MS = 15_000;\n\nexport interface UsePositionsOptions {\n /**\n * Appended to the query key so changing scope (e.g. switching wallet) does not serve the previous\n * scope's cached positions until a refetch. Omit to keep the default, scope-less cache key.\n */\n scope?: string | null;\n /**\n * Poll faster while any position is in a transient state (pending/closing/settling/unwinding) and\n * slower otherwise. Pass `true` for the defaults (5s / 15s) or an object to tune them.\n */\n adaptivePolling?: boolean | { fastMs?: number; slowMs?: number };\n /**\n * Defer to fresher WebSocket data: when a position was updated over the socket within the\n * reconciliation window, a slower REST poll won't overwrite it. Use with `usePositionStream` in\n * reconcile mode. Pass `true` for the default window or a number of milliseconds.\n */\n reconcile?: boolean | number;\n}\n\nfunction adaptiveRefetchInterval(\n adaptive: NonNullable<UsePositionsOptions[\"adaptivePolling\"]>,\n): (query: Query<Position[]>) => number {\n const fastMs = typeof adaptive === \"object\" ? (adaptive.fastMs ?? DEFAULT_FAST_POLL_MS) : DEFAULT_FAST_POLL_MS;\n const slowMs = typeof adaptive === \"object\" ? (adaptive.slowMs ?? DEFAULT_SLOW_POLL_MS) : DEFAULT_SLOW_POLL_MS;\n return (query) => (query.state.data?.some((p) => transientPositionStatuses.has(p.status)) ? fastMs : slowMs);\n}\n\nfunction reconcileStructuralSharing(reconcile: number | true): (oldData: unknown, newData: unknown) => Position[] {\n const windowMs = typeof reconcile === \"number\" ? reconcile : defaultReconciliationWindowMs;\n return (oldData, newData) =>\n reconcilePolledPositions(oldData as Position[] | undefined, newData as Position[], windowMs, Date.now());\n}\n\nexport function usePositions(\n params?: GetPositionsParams,\n queryOptions?: Partial<UseQueryOptions<Position[]>>,\n options?: UsePositionsOptions,\n): UseQueryResult<Position[]> {\n const client = useDimesClient();\n\n const queryKey =\n options?.scope !== undefined ? [\"dimes\", \"positions\", params, options.scope] : [\"dimes\", \"positions\", params];\n\n const config: UseQueryOptions<Position[]> = {\n queryKey,\n queryFn: () => client.getPositions(params),\n };\n\n if (options?.adaptivePolling) {\n config.refetchInterval = adaptiveRefetchInterval(options.adaptivePolling);\n }\n\n if (options?.reconcile) {\n config.structuralSharing = reconcileStructuralSharing(options.reconcile);\n }\n\n return useQuery({ ...config, ...queryOptions });\n}\n","import type { QueryClient } from \"@tanstack/react-query\";\nimport type { Market, Paginated, Position } from \"../types\";\nimport type { MarketDelta, PositionEvent } from \"../ws\";\n\n/**\n * Shared plumbing for merging WebSocket events into the React Query cache. Used by the optional\n * reconcile mode of `usePositionStream` / `useMarketStream` and the `reconcile` option on\n * `usePositions`. Kept internal so the query keys and the WS-timestamp registry stay in sync.\n */\n\nexport const positionsQueryKey = [\"dimes\", \"positions\"] as const;\n\nexport const marketsQueryKey = [\"dimes\", \"markets\"] as const;\n\nexport const defaultReconciliationWindowMs = 12_000;\n\n/** Position statuses that indicate an in-flight transition — polled faster by `adaptivePolling`. */\nexport const transientPositionStatuses: ReadonlySet<string> = new Set([\"pending\", \"closing\", \"settling\", \"unwinding\"]);\n\n/**\n * Records the last time each position id was written from a WebSocket event. Polling reconciliation\n * uses this so a slower REST poll never clobbers fresher WS data inside the reconciliation window.\n */\nexport const wsPositionTimestamps = new Map<string, number>();\n\n/** Merge a single position event into every cached positions query. */\nexport function mergePositionEvent(queryClient: QueryClient, event: PositionEvent, now: number): void {\n const position = event.data;\n queryClient.setQueriesData<Position[]>({ queryKey: positionsQueryKey }, (old) => {\n if (!old) {\n return old;\n }\n const idx = old.findIndex((p) => p.id === position.id);\n if (idx >= 0) {\n const next = [...old];\n next[idx] = position;\n return next;\n }\n if (event.type === \"position.created\") {\n return [position, ...old];\n }\n return old;\n });\n wsPositionTimestamps.set(position.id, now);\n}\n\n/**\n * `structuralSharing` for a polled positions list: keep the cached (WS-fresher) copy of any position\n * updated over the socket within `windowMs`, otherwise accept the polled copy.\n */\nexport function reconcilePolledPositions(\n oldData: Position[] | undefined,\n newData: Position[],\n windowMs: number,\n now: number,\n): Position[] {\n if (!oldData) {\n return newData;\n }\n return newData.map((polled) => {\n const wsTime = wsPositionTimestamps.get(polled.id);\n if (wsTime !== undefined && now - wsTime < windowMs) {\n const fresher = oldData.find((p) => p.id === polled.id);\n return fresher ?? polled;\n }\n if (wsTime !== undefined) {\n wsPositionTimestamps.delete(polled.id);\n }\n return polled;\n });\n}\n\n/**\n * Deep-merge a market delta onto a cached market. The nested `leverage` block must be merged rather\n * than replaced — a max-leverage delta carries only the changed leverage fields, so a shallow spread\n * would drop the constant `minBps`/`stepBps` until the next full refetch.\n */\nfunction mergeMarket(prev: Market, delta: MarketDelta): Market {\n return {\n ...prev,\n ...delta,\n leverage: delta.leverage ? { ...prev.leverage, ...delta.leverage } : prev.leverage,\n };\n}\n\n/** Merge market deltas into every cached paginated markets query (no-op for ids not present). */\nexport function mergeMarketDeltas(queryClient: QueryClient, deltas: MarketDelta[]): void {\n queryClient.setQueriesData<Paginated<Market>>({ queryKey: marketsQueryKey }, (old) => {\n if (!old) {\n return old;\n }\n const data = old.data.map((market) => {\n const delta = deltas.find((d) => d.id === market.id);\n return delta ? mergeMarket(market, delta) : market;\n });\n const changed = data.some((market, i) => market !== old.data[i]);\n return changed ? { ...old, data } : old;\n });\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { ContractInfo } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\nexport function useContractInfo(queryOptions?: Partial<UseQueryOptions<ContractInfo>>): UseQueryResult<ContractInfo> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"contractInfo\"],\n queryFn: () => client.getContractInfo(),\n staleTime: Infinity,\n ...queryOptions,\n });\n}\n","import { useQuery, type UseQueryOptions, type UseQueryResult } from \"@tanstack/react-query\";\nimport type { CustomerLimit } from \"../types\";\nimport { useDimesClient } from \"./provider\";\n\n/** User trading limits (JWT auth) — `GET /user-limits`. */\nexport function useUserLimits(queryOptions?: Partial<UseQueryOptions<CustomerLimit>>): UseQueryResult<CustomerLimit> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"user-limits\"],\n queryFn: () => client.getUserLimits(),\n ...queryOptions,\n });\n}\n\n/** Partner-wide limits (API-key auth) — `GET /partner-limits`. */\nexport function usePartnerLimits(\n queryOptions?: Partial<UseQueryOptions<CustomerLimit>>,\n): UseQueryResult<CustomerLimit> {\n const client = useDimesClient();\n\n return useQuery({\n queryKey: [\"dimes\", \"partner-limits\"],\n queryFn: () => client.getPartnerLimits(),\n ...queryOptions,\n });\n}\n\n/** @deprecated Use {@link useUserLimits}. Alias kept for back-compat; resolves to user limits. */\nexport function useLimits(queryOptions?: Partial<UseQueryOptions<CustomerLimit>>): UseQueryResult<CustomerLimit> {\n return useUserLimits(queryOptions);\n}\n","import { useMutation, type UseMutationOptions, type UseMutationResult } from \"@tanstack/react-query\";\nimport { DimesApiError } from \"../errors/dimes-error\";\nimport { useDimesClient } from \"./provider\";\n\nconst HTTP_CONFLICT = 409;\n\nexport type CancelPositionResult = \"cancelled\" | \"already_cancelling\";\n\nexport interface UseCancelPositionOptions {\n /**\n * Treat a 409 Conflict (the position is already being cancelled) as success, resolving to\n * `\"already_cancelling\"` instead of throwing. Default false — a 409 rejects like any other error.\n */\n treatConflictAsAlreadyCancelling?: boolean;\n}\n\nexport function useCancelPosition(\n mutationOptions?: Partial<UseMutationOptions<CancelPositionResult, Error, string>>,\n options?: UseCancelPositionOptions,\n): UseMutationResult<CancelPositionResult, Error, string> {\n const client = useDimesClient();\n const treatConflictAsAlreadyCancelling = options?.treatConflictAsAlreadyCancelling ?? false;\n\n return useMutation({\n mutationFn: async (positionId: string): Promise<CancelPositionResult> => {\n try {\n await client.cancelPosition(positionId);\n return \"cancelled\";\n } catch (err) {\n if (treatConflictAsAlreadyCancelling && err instanceof DimesApiError && err.status === HTTP_CONFLICT) {\n return \"already_cancelling\";\n }\n throw err;\n }\n },\n ...mutationOptions,\n });\n}\n","import { useQueryClient } from \"@tanstack/react-query\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { PositionSocket, type NotificationEvent, type PositionEvent } from \"../ws\";\nimport { useDimesClient } from \"./provider\";\nimport { mergePositionEvent, positionsQueryKey } from \"./ws-reconcile\";\n\nexport type StreamMode = \"raw\" | \"reconcile\";\n\nexport interface UsePositionStreamOptions {\n /** Connect the socket. Default true. Set false to gate on auth being ready. */\n enabled?: boolean;\n /**\n * `\"reconcile\"` (default) merges every event into the `usePositions` query cache so the UI updates\n * instantly; `\"raw\"` does not touch the cache and only forwards events to your callbacks.\n */\n mode?: StreamMode;\n /** Disconnect while the tab is hidden and reconnect when it becomes visible again. Default true. */\n pauseOnHidden?: boolean;\n /** Invalidate the positions query on reconnect (skipping the first connect) to catch missed events. Default true. */\n invalidateOnReconnect?: boolean;\n /** Always called with the raw (camelCased) event, in both modes. */\n onEvent?: (event: PositionEvent) => void;\n /** Called with user-gateway notification events (toasts, fill progress…). Never touches the cache. */\n onNotification?: (event: NotificationEvent) => void;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: unknown) => void;\n}\n\nexport interface UsePositionStreamResult {\n socket: PositionSocket | null;\n connected: boolean;\n}\n\n/**\n * Subscribe to the user position WebSocket gateway. In `reconcile` mode (default) events are merged\n * into the React Query cache used by `usePositions`; in `raw` mode you handle events yourself via\n * `onEvent`. App-specific side effects (toasts, stores) belong in the callbacks, not the SDK.\n */\nexport function usePositionStream(options?: UsePositionStreamOptions): UsePositionStreamResult {\n const client = useDimesClient();\n const queryClient = useQueryClient();\n const socketRef = useRef<PositionSocket | null>(null);\n const [connected, setConnected] = useState(false);\n\n const enabled = options?.enabled ?? true;\n const mode = options?.mode ?? \"reconcile\";\n const pauseOnHidden = options?.pauseOnHidden ?? true;\n const invalidateOnReconnect = options?.invalidateOnReconnect ?? true;\n\n // Keep the latest callbacks/flags in a ref so the socket effect does not reconnect on every render.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n useEffect(() => {\n if (!enabled) {\n return undefined;\n }\n\n const socket = new PositionSocket({\n baseUrl: client.baseUrl,\n getToken: (): string | null => client.getToken(),\n });\n socketRef.current = socket;\n\n const unsubEvent = socket.on(\"*\", (event) => {\n if (mode === \"reconcile\") {\n mergePositionEvent(queryClient, event, Date.now());\n }\n optionsRef.current?.onEvent?.(event);\n });\n\n const unsubNotification = socket.onNotification((event) => {\n optionsRef.current?.onNotification?.(event);\n });\n\n let firstConnect = true;\n const unsubConnect = socket.onConnect(() => {\n setConnected(true);\n if (firstConnect) {\n firstConnect = false;\n } else if (mode === \"reconcile\" && invalidateOnReconnect) {\n void queryClient.invalidateQueries({ queryKey: positionsQueryKey });\n }\n optionsRef.current?.onConnect?.();\n });\n\n const unsubDisconnect = socket.onDisconnect(() => {\n setConnected(false);\n optionsRef.current?.onDisconnect?.();\n });\n\n const unsubError = socket.onError((error) => {\n optionsRef.current?.onError?.(error);\n });\n\n const handleVisibility =\n pauseOnHidden && typeof document !== \"undefined\"\n ? (): void => {\n if (document.hidden) {\n socket.disconnect();\n } else {\n socket.connect();\n }\n }\n : null;\n if (handleVisibility) {\n document.addEventListener(\"visibilitychange\", handleVisibility);\n }\n\n socket.connect();\n\n return (): void => {\n if (handleVisibility) {\n document.removeEventListener(\"visibilitychange\", handleVisibility);\n }\n unsubEvent();\n unsubNotification();\n unsubConnect();\n unsubDisconnect();\n unsubError();\n socket.disconnect();\n socketRef.current = null;\n setConnected(false);\n };\n }, [client, queryClient, enabled, mode, pauseOnHidden, invalidateOnReconnect]);\n\n return { socket: socketRef.current, connected };\n}\n","import { useQueryClient } from \"@tanstack/react-query\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { MarketSocket, type MarketDelta, type MarketEvent } from \"../ws\";\nimport { useDimesClient } from \"./provider\";\nimport type { StreamMode } from \"./use-position-stream\";\nimport { marketsQueryKey, mergeMarketDeltas } from \"./ws-reconcile\";\n\nexport interface UseMarketStreamOptions {\n /** Connect the socket. Default true. */\n enabled?: boolean;\n /**\n * `\"reconcile\"` (default) merges `eligibility_changed` / `max_leverage_changed` deltas into the\n * `useMarkets` query cache; `\"raw\"` only forwards events. `market.discovered` events are never\n * injected into the paginated cache (that would pollute server-filtered views) — handle them via\n * `onEvent` in either mode.\n */\n mode?: StreamMode;\n /** Disconnect while the tab is hidden and reconnect when visible again. Default true. */\n pauseOnHidden?: boolean;\n /** Invalidate the markets query on reconnect (skipping the first connect). Default true. */\n invalidateOnReconnect?: boolean;\n /** Always called with the raw (camelCased) event, in both modes. */\n onEvent?: (event: MarketEvent) => void;\n onConnect?: () => void;\n onDisconnect?: () => void;\n onError?: (error: unknown) => void;\n}\n\nexport interface UseMarketStreamResult {\n socket: MarketSocket | null;\n connected: boolean;\n}\n\n/**\n * Subscribe to the user market WebSocket gateway. In `reconcile` mode (default) eligibility and\n * max-leverage deltas are deep-merged into the `useMarkets` cache; discovered markets are forwarded\n * to `onEvent` for the app to route (e.g. a \"new markets\" strip).\n */\nexport function useMarketStream(options?: UseMarketStreamOptions): UseMarketStreamResult {\n const client = useDimesClient();\n const queryClient = useQueryClient();\n const socketRef = useRef<MarketSocket | null>(null);\n const [connected, setConnected] = useState(false);\n\n const enabled = options?.enabled ?? true;\n const mode = options?.mode ?? \"reconcile\";\n const pauseOnHidden = options?.pauseOnHidden ?? true;\n const invalidateOnReconnect = options?.invalidateOnReconnect ?? true;\n\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n useEffect(() => {\n if (!enabled) {\n return undefined;\n }\n\n const socket = new MarketSocket({\n baseUrl: client.baseUrl,\n getToken: (): string | null => client.getToken(),\n });\n socketRef.current = socket;\n\n const unsubEvent = socket.on(\"*\", (event) => {\n if (mode === \"reconcile\" && event.type !== \"market.discovered\") {\n mergeMarketDeltas(queryClient, event.data as MarketDelta[]);\n }\n optionsRef.current?.onEvent?.(event);\n });\n\n let firstConnect = true;\n const unsubConnect = socket.onConnect(() => {\n setConnected(true);\n if (firstConnect) {\n firstConnect = false;\n } else if (mode === \"reconcile\" && invalidateOnReconnect) {\n void queryClient.invalidateQueries({ queryKey: marketsQueryKey });\n }\n optionsRef.current?.onConnect?.();\n });\n\n const unsubDisconnect = socket.onDisconnect(() => {\n setConnected(false);\n optionsRef.current?.onDisconnect?.();\n });\n\n const unsubError = socket.onError((error) => {\n optionsRef.current?.onError?.(error);\n });\n\n const handleVisibility =\n pauseOnHidden && typeof document !== \"undefined\"\n ? (): void => {\n if (document.hidden) {\n socket.disconnect();\n } else {\n socket.connect();\n }\n }\n : null;\n if (handleVisibility) {\n document.addEventListener(\"visibilitychange\", handleVisibility);\n }\n\n socket.connect();\n\n return (): void => {\n if (handleVisibility) {\n document.removeEventListener(\"visibilitychange\", handleVisibility);\n }\n unsubEvent();\n unsubConnect();\n unsubDisconnect();\n unsubError();\n socket.disconnect();\n socketRef.current = null;\n setConnected(false);\n };\n }, [client, queryClient, enabled, mode, pauseOnHidden, invalidateOnReconnect]);\n\n return { socket: socketRef.current, connected };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,eAAe,kBAAkC;AAcjD;AATT,IAAM,eAAe,cAAkC,IAAI;AAQpD,SAAS,cAAc,EAAE,QAAQ,SAAS,GAAuB;AACtE,SAAO,oBAAC,aAAa,UAAb,EAAsB,OAAO,QAAS,UAAS;AACzD;AAEO,SAAS,iBAA8B;AAC5C,QAAM,SAAS,WAAW,YAAY;AACtC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,WAAW,oBAAoB,sDAAsD;AAAA,EACjG;AACA,SAAO;AACT;;;ACvBA,SAAS,aAAa,kBAAkB;AA8BxC,SAAS,QAAQ,OAAmB,QAA4B;AAC9D,UAAQ,OAA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SAAS,eAAe;AAAA,IACrC,CAAC;AAED,UAAM,aAAa,OAAO,QAAQ,CAAC,UAAU;AAC3C,iBAAW,SAAS,UAAU,KAAK;AAAA,IACrC,CAAC;AAED,UAAM,mBACJ,iBAAiB,OAAO,aAAa,cACjC,MAAY;AACV,UAAI,SAAS,QAAQ;AACnB,eAAO,WAAW;AAAA,MACpB,OAAO;AACL,eAAO,QAAQ;AAAA,MACjB;AAAA,IACF,IACA;AACN,QAAI,kBAAkB;AACpB,eAAS,iBAAiB,oBAAoB,gBAAgB;AAAA,IAChE;AAEA,WAAO,QAAQ;AAEf,WAAO,MAAY;AACjB,UAAI,kBAAkB;AACpB,iBAAS,oBAAoB,oBAAoB,gBAAgB;AAAA,MACnE;AACA,iBAAW;AACX,mBAAa;AACb,sBAAgB;AAChB,iBAAW;AACX,aAAO,WAAW;AAClB,gBAAU,UAAU;AACpB,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF,GAAG,CAAC,QAAQ,aAAa,SAAS,MAAM,eAAe,qBAAqB,CAAC;AAE7E,SAAO,EAAE,QAAQ,UAAU,SAAS,UAAU;AAChD;","names":["useCallback","useReducer","reducer","useReducer","useCallback","useQuery","useQuery","useQuery","useQuery","useQuery","useQuery","useRef","useRef","useQueryClient","useEffect","useRef","useState","useQueryClient","useRef","useState","useEffect"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { P as Position, M as Market,
|
|
1
|
+
import { P as Position, M as Market, a as MarketPolymarket, b as MarketLeverage } from './aliases-BJyM8ydu.js';
|
|
2
2
|
|
|
3
|
-
declare const positionEventTypes: readonly ["position.cancelled", "position.close_requested", "position.closed", "position.created", "position.force_unwound", "position.liquidated", "position.opened", "position.opening", "position.reverted", "position.settled"];
|
|
3
|
+
declare const positionEventTypes: readonly ["position.cancelled", "position.close_requested", "position.closed", "position.created", "position.force_unwound", "position.liquidated", "position.opened", "position.opening", "position.partial_close_requested", "position.partial_close_initiated", "position.partial_closed", "position.partial_close_aborted", "position.reverted", "position.settled"];
|
|
4
4
|
type PositionEventType = (typeof positionEventTypes)[number];
|
|
5
5
|
interface PositionEventEnvelope {
|
|
6
6
|
id: string;
|
|
@@ -57,4 +57,4 @@ declare const notificationCodes: {
|
|
|
57
57
|
};
|
|
58
58
|
type NotificationCode = (typeof notificationCodes)[keyof typeof notificationCodes];
|
|
59
59
|
|
|
60
|
-
export { type
|
|
60
|
+
export { type MarketEvent as M, type NotificationEvent as N, type PositionEvent as P, type PositionEventType as a, type MarketEventType as b, type MarketDelta as c, type MarketEventEnvelope as d, type NotificationCode as e, type NotificationEventEnvelope as f, type PositionEventEnvelope as g, marketEventTypes as m, notificationCodes as n, positionEventTypes as p };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { P as Position, M as Market,
|
|
1
|
+
import { P as Position, M as Market, a as MarketPolymarket, b as MarketLeverage } from './aliases-BJyM8ydu.cjs';
|
|
2
2
|
|
|
3
|
-
declare const positionEventTypes: readonly ["position.cancelled", "position.close_requested", "position.closed", "position.created", "position.force_unwound", "position.liquidated", "position.opened", "position.opening", "position.reverted", "position.settled"];
|
|
3
|
+
declare const positionEventTypes: readonly ["position.cancelled", "position.close_requested", "position.closed", "position.created", "position.force_unwound", "position.liquidated", "position.opened", "position.opening", "position.partial_close_requested", "position.partial_close_initiated", "position.partial_closed", "position.partial_close_aborted", "position.reverted", "position.settled"];
|
|
4
4
|
type PositionEventType = (typeof positionEventTypes)[number];
|
|
5
5
|
interface PositionEventEnvelope {
|
|
6
6
|
id: string;
|
|
@@ -57,4 +57,4 @@ declare const notificationCodes: {
|
|
|
57
57
|
};
|
|
58
58
|
type NotificationCode = (typeof notificationCodes)[keyof typeof notificationCodes];
|
|
59
59
|
|
|
60
|
-
export { type
|
|
60
|
+
export { type MarketEvent as M, type NotificationEvent as N, type PositionEvent as P, type PositionEventType as a, type MarketEventType as b, type MarketDelta as c, type MarketEventEnvelope as d, type NotificationCode as e, type NotificationEventEnvelope as f, type PositionEventEnvelope as g, marketEventTypes as m, notificationCodes as n, positionEventTypes as p };
|