@orderly.network/hooks 0.0.43 → 0.0.45

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/dist/index.js ADDED
@@ -0,0 +1,2296 @@
1
+ 'use strict';
2
+
3
+ var React2 = require('react');
4
+ var useSWR = require('swr');
5
+ var net = require('@orderly.network/net');
6
+ var useSWRMutation = require('swr/mutation');
7
+ var useConstant = require('use-constant');
8
+ var core = require('@orderly.network/core');
9
+ var types = require('@orderly.network/types');
10
+ var useSWRSubscription = require('swr/subscription');
11
+ var utils = require('@orderly.network/utils');
12
+ var ramda = require('ramda');
13
+ var futures = require('@orderly.network/futures');
14
+ var useSWRInfinite = require('swr/infinite');
15
+
16
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
17
+
18
+ var React2__default = /*#__PURE__*/_interopDefault(React2);
19
+ var useSWR__default = /*#__PURE__*/_interopDefault(useSWR);
20
+ var useSWRMutation__default = /*#__PURE__*/_interopDefault(useSWRMutation);
21
+ var useConstant__default = /*#__PURE__*/_interopDefault(useConstant);
22
+ var useSWRSubscription__default = /*#__PURE__*/_interopDefault(useSWRSubscription);
23
+ var useSWRInfinite__default = /*#__PURE__*/_interopDefault(useSWRInfinite);
24
+
25
+ var __defProp = Object.defineProperty;
26
+ var __defProps = Object.defineProperties;
27
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
28
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
29
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
30
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
31
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
32
+ var __spreadValues = (a, b) => {
33
+ for (var prop2 in b || (b = {}))
34
+ if (__hasOwnProp.call(b, prop2))
35
+ __defNormalProp(a, prop2, b[prop2]);
36
+ if (__getOwnPropSymbols)
37
+ for (var prop2 of __getOwnPropSymbols(b)) {
38
+ if (__propIsEnum.call(b, prop2))
39
+ __defNormalProp(a, prop2, b[prop2]);
40
+ }
41
+ return a;
42
+ };
43
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
44
+ var __objRest = (source, exclude) => {
45
+ var target = {};
46
+ for (var prop2 in source)
47
+ if (__hasOwnProp.call(source, prop2) && exclude.indexOf(prop2) < 0)
48
+ target[prop2] = source[prop2];
49
+ if (source != null && __getOwnPropSymbols)
50
+ for (var prop2 of __getOwnPropSymbols(source)) {
51
+ if (exclude.indexOf(prop2) < 0 && __propIsEnum.call(source, prop2))
52
+ target[prop2] = source[prop2];
53
+ }
54
+ return target;
55
+ };
56
+ var __export = (target, all) => {
57
+ for (var name in all)
58
+ __defProp(target, name, { get: all[name], enumerable: true });
59
+ };
60
+ var __async = (__this, __arguments, generator) => {
61
+ return new Promise((resolve, reject) => {
62
+ var fulfilled = (value) => {
63
+ try {
64
+ step(generator.next(value));
65
+ } catch (e) {
66
+ reject(e);
67
+ }
68
+ };
69
+ var rejected = (value) => {
70
+ try {
71
+ step(generator.throw(value));
72
+ } catch (e) {
73
+ reject(e);
74
+ }
75
+ };
76
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
77
+ step((generator = generator.apply(__this, __arguments)).next());
78
+ });
79
+ };
80
+ var OrderlyContext = React2.createContext({
81
+ // configStore: new MemoryConfigStore(),
82
+ });
83
+ var OrderlyProvider = OrderlyContext.Provider;
84
+ var fetcher = (url, init = {}, queryOptions) => net.get(url, init, queryOptions == null ? void 0 : queryOptions.formatter);
85
+
86
+ // src/useQuery.ts
87
+ var useQuery = (query, options) => {
88
+ const { apiBaseUrl } = React2.useContext(OrderlyContext);
89
+ const _a = options || {}, { formatter } = _a, swrOptions = __objRest(_a, ["formatter"]);
90
+ if (typeof apiBaseUrl === "undefined") {
91
+ throw new Error("please add OrderlyProvider to your app");
92
+ }
93
+ return useSWR__default.default(
94
+ // `${apiBaseUrl}${query}`,
95
+ query,
96
+ (url, init) => fetcher(url.startsWith("http") ? url : `${apiBaseUrl}${url}`, init, {
97
+ formatter
98
+ }),
99
+ swrOptions
100
+ );
101
+ };
102
+ var useAccountInstance = () => {
103
+ const { configStore, keyStore, contractManager, getWalletAdapter } = React2.useContext(OrderlyContext);
104
+ if (!configStore)
105
+ throw new Error("configStore is not defined, please use OrderlyProvider");
106
+ if (!keyStore) {
107
+ throw new Error(
108
+ "keyStore is not defined, please use OrderlyProvider and provide keyStore"
109
+ );
110
+ }
111
+ const account5 = useConstant__default.default(() => {
112
+ let account6 = core.SimpleDI.get("account");
113
+ if (!account6) {
114
+ account6 = new core.Account(
115
+ configStore,
116
+ keyStore,
117
+ contractManager,
118
+ getWalletAdapter
119
+ // walletAdapter
120
+ );
121
+ core.SimpleDI.registerByName("account", account6);
122
+ }
123
+ return account6;
124
+ });
125
+ return account5;
126
+ };
127
+
128
+ // src/useMutation.ts
129
+ var fetcher2 = (url, options) => {
130
+ const init = {
131
+ method: options.arg.method,
132
+ headers: __spreadValues({}, options.arg.signature)
133
+ };
134
+ if (options.arg.data) {
135
+ init.body = JSON.stringify(options.arg.data);
136
+ }
137
+ if (typeof options.arg.params === "object" && Object.keys(options.arg.params).length) {
138
+ let search = new URLSearchParams(options.arg.params);
139
+ url = `${url}?${search.toString()}`;
140
+ }
141
+ return net.mutate(url, init);
142
+ };
143
+ var useMutation = (url, method = "POST", options) => {
144
+ const { apiBaseUrl } = React2.useContext(OrderlyContext);
145
+ let fullUrl = url;
146
+ if (!url.startsWith("http")) {
147
+ fullUrl = `${apiBaseUrl}${url}`;
148
+ }
149
+ const account5 = useAccountInstance();
150
+ const signer = account5.signer;
151
+ const { trigger, data, error, reset, isMutating } = useSWRMutation__default.default(
152
+ fullUrl,
153
+ // method === "POST" ? fetcher : deleteFetcher,
154
+ fetcher2,
155
+ options
156
+ );
157
+ const mutation = (data2, params) => __async(void 0, null, function* () {
158
+ let newUrl = url;
159
+ if (typeof params === "object" && Object.keys(params).length) {
160
+ let search = new URLSearchParams(params);
161
+ newUrl = `${url}?${search.toString()}`;
162
+ }
163
+ const payload = {
164
+ method,
165
+ url: newUrl,
166
+ data: data2
167
+ };
168
+ const signature = yield signer.sign(payload);
169
+ return trigger({
170
+ data: data2,
171
+ params,
172
+ method,
173
+ signature: __spreadProps(__spreadValues({}, signature), {
174
+ "orderly-account-id": account5.accountId
175
+ })
176
+ });
177
+ });
178
+ return [
179
+ mutation,
180
+ {
181
+ data,
182
+ error,
183
+ reset,
184
+ isMutating
185
+ }
186
+ ];
187
+ };
188
+ var signatureMiddleware = (useSWRNext) => {
189
+ const { apiBaseUrl } = React2.useContext(OrderlyContext);
190
+ return (key, fetcher4, config) => {
191
+ try {
192
+ const extendedFetcher = (args) => __async(void 0, null, function* () {
193
+ let url = Array.isArray(args) ? args[0] : args;
194
+ let account5 = core.SimpleDI.get("account");
195
+ let fullUrl = `${apiBaseUrl}${url}`;
196
+ const signer = account5.signer;
197
+ const payload = {
198
+ method: "GET",
199
+ url
200
+ };
201
+ const signature = yield signer.sign(payload);
202
+ return fetcher4(fullUrl, {
203
+ headers: __spreadProps(__spreadValues({}, signature), {
204
+ "orderly-account-id": account5.accountId
205
+ })
206
+ });
207
+ });
208
+ return useSWRNext(key, extendedFetcher, config);
209
+ } catch (e) {
210
+ console.error("signature error:", e);
211
+ throw e;
212
+ }
213
+ };
214
+ };
215
+ var useAccount = () => {
216
+ const {
217
+ configStore,
218
+ keyStore,
219
+ onWalletConnect,
220
+ onWalletDisconnect,
221
+ onSetChain
222
+ } = React2.useContext(OrderlyContext);
223
+ if (!configStore)
224
+ throw new Error("configStore is not defined, please use OrderlyProvider");
225
+ if (!keyStore) {
226
+ throw new Error(
227
+ "keyStore is not defined, please use OrderlyProvider and provide keyStore"
228
+ );
229
+ }
230
+ const account5 = useAccountInstance();
231
+ const [state, setState] = React2.useState(account5.stateValue);
232
+ const statusChangeHandler = (nextState) => {
233
+ setState(() => nextState);
234
+ };
235
+ React2.useEffect(() => {
236
+ account5.on("change:status", statusChangeHandler);
237
+ return () => {
238
+ account5.off("change:status", statusChangeHandler);
239
+ };
240
+ }, []);
241
+ const login = React2.useCallback(
242
+ (address) => {
243
+ account5.login(address);
244
+ },
245
+ [account5]
246
+ );
247
+ const createOrderlyKey = React2.useCallback(
248
+ (remember) => __async(void 0, null, function* () {
249
+ return account5.createOrderlyKey(remember ? 365 : 30);
250
+ }),
251
+ [account5]
252
+ );
253
+ const createAccount = React2.useCallback(() => __async(void 0, null, function* () {
254
+ return account5.createAccount();
255
+ }), [account5]);
256
+ const connect = React2.useCallback(() => __async(void 0, null, function* () {
257
+ return onWalletConnect == null ? void 0 : onWalletConnect();
258
+ }), [account5]);
259
+ const disconnect = () => __async(void 0, null, function* () {
260
+ return onWalletDisconnect == null ? void 0 : onWalletDisconnect();
261
+ });
262
+ const setChain = (chainId) => __async(void 0, null, function* () {
263
+ return onSetChain == null ? void 0 : onSetChain(chainId);
264
+ });
265
+ return {
266
+ // account: state!,
267
+ account: account5,
268
+ state,
269
+ // info: {},
270
+ login,
271
+ createOrderlyKey,
272
+ createAccount,
273
+ disconnect,
274
+ connect,
275
+ setChain
276
+ // settlement,
277
+ };
278
+ };
279
+ var usePrivateQuery = (query, options) => {
280
+ var _b;
281
+ const _a = options || {}, { formatter } = _a, swrOptions = __objRest(_a, ["formatter"]);
282
+ const account5 = useAccount();
283
+ const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_b = options == null ? void 0 : options.use) != null ? _b : [] : [];
284
+ return useSWR__default.default(
285
+ () => account5.state.status >= types.AccountStatusEnum.EnableTrading ? [query, account5.state.accountId] : null,
286
+ // query,
287
+ (url, init) => {
288
+ return fetcher(url, init, { formatter });
289
+ },
290
+ __spreadProps(__spreadValues({}, swrOptions), {
291
+ use: [signatureMiddleware, ...middleware],
292
+ onError: (err) => {
293
+ console.log("usePrivateQuery error", err);
294
+ }
295
+ })
296
+ );
297
+ };
298
+
299
+ // src/useTradingView.ts
300
+ var useTradingView = () => {
301
+ return {};
302
+ };
303
+ var usePrivateObserve = () => {
304
+ const [data, setData] = React2.useState();
305
+ React2.useEffect(() => {
306
+ return () => {
307
+ };
308
+ }, []);
309
+ return {
310
+ data
311
+ };
312
+ };
313
+ var useTopicObserve = (topic) => {
314
+ const [data, setData] = React2.useState();
315
+ React2.useEffect(() => {
316
+ return () => {
317
+ };
318
+ }, []);
319
+ return {
320
+ data
321
+ };
322
+ };
323
+ var useAppState = () => {
324
+ const { errors, ready } = React2.useContext(OrderlyContext);
325
+ return {
326
+ errors,
327
+ ready
328
+ };
329
+ };
330
+
331
+ // src/usePreloadData.ts
332
+ var usePreLoadData = (onSuccess) => {
333
+ useSWR__default.default(
334
+ "https://fi-api.woo.org/swap_support",
335
+ (url) => fetch(url).then((res) => res.json()),
336
+ {
337
+ revalidateOnFocus: false,
338
+ // suspense: true,
339
+ onSuccess: (data, key, config) => {
340
+ onSuccess("chains_fetch");
341
+ }
342
+ }
343
+ );
344
+ };
345
+ var useEventEmitter = (channel) => {
346
+ return useConstant__default.default(() => {
347
+ let ee = core.SimpleDI.get("EE");
348
+ if (!ee) {
349
+ ee = new core.EventEmitter();
350
+ core.SimpleDI.registerByName("EE", ee);
351
+ }
352
+ return ee;
353
+ });
354
+ };
355
+
356
+ // src/utils/json.ts
357
+ function parseJSON(value) {
358
+ try {
359
+ return value === "undefined" ? void 0 : JSON.parse(value != null ? value : "");
360
+ } catch (e) {
361
+ console.log("parsing error on", { value });
362
+ return void 0;
363
+ }
364
+ }
365
+
366
+ // src/useSessionStorage.ts
367
+ function useSessionStorage(key, initialValue) {
368
+ const readValue = React2.useCallback(() => {
369
+ if (typeof window === "undefined") {
370
+ return initialValue;
371
+ }
372
+ try {
373
+ const item = window.sessionStorage.getItem(key);
374
+ return item ? parseJSON(item) : initialValue;
375
+ } catch (error) {
376
+ console.warn(`Error reading sessionStorage key \u201C${key}\u201D:`, error);
377
+ return initialValue;
378
+ }
379
+ }, [initialValue, key]);
380
+ const [storedValue, setStoredValue] = React2.useState(readValue);
381
+ const setValue = (value) => {
382
+ if (typeof window == "undefined") {
383
+ console.warn(
384
+ `Tried setting sessionStorage key \u201C${key}\u201D even though environment is not a client`
385
+ );
386
+ }
387
+ try {
388
+ const newValue = value instanceof Function ? value(storedValue) : value;
389
+ window.sessionStorage.setItem(key, JSON.stringify(newValue));
390
+ setStoredValue(newValue);
391
+ } catch (error) {
392
+ console.warn(`Error setting sessionStorage key \u201C${key}\u201D:`, error);
393
+ }
394
+ };
395
+ React2.useEffect(() => {
396
+ setStoredValue(readValue());
397
+ }, []);
398
+ React2.useEffect(() => {
399
+ if (typeof window == "undefined") {
400
+ return;
401
+ }
402
+ window.addEventListener("storage", handleStorageChange);
403
+ return () => {
404
+ window.removeEventListener("storage", handleStorageChange);
405
+ };
406
+ });
407
+ const handleStorageChange = React2.useCallback(
408
+ (event) => {
409
+ if ((event == null ? void 0 : event.key) && event.key !== key) {
410
+ return;
411
+ }
412
+ setStoredValue(readValue());
413
+ },
414
+ [key, readValue]
415
+ );
416
+ return [storedValue, setValue];
417
+ }
418
+ function useLocalStorage(key, initialValue) {
419
+ const readValue = React2.useCallback(() => {
420
+ if (typeof window === "undefined") {
421
+ return initialValue;
422
+ }
423
+ try {
424
+ const item = window.localStorage.getItem(key);
425
+ return item ? parseJSON(item) : initialValue;
426
+ } catch (error) {
427
+ console.warn(`Error reading localStorage key \u201C${key}\u201D:`, error);
428
+ return initialValue;
429
+ }
430
+ }, [initialValue, key]);
431
+ const [storedValue, setStoredValue] = React2.useState(readValue);
432
+ const setValue = React2.useCallback(
433
+ (value) => {
434
+ if (typeof window === "undefined") {
435
+ console.warn(
436
+ `Tried setting localStorage key \u201C${key}\u201D even though environment is not a client`
437
+ );
438
+ }
439
+ try {
440
+ const newValue = value instanceof Function ? value(storedValue) : value;
441
+ window.localStorage.setItem(key, JSON.stringify(newValue));
442
+ setStoredValue(() => newValue);
443
+ } catch (error) {
444
+ console.warn(`Error setting localStorage key \u201C${key}\u201D:`, error);
445
+ }
446
+ },
447
+ [storedValue]
448
+ );
449
+ React2.useEffect(() => {
450
+ setStoredValue(readValue());
451
+ }, []);
452
+ return [storedValue, setValue];
453
+ }
454
+ var useRunOnce = ({ fn, sessionKey }) => {
455
+ const triggered = React2.useRef(false);
456
+ React2.useEffect(() => {
457
+ const hasBeenTriggered = sessionKey ? sessionStorage.getItem(sessionKey) : triggered.current;
458
+ if (!hasBeenTriggered) {
459
+ fn();
460
+ triggered.current = true;
461
+ if (sessionKey) {
462
+ sessionStorage.setItem(sessionKey, "true");
463
+ }
464
+ }
465
+ }, [fn, sessionKey]);
466
+ return null;
467
+ };
468
+ var DataSourceContext = React2.createContext({});
469
+ var DataSourceProvider = (props) => {
470
+ console.log("render DataSourceProvider");
471
+ useAccountInstance();
472
+ useConstant__default.default(() => {
473
+ });
474
+ return /* @__PURE__ */ React2__default.default.createElement(DataSourceContext.Provider, { value: {} }, props.children);
475
+ };
476
+ var WS_NAME = "nativeWebsocketClient";
477
+ var useWS = () => {
478
+ useAccount();
479
+ const { configStore } = React2.useContext(OrderlyContext);
480
+ const ws = useConstant__default.default(() => {
481
+ let websocketClient = core.SimpleDI.get(WS_NAME);
482
+ const account5 = core.SimpleDI.get(core.Account.instanceName);
483
+ if (!websocketClient) {
484
+ websocketClient = new net.WS({
485
+ // accountId: "OqdphuyCtYWxwzhxyLLjOWNdFP7sQt8RPWzmb5xY",
486
+ networkId: "testnet",
487
+ publicUrl: configStore.get("publicWsUrl"),
488
+ privateUrl: configStore.get("privateWsUrl"),
489
+ onSigntureRequest: (accountId) => __async(void 0, null, function* () {
490
+ const signer = account5.signer;
491
+ const timestamp = (/* @__PURE__ */ new Date()).getTime();
492
+ const result = yield signer.signText(timestamp.toString());
493
+ return __spreadProps(__spreadValues({}, result), { timestamp });
494
+ })
495
+ });
496
+ account5.on("change:status", (nextState) => {
497
+ if (nextState.status === types.AccountStatusEnum.EnableTrading && nextState.accountId) {
498
+ websocketClient.openPrivate(nextState.accountId);
499
+ }
500
+ });
501
+ core.SimpleDI.registerByName(WS_NAME, websocketClient);
502
+ }
503
+ return websocketClient;
504
+ });
505
+ return ws;
506
+ };
507
+ var useConfig = () => {
508
+ const { configStore } = React2.useContext(OrderlyContext);
509
+ return configStore;
510
+ };
511
+ var useTickerStream = (symbol) => {
512
+ if (!symbol) {
513
+ throw new Error("useFuturesForSymbol requires a symbol");
514
+ }
515
+ const { data: info } = useQuery(
516
+ `/v1/public/futures/${symbol}`,
517
+ {
518
+ revalidateOnFocus: false
519
+ }
520
+ );
521
+ const ws = useWS();
522
+ const { data: ticker } = useSWRSubscription__default.default(
523
+ `${symbol}@ticker`,
524
+ (key, { next }) => {
525
+ const unsubscribe = ws.subscribe(
526
+ // { event: "subscribe", topic: "markprices" },
527
+ `${symbol}@ticker`,
528
+ {
529
+ onMessage: (message) => {
530
+ next(null, message);
531
+ }
532
+ // onUnsubscribe: () => {
533
+ // return "markprices";
534
+ // },
535
+ // onError: (error: any) => {
536
+ // console.log("error", error);
537
+ // },
538
+ }
539
+ );
540
+ return () => {
541
+ console.log("unsubscribe!!!!!!!");
542
+ unsubscribe == null ? void 0 : unsubscribe();
543
+ };
544
+ }
545
+ );
546
+ const value = React2.useMemo(() => {
547
+ if (!info)
548
+ return null;
549
+ if (!ticker)
550
+ return info;
551
+ const config = __spreadValues({}, info);
552
+ if (ticker.close !== void 0) {
553
+ config["24h_close"] = ticker.close;
554
+ }
555
+ if (ticker.open !== void 0) {
556
+ config["24h_open"] = ticker.open;
557
+ }
558
+ if (ticker.volume !== void 0) {
559
+ config["24h_volumn"] = ticker.volume;
560
+ }
561
+ if (ticker.close !== void 0 && ticker.open !== void 0) {
562
+ config["change"] = new utils.Decimal(ticker.close).minus(ticker.open).div(ticker.open).toNumber();
563
+ }
564
+ return config;
565
+ }, [info, ticker]);
566
+ return value;
567
+ };
568
+ var useMarkPrice = (symbol) => {
569
+ const ws = useWS();
570
+ return useSWRSubscription__default.default(`${symbol}@markprice`, (key, { next }) => {
571
+ const unsubscribe = ws.subscribe(`${symbol}@markprice`, {
572
+ onMessage: (message) => {
573
+ next(null, message.price);
574
+ }
575
+ });
576
+ return () => {
577
+ console.log("unsubscribe useMarkPrice !!!!!!!");
578
+ unsubscribe == null ? void 0 : unsubscribe();
579
+ };
580
+ });
581
+ };
582
+
583
+ // src/utils/createGetter.ts
584
+ function createGetter(data, depth = 2) {
585
+ return new Proxy(data || {}, {
586
+ get(target, property, receiver) {
587
+ if (depth === 1) {
588
+ return (defaultValue) => {
589
+ var _a;
590
+ if (!target)
591
+ return defaultValue;
592
+ return (_a = target[property]) != null ? _a : defaultValue;
593
+ };
594
+ }
595
+ return (key, defaultValue) => {
596
+ var _a, _b;
597
+ if (key) {
598
+ return (_b = (_a = target[property]) == null ? void 0 : _a[key]) != null ? _b : defaultValue;
599
+ } else {
600
+ return target[property];
601
+ }
602
+ };
603
+ }
604
+ });
605
+ }
606
+ var useSymbolsInfo = () => {
607
+ const { data = {} } = useQuery(`/v1/public/info`, {
608
+ focusThrottleInterval: 1e3 * 60 * 60 * 24,
609
+ dedupingInterval: 1e3 * 60 * 60 * 24,
610
+ revalidateOnFocus: false,
611
+ formatter(data2) {
612
+ var _a;
613
+ if (!(data2 == null ? void 0 : data2.rows) || !((_a = data2 == null ? void 0 : data2.rows) == null ? void 0 : _a.length)) {
614
+ return {};
615
+ }
616
+ const obj = /* @__PURE__ */ Object.create(null);
617
+ for (let index = 0; index < data2.rows.length; index++) {
618
+ const item = data2.rows[index];
619
+ const arr = item.symbol.split("_");
620
+ const base_dp = utils.getPrecisionByNumber(item.base_tick);
621
+ const quote_dp = utils.getPrecisionByNumber(item.quote_tick);
622
+ obj[item.symbol] = __spreadProps(__spreadValues({}, item), {
623
+ base_dp,
624
+ quote_dp,
625
+ base: arr[1],
626
+ quote: arr[2],
627
+ type: arr[0],
628
+ name: `${arr[1]}-${arr[0]}`
629
+ });
630
+ }
631
+ return obj;
632
+ }
633
+ });
634
+ return createGetter(data);
635
+ };
636
+ var paddingFn = (len) => Array(len).fill([Number.NaN, Number.NaN, Number.NaN]);
637
+ var asksSortFn = (a, b) => a[0] - b[0];
638
+ var bidsSortFn = (a, b) => b[0] - a[0];
639
+ var reduceItems = (depth, level, data, asks = false) => {
640
+ if (!Array.isArray(data) || data.length === 0) {
641
+ return [];
642
+ }
643
+ let newData = [...data];
644
+ const result = [];
645
+ if (typeof depth !== "undefined") {
646
+ const prices = /* @__PURE__ */ new Map();
647
+ for (let i = 0; i < data.length; i++) {
648
+ const [price, quantity] = data[i];
649
+ if (isNaN(price) || isNaN(quantity))
650
+ continue;
651
+ let priceKey;
652
+ if (asks) {
653
+ priceKey = new utils.Decimal(Math.ceil(price / depth)).mul(depth).toNumber();
654
+ } else {
655
+ priceKey = new utils.Decimal(Math.floor(price / depth)).mul(depth).toNumber();
656
+ }
657
+ if (prices.has(priceKey)) {
658
+ const item = prices.get(priceKey);
659
+ const itemPrice = new utils.Decimal(item[1]).add(quantity).toNumber();
660
+ prices.set(priceKey, [priceKey, itemPrice]);
661
+ } else {
662
+ prices.set(priceKey, [priceKey, quantity]);
663
+ }
664
+ }
665
+ newData = Array.from(prices.values());
666
+ }
667
+ for (let i = 0; i < newData.length; i++) {
668
+ const [price, quantity] = newData[i];
669
+ if (isNaN(price) || isNaN(quantity))
670
+ continue;
671
+ const newQuantity = new utils.Decimal(quantity).add(result.length > 0 ? result[result.length - 1][2] : 0).toNumber();
672
+ result.push([price, quantity, newQuantity]);
673
+ }
674
+ return result;
675
+ };
676
+ var reduceOrderbook = (depth, level, data) => {
677
+ const asks = reduceItems(depth, level, data.asks, true).reverse();
678
+ const bids = reduceItems(depth, level, data.bids);
679
+ return {
680
+ asks: asks.length < level ? paddingFn(level - asks.length).concat(asks) : asks,
681
+ bids: bids.length < level ? bids.concat(paddingFn(level - bids.length)) : bids
682
+ };
683
+ };
684
+ var mergeItems = (data, update) => {
685
+ if (data.length === 0)
686
+ return update;
687
+ data = data.filter(([price]) => !isNaN(price));
688
+ while (update.length > 0) {
689
+ const item = update.shift();
690
+ if (item) {
691
+ const [price, quantity] = item;
692
+ const index = data.findIndex(([p], index2) => p === price);
693
+ if (index === -1) {
694
+ if (quantity === 0)
695
+ continue;
696
+ data.push(item);
697
+ } else {
698
+ if (quantity === 0) {
699
+ data.splice(index, 1);
700
+ continue;
701
+ } else {
702
+ data[index] = item;
703
+ }
704
+ }
705
+ }
706
+ }
707
+ return data;
708
+ };
709
+ var mergeOrderbook = (data, update) => {
710
+ return {
711
+ asks: mergeItems(data.asks, update.asks).sort(asksSortFn),
712
+ bids: mergeItems(data.bids, update.bids).sort(bidsSortFn)
713
+ };
714
+ };
715
+ var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) => {
716
+ if (!symbol) {
717
+ throw new Error("useOrderbookStream requires a symbol");
718
+ }
719
+ const [requestData, setRequestData] = React2.useState(null);
720
+ const [data, setData] = React2.useState(initial);
721
+ const [isLoading, setIsLoading] = React2.useState(true);
722
+ const [level, setLevel] = React2.useState(() => {
723
+ var _a;
724
+ return (_a = options == null ? void 0 : options.level) != null ? _a : 10;
725
+ });
726
+ const config = useSymbolsInfo()[symbol];
727
+ const [depth, setDepth] = React2.useState();
728
+ const depths = React2.useMemo(() => {
729
+ const tick = config("quote_tick");
730
+ return [tick, tick * 10, tick * 100, tick * 1e3];
731
+ }, [config("quote_tick")]);
732
+ React2.useEffect(() => {
733
+ setDepth(config("quote_tick"));
734
+ }, [config("quote_tick")]);
735
+ const ws = useWS();
736
+ const ticker = useTickerStream(symbol);
737
+ const eventEmitter = useEventEmitter();
738
+ React2.useEffect(() => {
739
+ ws.onceSubscribe(
740
+ {
741
+ event: "request",
742
+ id: `${symbol}@orderbook`,
743
+ params: {
744
+ type: "orderbook",
745
+ symbol
746
+ }
747
+ },
748
+ {
749
+ onMessage: (message) => {
750
+ if (!!message) {
751
+ const reduceOrderbookData = reduceOrderbook(depth, level, message);
752
+ setRequestData(reduceOrderbookData);
753
+ setData(reduceOrderbookData);
754
+ }
755
+ setIsLoading(false);
756
+ }
757
+ }
758
+ );
759
+ return () => {
760
+ setRequestData(null);
761
+ };
762
+ }, [symbol, depth]);
763
+ const { data: markPrice } = useMarkPrice(symbol);
764
+ React2.useEffect(() => {
765
+ if (!requestData)
766
+ return;
767
+ const subscription = ws.subscribe(
768
+ {
769
+ event: "subscribe",
770
+ topic: `${symbol}@orderbookupdate`
771
+ },
772
+ {
773
+ onMessage: (message) => {
774
+ setData((data2) => {
775
+ const mergedData = !message.asks && !message.bids ? data2 : mergeOrderbook(data2, message);
776
+ const reducedData = reduceOrderbook(depth, level, mergedData);
777
+ return reducedData;
778
+ });
779
+ }
780
+ }
781
+ );
782
+ return () => {
783
+ subscription == null ? void 0 : subscription();
784
+ };
785
+ }, [symbol, requestData]);
786
+ const onItemClick = React2.useCallback((item) => {
787
+ eventEmitter.emit("orderbook:item:click", item);
788
+ }, []);
789
+ const onDepthChange = React2.useCallback((depth2) => {
790
+ setDepth(() => depth2);
791
+ }, []);
792
+ const prevMiddlePrice = React2.useRef(0);
793
+ const middlePrice = React2.useMemo(() => {
794
+ let asksFrist = 0, bidsFirst = 0;
795
+ if (data.asks.length > 0) {
796
+ asksFrist = data.asks[data.asks.length - 1][0];
797
+ }
798
+ if (data.bids.length > 0) {
799
+ bidsFirst = data.bids[0][0];
800
+ }
801
+ if (isNaN(asksFrist) || isNaN(bidsFirst) || !ticker)
802
+ return 0;
803
+ return [asksFrist, bidsFirst, ticker["24h_close"]].sort()[1];
804
+ }, [ticker, data]);
805
+ React2.useEffect(() => {
806
+ prevMiddlePrice.current = middlePrice;
807
+ }, [middlePrice]);
808
+ return [
809
+ {
810
+ asks: data.asks.slice(-level),
811
+ bids: data.bids.slice(0, level),
812
+ markPrice,
813
+ middlePrice: [prevMiddlePrice.current, middlePrice]
814
+ },
815
+ { onDepthChange, depth, allDepths: depths, isLoading, onItemClick }
816
+ ];
817
+ };
818
+ var needNumberOnlyFields = ["order_quantity", "order_price", "total"];
819
+ function baseInputHandle(inputs) {
820
+ let [values, input, value, markPrice, config] = inputs;
821
+ if (needNumberOnlyFields.includes(input)) {
822
+ value = value.toString();
823
+ value = value.replace(/,/g, "");
824
+ value = value.replace(/[^\d.]/g, "");
825
+ }
826
+ return [
827
+ __spreadProps(__spreadValues({}, values), {
828
+ [input]: value
829
+ }),
830
+ input,
831
+ value,
832
+ markPrice,
833
+ config
834
+ ];
835
+ }
836
+ function orderEntityFormatHandle(baseTick, quoteTick) {
837
+ return function(inputs) {
838
+ const [values, input, value, markPrice, config] = inputs;
839
+ return [values, input, value, markPrice, config];
840
+ };
841
+ }
842
+ function priceInputHandle(inputs) {
843
+ const [values, input, value, markPrice, config] = inputs;
844
+ if (value === "") {
845
+ return [__spreadProps(__spreadValues({}, values), { total: "" }), input, value, markPrice, config];
846
+ }
847
+ const price = new utils.Decimal(value);
848
+ const priceDP = price.dp();
849
+ if (priceDP > config.quoteDP) {
850
+ values.order_price = price.toDecimalPlaces(config.quoteDP).toString();
851
+ }
852
+ price.toDecimalPlaces(Math.min(priceDP, config.quoteDP));
853
+ if (!values.order_quantity) {
854
+ return [values, input, value, markPrice, config];
855
+ }
856
+ const total = price.mul(values.order_quantity);
857
+ return [
858
+ __spreadProps(__spreadValues({}, values), {
859
+ total: total.todp(2).toString()
860
+ }),
861
+ input,
862
+ value,
863
+ markPrice,
864
+ config
865
+ ];
866
+ }
867
+ function quantityInputHandle(inputs) {
868
+ const [values, input, value, markPrice, config] = inputs;
869
+ if (value === "") {
870
+ return [__spreadProps(__spreadValues({}, values), { total: "" }), input, value, markPrice, config];
871
+ }
872
+ let quantity = new utils.Decimal(value);
873
+ const quantityDP = quantity.dp();
874
+ if (quantityDP > config.baseDP) {
875
+ quantity = quantity.toDecimalPlaces(config.baseDP);
876
+ values.order_quantity = quantity.toNumber();
877
+ }
878
+ if (values.order_type === types.OrderType.MARKET) {
879
+ const price = markPrice;
880
+ values.total = quantity.mul(price).todp(2).toNumber();
881
+ }
882
+ if (values.order_type === types.OrderType.LIMIT) {
883
+ if (values.order_price) {
884
+ const price = Number(values.order_price);
885
+ const total = quantity.mul(price);
886
+ values.total = total.todp(2).toNumber();
887
+ } else {
888
+ values.total = "";
889
+ }
890
+ }
891
+ return [
892
+ __spreadValues({}, values),
893
+ input,
894
+ value,
895
+ markPrice,
896
+ config
897
+ ];
898
+ }
899
+ function totalInputHandle(inputs) {
900
+ const [values, input, value, markPrice, config] = inputs;
901
+ if (value === "") {
902
+ return [__spreadProps(__spreadValues({}, values), { order_quantity: "" }), input, value, markPrice, config];
903
+ }
904
+ let price = markPrice;
905
+ if (values.order_type === types.OrderType.LIMIT && !!values.order_price) {
906
+ price = Number(values.order_price);
907
+ }
908
+ let total = new utils.Decimal(value);
909
+ const totalDP = total.dp();
910
+ if (totalDP > config.quoteDP) {
911
+ total = total.toDecimalPlaces(config.quoteDP);
912
+ values.total = total.toNumber();
913
+ }
914
+ const quantity = total.div(price);
915
+ return [
916
+ __spreadProps(__spreadValues({}, values), {
917
+ order_quantity: quantity.toDecimalPlaces(Math.min(config.baseDP, quantity.dp())).toNumber()
918
+ }),
919
+ input,
920
+ value,
921
+ markPrice,
922
+ config
923
+ ];
924
+ }
925
+ function otherInputHandle(inputs) {
926
+ return inputs;
927
+ }
928
+ var getCalculateHandler = (fieldName) => {
929
+ switch (fieldName) {
930
+ case "order_quantity": {
931
+ return quantityInputHandle;
932
+ }
933
+ case "order_price": {
934
+ return priceInputHandle;
935
+ }
936
+ case "total": {
937
+ return totalInputHandle;
938
+ }
939
+ default:
940
+ return otherInputHandle;
941
+ }
942
+ };
943
+
944
+ // src/orderly/useFundingRates.ts
945
+ var useFundingRates = () => {
946
+ const { data } = useQuery(
947
+ `/v1/public/funding_rates`,
948
+ {
949
+ focusThrottleInterval: 1e3 * 60 * 60 * 24,
950
+ revalidateOnFocus: false,
951
+ formatter(data2) {
952
+ var _a;
953
+ if (!(data2 == null ? void 0 : data2.rows) || !((_a = data2 == null ? void 0 : data2.rows) == null ? void 0 : _a.length)) {
954
+ return {};
955
+ }
956
+ const obj = /* @__PURE__ */ Object.create(null);
957
+ for (let index = 0; index < data2.rows.length; index++) {
958
+ const item = data2.rows[index];
959
+ obj[item.symbol] = item;
960
+ }
961
+ return obj;
962
+ }
963
+ }
964
+ );
965
+ return createGetter(data);
966
+ };
967
+ var useMarkPricesStream = () => {
968
+ const ws = useWS();
969
+ return useSWRSubscription__default.default("markPrices", (key, { next }) => {
970
+ const unsubscribe = ws.subscribe(
971
+ // { event: "subscribe", topic: "markprices" },
972
+ "markprices",
973
+ {
974
+ onMessage: (message) => {
975
+ const data = /* @__PURE__ */ Object.create(null);
976
+ for (let index = 0; index < message.length; index++) {
977
+ const element = message[index];
978
+ data[element.symbol] = element.price;
979
+ }
980
+ next(null, data);
981
+ },
982
+ // onUnsubscribe: () => {
983
+ // return "markprices";
984
+ // },
985
+ onError: (error) => {
986
+ console.log("error", error);
987
+ }
988
+ }
989
+ );
990
+ return () => {
991
+ console.log("unsubscribe!!!!!!!");
992
+ unsubscribe == null ? void 0 : unsubscribe();
993
+ };
994
+ });
995
+ };
996
+
997
+ // src/utils/parseHolding.ts
998
+ var parseHolding = (holding, markPrices) => {
999
+ const nonUSDC = [];
1000
+ let USDC_holding = 0;
1001
+ holding.forEach((item) => {
1002
+ var _a;
1003
+ if (item.token === "USDC") {
1004
+ USDC_holding = item.holding;
1005
+ } else {
1006
+ nonUSDC.push({
1007
+ holding: item.holding,
1008
+ markPrice: (_a = markPrices[item.token]) != null ? _a : 0,
1009
+ // markPrice: 0,
1010
+ discount: 0
1011
+ });
1012
+ }
1013
+ });
1014
+ return [USDC_holding, nonUSDC];
1015
+ };
1016
+ var usePositionStream = (symbol, options) => {
1017
+ var _a;
1018
+ const symbolInfo = useSymbolsInfo();
1019
+ useEventEmitter();
1020
+ const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1021
+ const { data: holding } = usePrivateQuery(
1022
+ "/v1/client/holding",
1023
+ {
1024
+ formatter: (data2) => {
1025
+ return data2.holding;
1026
+ }
1027
+ }
1028
+ );
1029
+ const fundingRates = useFundingRates();
1030
+ const {
1031
+ data,
1032
+ error
1033
+ // mutate: updatePositions,
1034
+ } = usePrivateQuery(`/v1/positions`, __spreadProps(__spreadValues({}, options), {
1035
+ formatter: (data2) => data2,
1036
+ onError: (err) => {
1037
+ console.log("usePositionStream error", err);
1038
+ }
1039
+ }));
1040
+ const { data: markPrices } = useMarkPricesStream();
1041
+ const formatedPositions = React2.useMemo(() => {
1042
+ if (!(data == null ? void 0 : data.rows) || !symbolInfo || !accountInfo)
1043
+ return null;
1044
+ const filteredData = typeof symbol === "undefined" || symbol === "" ? data.rows : data.rows.filter((item) => {
1045
+ return item.symbol === symbol;
1046
+ });
1047
+ let unrealPnL_total = utils.zero, notional_total = utils.zero, unsettlementPnL_total = utils.zero;
1048
+ const formatted = filteredData.map((item) => {
1049
+ var _a2;
1050
+ const price = ramda.propOr(
1051
+ item.mark_price,
1052
+ item.symbol,
1053
+ markPrices
1054
+ );
1055
+ const notional = futures.positions.notional(item.position_qty, price);
1056
+ const unrealPnl = futures.positions.unrealizedPnL({
1057
+ qty: item.position_qty,
1058
+ openPrice: item.average_open_price,
1059
+ markPrice: price
1060
+ });
1061
+ const unsettlementPnL = futures.positions.unsettlementPnL({
1062
+ positionQty: item.position_qty,
1063
+ markPrice: price,
1064
+ costPosition: item.cost_position,
1065
+ sumUnitaryFunding: (_a2 = fundingRates[item.symbol]) == null ? void 0 : _a2.call(
1066
+ fundingRates,
1067
+ "sum_unitary_funding",
1068
+ 0
1069
+ ),
1070
+ lastSumUnitaryFunding: item.last_sum_unitary_funding
1071
+ });
1072
+ unrealPnL_total = unrealPnL_total.add(unrealPnl);
1073
+ notional_total = notional_total.add(notional);
1074
+ unsettlementPnL_total = unsettlementPnL_total.add(unsettlementPnL);
1075
+ return __spreadProps(__spreadValues({}, item), {
1076
+ mark_price: price,
1077
+ mm: 0,
1078
+ notional,
1079
+ unsettlement_pnl: unsettlementPnL,
1080
+ unrealized_pnl: unrealPnl
1081
+ });
1082
+ });
1083
+ return [
1084
+ formatted,
1085
+ {
1086
+ unrealPnL: unrealPnL_total.toNumber(),
1087
+ notional: notional_total.toNumber(),
1088
+ unsettledPnL: unsettlementPnL_total.toNumber()
1089
+ }
1090
+ ];
1091
+ }, [data == null ? void 0 : data.rows, symbolInfo, accountInfo, markPrices, symbol, holding]);
1092
+ const [totalCollateral, totalValue, totalUnrealizedROI] = React2.useMemo(() => {
1093
+ if (!holding || !markPrices) {
1094
+ return [utils.zero, utils.zero, 0];
1095
+ }
1096
+ const unsettlemnedPnL = ramda.pathOr(0, [1, "unsettledPnL"])(formatedPositions);
1097
+ const unrealizedPnL = ramda.pathOr(0, [1, "unrealPnL"])(formatedPositions);
1098
+ const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
1099
+ const totalCollateral2 = futures.account.totalCollateral({
1100
+ USDCHolding: USDC_holding,
1101
+ nonUSDCHolding: nonUSDC,
1102
+ unsettlementPnL: unsettlemnedPnL
1103
+ });
1104
+ const totalValue2 = futures.account.totalValue({
1105
+ totalUnsettlementPnL: unsettlemnedPnL,
1106
+ USDCHolding: USDC_holding,
1107
+ nonUSDCHolding: nonUSDC
1108
+ });
1109
+ const totalUnrealizedROI2 = futures.account.totalUnrealizedROI({
1110
+ totalUnrealizedPnL: unrealizedPnL,
1111
+ totalValue: totalValue2.toNumber()
1112
+ });
1113
+ return [totalCollateral2, totalValue2, totalUnrealizedROI2];
1114
+ }, [holding, formatedPositions, markPrices]);
1115
+ const positionsRows = React2.useMemo(() => {
1116
+ if (!formatedPositions)
1117
+ return null;
1118
+ if (!symbolInfo || !accountInfo)
1119
+ return formatedPositions[0];
1120
+ const total = totalCollateral.toNumber();
1121
+ return formatedPositions[0].filter((item) => item.position_qty !== 0).map((item) => {
1122
+ const info = symbolInfo == null ? void 0 : symbolInfo[item.symbol];
1123
+ const MMR = futures.positions.MMR({
1124
+ baseMMR: info("base_mmr"),
1125
+ baseIMR: info("base_imr"),
1126
+ IMRFactor: accountInfo.imr_factor[info("base")],
1127
+ positionNotional: item.notional,
1128
+ IMR_factor_power: 4 / 5
1129
+ });
1130
+ return __spreadProps(__spreadValues({}, item), {
1131
+ mm: futures.positions.maintenanceMargin({
1132
+ positionQty: item.position_qty,
1133
+ markPrice: item.mark_price,
1134
+ MMR
1135
+ }),
1136
+ est_liq_price: futures.positions.liqPrice({
1137
+ markPrice: item.mark_price,
1138
+ totalCollateral: total,
1139
+ positionQty: item.position_qty,
1140
+ MMR
1141
+ }),
1142
+ MMR
1143
+ });
1144
+ });
1145
+ }, [formatedPositions, symbolInfo, accountInfo, totalCollateral]);
1146
+ return [
1147
+ {
1148
+ rows: positionsRows,
1149
+ aggregated: (_a = formatedPositions == null ? void 0 : formatedPositions[1]) != null ? _a : {},
1150
+ totalCollateral,
1151
+ totalValue,
1152
+ totalUnrealizedROI
1153
+ },
1154
+ createGetter(data, 1),
1155
+ {
1156
+ // close: onClosePosition,
1157
+ loading: false,
1158
+ // showSymbol,
1159
+ error,
1160
+ loadMore: () => {
1161
+ },
1162
+ refresh: () => {
1163
+ }
1164
+ }
1165
+ ];
1166
+ };
1167
+ var pathOr_unsettledPnLPathOr = ramda.pathOr(0, [
1168
+ 0,
1169
+ "aggregated",
1170
+ "unsettledPnL"
1171
+ ]);
1172
+ var useHoldingStream = () => {
1173
+ const ws = useWS();
1174
+ const { data, isLoading, mutate: mutate2 } = usePrivateQuery(
1175
+ "/v1/client/holding",
1176
+ {
1177
+ formatter: (data2) => {
1178
+ return data2.holding;
1179
+ }
1180
+ }
1181
+ );
1182
+ const usdc = React2.useMemo(() => {
1183
+ const usdc2 = data == null ? void 0 : data.find((item) => item.token === "USDC");
1184
+ return usdc2;
1185
+ }, [data]);
1186
+ useSWRSubscription__default.default("holding", (_, { next }) => {
1187
+ const unsubscribe = ws.privateSubscribe(
1188
+ {
1189
+ id: "balance",
1190
+ event: "subscribe",
1191
+ topic: "balance",
1192
+ ts: Date.now()
1193
+ },
1194
+ {
1195
+ onMessage: (data2) => {
1196
+ var _a;
1197
+ const holding = (_a = data2 == null ? void 0 : data2.balances) != null ? _a : {};
1198
+ if (holding) {
1199
+ mutate2((prevData) => {
1200
+ return prevData == null ? void 0 : prevData.map((item) => {
1201
+ const token = holding[item.token];
1202
+ return __spreadProps(__spreadValues({}, item), {
1203
+ frozen: token.frozen,
1204
+ holding: token.holding
1205
+ });
1206
+ });
1207
+ });
1208
+ next(holding);
1209
+ }
1210
+ }
1211
+ }
1212
+ );
1213
+ return () => unsubscribe();
1214
+ });
1215
+ return {
1216
+ data,
1217
+ usdc,
1218
+ isLoading
1219
+ };
1220
+ };
1221
+
1222
+ // src/orderly/useCollateral.ts
1223
+ var positionsPath = ramda.pathOr([], [0, "rows"]);
1224
+ ramda.pathOr(0, [0, "totalCollateral"]);
1225
+ var useCollateral = (options = { dp: 6 }) => {
1226
+ const { dp } = options;
1227
+ const positions2 = usePositionStream();
1228
+ const { data: orders } = usePrivateQuery(
1229
+ `/v1/orders?status=NEW`
1230
+ );
1231
+ const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1232
+ const symbolInfo = useSymbolsInfo();
1233
+ const { data: markPrices } = useMarkPricesStream();
1234
+ const { usdc } = useHoldingStream();
1235
+ const [totalCollateral, totalValue] = React2.useMemo(() => {
1236
+ return [
1237
+ ramda.pathOr(utils.zero, [0, "totalCollateral"], positions2),
1238
+ ramda.pathOr(utils.zero, [0, "totalValue"], positions2)
1239
+ ];
1240
+ }, [positions2, markPrices]);
1241
+ const totalInitialMarginWithOrders = React2.useMemo(() => {
1242
+ if (!accountInfo || !symbolInfo || !markPrices) {
1243
+ return 0;
1244
+ }
1245
+ return futures.account.totalInitialMarginWithOrders({
1246
+ positions: positionsPath(positions2),
1247
+ orders: orders != null ? orders : [],
1248
+ markPrices,
1249
+ IMR_Factors: accountInfo.imr_factor,
1250
+ maxLeverage: accountInfo.max_leverage,
1251
+ symbolInfo
1252
+ });
1253
+ }, [positions2, orders, markPrices, accountInfo, symbolInfo]);
1254
+ const freeCollateral = React2.useMemo(() => {
1255
+ return futures.account.freeCollateral({
1256
+ totalCollateral,
1257
+ totalInitialMarginWithOrders
1258
+ });
1259
+ }, [totalCollateral, totalInitialMarginWithOrders]);
1260
+ const availableBalance = React2.useMemo(() => {
1261
+ var _a;
1262
+ return futures.account.availableBalance({
1263
+ USDCHolding: (_a = usdc == null ? void 0 : usdc.holding) != null ? _a : 0,
1264
+ unsettlementPnL: pathOr_unsettledPnLPathOr(positions2)
1265
+ });
1266
+ }, [usdc, pathOr_unsettledPnLPathOr(positions2)]);
1267
+ return {
1268
+ totalCollateral: totalCollateral.toDecimalPlaces(dp).toNumber(),
1269
+ freeCollateral: freeCollateral.toDecimalPlaces(dp).toNumber(),
1270
+ totalValue: totalValue.toDecimalPlaces(dp).toNumber(),
1271
+ availableBalance,
1272
+ unsettledPnL: pathOr_unsettledPnLPathOr(positions2)
1273
+ };
1274
+ };
1275
+ var positionsPath2 = ramda.pathOr([], [0, "rows"]);
1276
+ var useMaxQty = (symbol, side, reduceOnly = false) => {
1277
+ const positionsData = usePositionStream();
1278
+ const { data: orders } = usePrivateQuery(
1279
+ `/v1/orders?status=NEW`
1280
+ );
1281
+ const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1282
+ const symbolInfo = useSymbolsInfo();
1283
+ const { totalCollateral } = useCollateral();
1284
+ const { data: markPrices } = useMarkPricesStream();
1285
+ const maxQty = React2.useMemo(() => {
1286
+ if (!symbol)
1287
+ return 0;
1288
+ const positions2 = positionsPath2(positionsData);
1289
+ const positionQty = futures.account.getQtyFromPositions(positions2, symbol);
1290
+ if (reduceOnly) {
1291
+ if (positionQty > 0) {
1292
+ if (side === types.OrderSide.BUY) {
1293
+ return 0;
1294
+ } else {
1295
+ return Math.abs(positionQty);
1296
+ }
1297
+ }
1298
+ if (positionQty < 0) {
1299
+ if (side === types.OrderSide.BUY) {
1300
+ return Math.abs(positionQty);
1301
+ } else {
1302
+ return 0;
1303
+ }
1304
+ }
1305
+ return 0;
1306
+ }
1307
+ if (!markPrices || !markPrices[symbol] || !orders || !accountInfo)
1308
+ return 0;
1309
+ const getSymbolInfo = symbolInfo[symbol];
1310
+ const buyOrdersQty = futures.account.getQtyFromOrdersBySide(
1311
+ orders,
1312
+ symbol,
1313
+ types.OrderSide.BUY
1314
+ );
1315
+ const sellOrdersQty = futures.account.getQtyFromOrdersBySide(
1316
+ orders,
1317
+ symbol,
1318
+ types.OrderSide.SELL
1319
+ );
1320
+ const otherPositions = positions2.filter(
1321
+ (item) => item.symbol !== symbol
1322
+ );
1323
+ const otherOrders = orders.filter(
1324
+ (item) => item.symbol !== symbol
1325
+ );
1326
+ const otherIMs = futures.account.otherIMs({
1327
+ orders: otherOrders,
1328
+ positions: otherPositions,
1329
+ symbolInfo,
1330
+ markPrices,
1331
+ IMR_Factors: accountInfo.imr_factor,
1332
+ maxLeverage: accountInfo.max_leverage
1333
+ });
1334
+ return futures.account.maxQty(side, {
1335
+ markPrice: markPrices[symbol],
1336
+ symbol,
1337
+ baseMaxQty: getSymbolInfo("base_max"),
1338
+ totalCollateral,
1339
+ maxLeverage: accountInfo.max_leverage,
1340
+ takerFeeRate: accountInfo.taker_fee_rate,
1341
+ baseIMR: getSymbolInfo("base_imr"),
1342
+ otherIMs,
1343
+ positionQty,
1344
+ buyOrdersQty,
1345
+ sellOrdersQty,
1346
+ IMR_Factor: accountInfo.imr_factor[getSymbolInfo("base")]
1347
+ });
1348
+ }, [
1349
+ orders,
1350
+ positionsData,
1351
+ markPrices,
1352
+ accountInfo,
1353
+ symbolInfo,
1354
+ symbol,
1355
+ side,
1356
+ totalCollateral,
1357
+ reduceOnly
1358
+ ]);
1359
+ return maxQty;
1360
+ };
1361
+ var { maxPrice, minPrice } = futures.order;
1362
+ var BaseOrderCreator = class {
1363
+ baseOrder(data) {
1364
+ const order2 = {
1365
+ // symbol: data.symbol,
1366
+ order_type: data.order_type === types.OrderType.LIMIT ? !!data.order_type_ext ? data.order_type_ext : data.order_type : data.order_type,
1367
+ side: data.side,
1368
+ reduce_only: data.reduce_only,
1369
+ order_quantity: data.order_quantity
1370
+ };
1371
+ if (data.visible_quantity === 0) {
1372
+ order2.visible_quantity = data.visible_quantity;
1373
+ }
1374
+ return order2;
1375
+ }
1376
+ baseValidate(values, configs) {
1377
+ const errors = {};
1378
+ const { maxQty } = configs;
1379
+ const { order_quantity, total } = values;
1380
+ if (!order_quantity) {
1381
+ errors.order_quantity = {
1382
+ type: "required",
1383
+ message: "quantity is required"
1384
+ };
1385
+ } else {
1386
+ const { base_min, quote_dp, base_dp } = configs.symbol;
1387
+ const qty = new utils.Decimal(order_quantity);
1388
+ if (qty.lt(base_min)) {
1389
+ errors.order_quantity = {
1390
+ type: "min",
1391
+ message: `quantity must be greater than ${new utils.Decimal(base_min).todp(
1392
+ base_dp
1393
+ )}`
1394
+ };
1395
+ } else if (qty.gt(maxQty)) {
1396
+ errors.order_quantity = {
1397
+ type: "max",
1398
+ message: `quantity must be less than ${new utils.Decimal(maxQty).todp(
1399
+ base_dp
1400
+ )}`
1401
+ };
1402
+ }
1403
+ }
1404
+ if (!!total) {
1405
+ const { quote_max, quote_min, quote_dp } = configs.symbol;
1406
+ const totalNumber = new utils.Decimal(total);
1407
+ if (totalNumber.lt(quote_min)) {
1408
+ errors.total = {
1409
+ type: "min",
1410
+ message: `Quantity should be greater or equal than ${new utils.Decimal(
1411
+ quote_min
1412
+ ).todp(quote_dp)}`
1413
+ };
1414
+ } else if (totalNumber.gt(quote_max)) {
1415
+ errors.total = {
1416
+ type: "max",
1417
+ message: `Quantity should be less or equal than ${new utils.Decimal(
1418
+ quote_max
1419
+ ).todp(quote_dp)}`
1420
+ };
1421
+ }
1422
+ }
1423
+ return Promise.resolve(errors);
1424
+ }
1425
+ };
1426
+ var LimitOrderCreator = class extends BaseOrderCreator {
1427
+ create(values) {
1428
+ return __spreadProps(__spreadValues({}, this.baseOrder(values)), {
1429
+ order_price: values.order_price
1430
+ });
1431
+ }
1432
+ validate(values, config) {
1433
+ return this.baseValidate(values, config).then((errors) => {
1434
+ const { order_price } = values;
1435
+ if (!order_price) {
1436
+ errors.order_price = {
1437
+ type: "required",
1438
+ message: "price is required"
1439
+ };
1440
+ } else {
1441
+ const price = new utils.Decimal(order_price);
1442
+ const { symbol } = config;
1443
+ const { price_range } = symbol;
1444
+ const maxPriceNumber = maxPrice(config.markPrice, price_range);
1445
+ const minPriceNumber = minPrice(config.markPrice, price_range);
1446
+ if (price.lt(minPriceNumber)) {
1447
+ errors.order_price = {
1448
+ type: "min",
1449
+ message: `price must be greater than ${new utils.Decimal(
1450
+ minPriceNumber
1451
+ ).todp(symbol.quote_dp)}`
1452
+ };
1453
+ } else if (price.gt(maxPriceNumber)) {
1454
+ errors.order_price = {
1455
+ type: "max",
1456
+ message: `price must be less than ${new utils.Decimal(
1457
+ maxPriceNumber
1458
+ ).todp(symbol.quote_dp)}`
1459
+ };
1460
+ }
1461
+ }
1462
+ return errors;
1463
+ });
1464
+ }
1465
+ };
1466
+ var MarketOrderCreator = class extends BaseOrderCreator {
1467
+ create(values) {
1468
+ const data = this.baseOrder(values);
1469
+ delete data["order_price"];
1470
+ return __spreadValues({}, data);
1471
+ }
1472
+ validate(values, configs) {
1473
+ return this.baseValidate(values, configs);
1474
+ }
1475
+ };
1476
+ var PostOnlyOrderCreator = class extends LimitOrderCreator {
1477
+ };
1478
+ var FOKOrderCreator = class extends LimitOrderCreator {
1479
+ };
1480
+ var IOCOrderCreator = class extends LimitOrderCreator {
1481
+ };
1482
+ var GeneralOrderCreator = class extends BaseOrderCreator {
1483
+ create(data) {
1484
+ return __spreadProps(__spreadValues({}, this.baseOrder(data)), {
1485
+ order_price: data.order_price,
1486
+ order_quantity: data.order_quantity
1487
+ });
1488
+ }
1489
+ validate(values, configs) {
1490
+ return super.baseValidate(values, configs);
1491
+ }
1492
+ };
1493
+ var OrderFactory = class {
1494
+ static create(type) {
1495
+ switch (type) {
1496
+ case types.OrderType.LIMIT:
1497
+ return new LimitOrderCreator();
1498
+ case types.OrderType.MARKET:
1499
+ return new MarketOrderCreator();
1500
+ case types.OrderType.IOC:
1501
+ return new IOCOrderCreator();
1502
+ case types.OrderType.FOK:
1503
+ return new FOKOrderCreator();
1504
+ case types.OrderType.POST_ONLY:
1505
+ return new PostOnlyOrderCreator();
1506
+ default:
1507
+ return new GeneralOrderCreator();
1508
+ }
1509
+ }
1510
+ };
1511
+
1512
+ // src/orderly/useOrderEntry.ts
1513
+ var useOrderEntry = (symbol, side, reduceOnly = false, options) => {
1514
+ const [doCreateOrder] = useMutation("/v1/order");
1515
+ const { freeCollateral } = useCollateral();
1516
+ const symbolInfo = useSymbolsInfo();
1517
+ const baseDP = React2.useMemo(
1518
+ () => utils.getPrecisionByNumber(symbolInfo[symbol]("base_tick", 0)),
1519
+ [symbolInfo]
1520
+ );
1521
+ const quoteDP = React2.useMemo(() => {
1522
+ return utils.getPrecisionByNumber(symbolInfo[symbol]("quote_tick", 0));
1523
+ }, [symbolInfo]);
1524
+ const { data: markPrice } = useMarkPrice(symbol);
1525
+ const maxQty = useMaxQty(
1526
+ symbol,
1527
+ side,
1528
+ // orderExtraValues.reduce_only
1529
+ reduceOnly
1530
+ );
1531
+ const onSubmit = (values) => {
1532
+ if (!values || typeof values.order_type === "undefined" || values.order_type !== types.OrderType.MARKET && values.order_type !== types.OrderType.LIMIT) {
1533
+ throw new Error("order_type is error");
1534
+ }
1535
+ const orderCreator = OrderFactory.create(
1536
+ !!values.order_type_ext ? values.order_type_ext : values.order_type
1537
+ );
1538
+ if (!orderCreator) {
1539
+ return Promise.reject(new Error("orderCreator is null"));
1540
+ }
1541
+ return orderCreator == null ? void 0 : orderCreator.validate(values, {
1542
+ symbol: symbolInfo[symbol](),
1543
+ // token: tokenInfo[symbol](),
1544
+ maxQty,
1545
+ markPrice
1546
+ }).then(() => {
1547
+ if (!orderCreator) {
1548
+ throw new Error("orderCreator is null");
1549
+ }
1550
+ if (!symbol) {
1551
+ throw new Error("symbol is null");
1552
+ }
1553
+ const data = orderCreator.create(values);
1554
+ return doCreateOrder(__spreadProps(__spreadValues({}, data), {
1555
+ symbol
1556
+ }));
1557
+ });
1558
+ };
1559
+ const calculate = React2.useCallback(
1560
+ (values, field, value) => {
1561
+ console.log("calculate", values, field, value, markPrice);
1562
+ const fieldHandler = getCalculateHandler(field);
1563
+ const newValues = ramda.compose(
1564
+ ramda.head,
1565
+ orderEntityFormatHandle(),
1566
+ fieldHandler,
1567
+ baseInputHandle
1568
+ )([values, field, value, markPrice, { baseDP, quoteDP }]);
1569
+ return newValues;
1570
+ },
1571
+ [markPrice]
1572
+ );
1573
+ const validator = (values) => {
1574
+ const creator = OrderFactory.create(values.order_type);
1575
+ return creator == null ? void 0 : creator.validate(values, {
1576
+ symbol: symbolInfo[symbol](),
1577
+ // token: tokenInfo[symbol](),
1578
+ maxQty,
1579
+ markPrice
1580
+ });
1581
+ };
1582
+ return {
1583
+ maxQty,
1584
+ freeCollateral,
1585
+ markPrice,
1586
+ onSubmit,
1587
+ helper: {
1588
+ calculate,
1589
+ validator
1590
+ },
1591
+ symbolConfig: symbolInfo[symbol]()
1592
+ };
1593
+ };
1594
+ var useFetures = () => {
1595
+ const { data, isLoading, error } = useQuery(
1596
+ `/v1/public/futures`,
1597
+ {
1598
+ revalidateOnFocus: false
1599
+ }
1600
+ );
1601
+ const [sortedData, setSortedData] = React2.useState(data);
1602
+ useWS();
1603
+ React2.useEffect(() => {
1604
+ }, []);
1605
+ React2.useEffect(() => {
1606
+ if (data) {
1607
+ const sortedData2 = data.sort((a, b) => {
1608
+ return 0;
1609
+ });
1610
+ setSortedData(sortedData2);
1611
+ }
1612
+ }, [data]);
1613
+ const sortBy = React2.useCallback((key) => {
1614
+ }, [data]);
1615
+ const filterBy = React2.useCallback((key) => {
1616
+ }, [data]);
1617
+ return {
1618
+ // ...data,
1619
+ data: sortedData,
1620
+ sortBy,
1621
+ filterBy,
1622
+ isLoading,
1623
+ error
1624
+ };
1625
+ };
1626
+
1627
+ // src/orderly/useAccountInfo.ts
1628
+ var useAccountInfo = () => {
1629
+ return usePrivateQuery("/v1/client/info");
1630
+ };
1631
+
1632
+ // src/orderly/useTokenInfo.ts
1633
+ var useTokenInfo = () => {
1634
+ const { data = {} } = useQuery(
1635
+ "/v1/public/token",
1636
+ {
1637
+ focusThrottleInterval: 1e3 * 60 * 60 * 24,
1638
+ revalidateOnFocus: false,
1639
+ formatter(data2) {
1640
+ var _a;
1641
+ if (!(data2 == null ? void 0 : data2.rows) || !((_a = data2 == null ? void 0 : data2.rows) == null ? void 0 : _a.length)) {
1642
+ return {};
1643
+ }
1644
+ const obj = /* @__PURE__ */ Object.create(null);
1645
+ for (let index = 0; index < data2.rows.length; index++) {
1646
+ const item = data2.rows[index];
1647
+ obj[item.token] = item;
1648
+ }
1649
+ return obj;
1650
+ }
1651
+ }
1652
+ );
1653
+ return createGetter(data);
1654
+ };
1655
+ var useMarketsStream = () => {
1656
+ const ws = useWS();
1657
+ const { data: futures } = useQuery(`/v1/public/futures`, {
1658
+ revalidateOnFocus: false
1659
+ });
1660
+ const { data: tickers } = useSWRSubscription__default.default("tickers", (_, { next }) => {
1661
+ const unsubscribe = ws.subscribe(
1662
+ // { event: "subscribe", topic: "markprices" },
1663
+ "tickers",
1664
+ {
1665
+ onMessage: (message) => {
1666
+ next(null, message);
1667
+ }
1668
+ // onUnsubscribe: () => {
1669
+ // return "markprices";
1670
+ // },
1671
+ // onError: (error: any) => {
1672
+ // console.log("error", error);
1673
+ // },
1674
+ }
1675
+ );
1676
+ return () => {
1677
+ console.log("unsubscribe!!!!!!!");
1678
+ unsubscribe == null ? void 0 : unsubscribe();
1679
+ };
1680
+ });
1681
+ const value = React2.useMemo(() => {
1682
+ if (!futures)
1683
+ return null;
1684
+ if (!tickers)
1685
+ return futures;
1686
+ return futures.map((item) => {
1687
+ const ticker = tickers.find(
1688
+ (t) => t.symbol === item.symbol
1689
+ );
1690
+ if (ticker) {
1691
+ return __spreadProps(__spreadValues({}, item), {
1692
+ ["24h_close"]: ticker.close,
1693
+ ["24h_open"]: ticker.open,
1694
+ ["24h_volumn"]: ticker.volume,
1695
+ change: 0
1696
+ });
1697
+ }
1698
+ return item;
1699
+ });
1700
+ }, [futures, tickers]);
1701
+ return { data: value };
1702
+ };
1703
+ var useLeverage = () => {
1704
+ const { data, mutate: mutate2 } = usePrivateQuery("/v1/client/info");
1705
+ const [update] = useMutation("/v1/client/leverage");
1706
+ const updateLeverage = React2.useCallback((data2) => {
1707
+ return update(data2).then((res) => {
1708
+ return mutate2();
1709
+ });
1710
+ }, []);
1711
+ return [ramda.prop("max_leverage", data), { update: updateLeverage }];
1712
+ };
1713
+ var useFundingRate = (symbol) => {
1714
+ var _a;
1715
+ if (!symbol) {
1716
+ throw new Error("useFuturesForSymbol requires a symbol");
1717
+ }
1718
+ const [countDown, setCountDown] = React2.useState("00:00:00");
1719
+ const { data } = useQuery(
1720
+ `/v1/public/funding_rate/${symbol}`,
1721
+ {
1722
+ fallbackData: {
1723
+ est_funding_rate: 0,
1724
+ next_funing_time: 0
1725
+ }
1726
+ }
1727
+ );
1728
+ React2.useEffect(() => {
1729
+ if (!data)
1730
+ return;
1731
+ const { next_funding_time } = data;
1732
+ if (!next_funding_time || next_funding_time <= 0) {
1733
+ return;
1734
+ }
1735
+ const timer = setInterval(() => {
1736
+ const diff = new Date(next_funding_time).getTime() - Date.now();
1737
+ const result = utils.timeConvertString(diff);
1738
+ if (result.length === 3) {
1739
+ setCountDown(
1740
+ `${result[0].toString().padStart(2, "0")}:${result[1].toString().padStart(2, "0")}:${result[2].toString().padStart(2, "0")}`
1741
+ );
1742
+ }
1743
+ }, 1e3);
1744
+ return () => {
1745
+ clearInterval(timer);
1746
+ };
1747
+ }, [data]);
1748
+ return __spreadProps(__spreadValues({}, data), {
1749
+ est_funding_rate: (Number((_a = data == null ? void 0 : data.est_funding_rate) != null ? _a : 0) * 100).toFixed(4),
1750
+ countDown
1751
+ });
1752
+ };
1753
+ var fetcher3 = (url, init) => net.get(url, init);
1754
+ var usePrivateInfiniteQuery = (getKey, options) => {
1755
+ var _a;
1756
+ const account5 = useAccount();
1757
+ const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_a = options == null ? void 0 : options.use) != null ? _a : [] : [];
1758
+ const result = useSWRInfinite__default.default(
1759
+ (pageIndex, previousPageData) => account5.state.status >= types.AccountStatusEnum.EnableTrading ? getKey(pageIndex, previousPageData) : null,
1760
+ fetcher3,
1761
+ __spreadProps(__spreadValues({}, options), {
1762
+ use: [signatureMiddleware, ...middleware]
1763
+ })
1764
+ );
1765
+ return result;
1766
+ };
1767
+ var OrderStatus = /* @__PURE__ */ ((OrderStatus3) => {
1768
+ OrderStatus3["FILLED"] = "FILLED";
1769
+ OrderStatus3["PARTIAL_FILLED"] = "PARTIAL_FILLED";
1770
+ OrderStatus3["CANCELED"] = "CANCELED";
1771
+ OrderStatus3["NEW"] = "NEW";
1772
+ OrderStatus3["COMPLETED"] = "COMPLETED";
1773
+ return OrderStatus3;
1774
+ })(OrderStatus || {});
1775
+ var useOrderStream = ({
1776
+ status,
1777
+ symbol,
1778
+ side,
1779
+ size = 100
1780
+ } = {}) => {
1781
+ const ee = useEventEmitter();
1782
+ const { data: markPrices = {} } = useMarkPricesStream();
1783
+ const [doCancelOrder] = useMutation("/v1/order", "DELETE");
1784
+ const [doUpdateOrder] = useMutation("/v1/order", "PUT");
1785
+ const ordersResponse = usePrivateInfiniteQuery(
1786
+ (pageIndex, previousPageData) => {
1787
+ const search = new URLSearchParams([
1788
+ ["size", size.toString()],
1789
+ ["page", `${pageIndex + 1}`]
1790
+ // [`status`, status],
1791
+ ]);
1792
+ if (status) {
1793
+ search.set(`status`, status);
1794
+ }
1795
+ if (symbol) {
1796
+ search.set(`symbol`, symbol);
1797
+ }
1798
+ if (side) {
1799
+ search.set(`side`, side);
1800
+ }
1801
+ return `/v1/orders?${search.toString()}`;
1802
+ },
1803
+ {
1804
+ initialSize: 1,
1805
+ onError: (err) => {
1806
+ console.error("fetch failed::::", err);
1807
+ }
1808
+ }
1809
+ );
1810
+ const orders = React2.useMemo(() => {
1811
+ var _a;
1812
+ if (!ordersResponse.data) {
1813
+ return null;
1814
+ }
1815
+ return (_a = ordersResponse.data) == null ? void 0 : _a.flat().map((item) => {
1816
+ var _a2;
1817
+ return __spreadProps(__spreadValues({}, item), {
1818
+ mark_price: (_a2 = markPrices[item.symbol]) != null ? _a2 : 0
1819
+ });
1820
+ });
1821
+ }, [ordersResponse.data, markPrices]);
1822
+ React2.useEffect(() => {
1823
+ const handler = () => ordersResponse.mutate();
1824
+ ee.on("orders:changed", handler);
1825
+ return () => {
1826
+ ee.off("orders:changed", handler);
1827
+ };
1828
+ }, []);
1829
+ const cancelAllOrders = React2.useCallback(() => {
1830
+ }, [ordersResponse.data]);
1831
+ const updateOrder = React2.useCallback((orderId, order2) => {
1832
+ return doUpdateOrder(__spreadProps(__spreadValues({}, order2), { order_id: orderId }));
1833
+ }, []);
1834
+ const cancelOrder = React2.useCallback((orderId, symbol2) => {
1835
+ return doCancelOrder(null, {
1836
+ order_id: orderId,
1837
+ symbol: symbol2
1838
+ }).then((res) => {
1839
+ if (res.success) {
1840
+ return ordersResponse.mutate().then(() => {
1841
+ return res;
1842
+ });
1843
+ } else {
1844
+ throw new Error(res.message);
1845
+ }
1846
+ });
1847
+ }, []);
1848
+ return [
1849
+ orders,
1850
+ {
1851
+ cancelAllOrders,
1852
+ updateOrder,
1853
+ cancelOrder
1854
+ }
1855
+ ];
1856
+ };
1857
+ var useMarketTradeStream = (symbol, options = {}) => {
1858
+ if (!symbol) {
1859
+ throw new Error("useTradeStream: symbol is required");
1860
+ }
1861
+ const [trades, setTrades] = React2.useState([]);
1862
+ const [isLoading, setIsLoading] = React2.useState(false);
1863
+ React2.useState(() => symbol);
1864
+ const { limit = 50 } = options;
1865
+ const ws = useWS();
1866
+ React2.useEffect(() => {
1867
+ setIsLoading(true);
1868
+ setTrades(() => []);
1869
+ ws.onceSubscribe(
1870
+ {
1871
+ id: `${symbol}@trade`,
1872
+ event: "request",
1873
+ params: {
1874
+ type: "trade",
1875
+ symbol,
1876
+ limit
1877
+ }
1878
+ },
1879
+ {
1880
+ onMessage: (data) => {
1881
+ setIsLoading(false);
1882
+ setTrades(() => data);
1883
+ }
1884
+ }
1885
+ );
1886
+ }, [symbol]);
1887
+ React2.useEffect(() => {
1888
+ const unsubscript = ws.subscribe(
1889
+ {
1890
+ id: `${symbol}@trade`,
1891
+ event: "subscribe",
1892
+ topic: `${symbol}@trade`,
1893
+ ts: Date.now()
1894
+ },
1895
+ {
1896
+ onMessage: (data) => {
1897
+ setTrades((prev) => {
1898
+ const arr = [__spreadProps(__spreadValues({}, data), { ts: Date.now() }), ...prev];
1899
+ if (arr.length > limit) {
1900
+ arr.pop();
1901
+ }
1902
+ return arr;
1903
+ });
1904
+ }
1905
+ }
1906
+ );
1907
+ return () => {
1908
+ unsubscript == null ? void 0 : unsubscript();
1909
+ };
1910
+ }, [symbol]);
1911
+ console.log("trades", trades);
1912
+ return { data: trades, isLoading };
1913
+ };
1914
+ var useMarginRatio = () => {
1915
+ const [{ rows }] = usePositionStream();
1916
+ const { data: markPrices } = useMarkPricesStream();
1917
+ const { totalCollateral } = useCollateral();
1918
+ const marginRatio = React2.useMemo(() => {
1919
+ if (!rows || !markPrices || !totalCollateral || rows.length === 0) {
1920
+ return 0;
1921
+ }
1922
+ const ratio = futures.account.totalMarginRatio({
1923
+ totalCollateral,
1924
+ markPrices,
1925
+ positions: rows != null ? rows : []
1926
+ });
1927
+ return ratio;
1928
+ }, [rows, markPrices, totalCollateral]);
1929
+ const currentLeverage = React2.useMemo(() => {
1930
+ return futures.account.currentLeverage(marginRatio);
1931
+ }, [marginRatio]);
1932
+ return { marginRatio, currentLeverage };
1933
+ };
1934
+ var useChains = (networkId, options = {}) => {
1935
+ const _a = options, swrOptions = __objRest(_a, ["filter", "pick"]);
1936
+ const field = options == null ? void 0 : options.pick;
1937
+ const { data } = useSWR__default.default(
1938
+ "https://fi-api.woo.org/swap_support",
1939
+ (url) => fetch(url).then((res) => res.json()),
1940
+ __spreadValues({
1941
+ revalidateOnFocus: false,
1942
+ revalidateOnReconnect: false
1943
+ }, swrOptions)
1944
+ );
1945
+ const chains = React2.useMemo(() => {
1946
+ if (!data || !data.data)
1947
+ return data;
1948
+ let arr = [];
1949
+ Object.keys(data.data).forEach((key) => {
1950
+ const item = data.data[key];
1951
+ arr.push(__spreadProps(__spreadValues({}, item), {
1952
+ name: key
1953
+ }));
1954
+ });
1955
+ if (networkId === "mainnet") {
1956
+ arr = arr.filter((item) => item.network_infos.mainnet);
1957
+ }
1958
+ if (networkId === "testnet") {
1959
+ arr = arr.filter((item) => !item.network_infos.mainnet);
1960
+ }
1961
+ if (typeof (options == null ? void 0 : options.filter) === "function") {
1962
+ arr = arr.filter(options.filter);
1963
+ }
1964
+ if (typeof field !== "undefined") {
1965
+ return arr.map((item) => {
1966
+ return item[field];
1967
+ });
1968
+ }
1969
+ return arr;
1970
+ }, [data, networkId, field, options]);
1971
+ const findByChainId = React2.useCallback(
1972
+ (chainId) => {
1973
+ if (!data || !data.data)
1974
+ return void 0;
1975
+ return data.data[chainId];
1976
+ },
1977
+ [data]
1978
+ );
1979
+ return [chains, { findByChainId }];
1980
+ };
1981
+ var useChain = (token) => {
1982
+ const { data, isLoading } = useQuery("/v1/public/token");
1983
+ const chains = React2.useMemo(() => {
1984
+ if (!data)
1985
+ return null;
1986
+ let item = data.find((chain) => chain.token === token);
1987
+ if (item) {
1988
+ item.chain_details = item.chain_details.map((d) => {
1989
+ var _a;
1990
+ const chain = types.chainsMap.get(Number(d.chain_id));
1991
+ return __spreadProps(__spreadValues({}, d), {
1992
+ chain_name: (_a = chain == null ? void 0 : chain.chainName) != null ? _a : "--"
1993
+ });
1994
+ });
1995
+ }
1996
+ return item || null;
1997
+ }, [data, token]);
1998
+ return { chains, isLoading };
1999
+ };
2000
+ var useWithdraw = () => {
2001
+ const { account: account5, state } = useAccount();
2002
+ const [isLoading, setIsLoading] = React2.useState(false);
2003
+ const { unsettledPnL, availableBalance } = useCollateral();
2004
+ const withdraw = React2.useCallback(
2005
+ (inputs) => {
2006
+ return account5.assetsManager.withdraw(inputs).then((res) => {
2007
+ console.log("---------- withdraw -------", res);
2008
+ return res;
2009
+ });
2010
+ },
2011
+ [state]
2012
+ );
2013
+ const { usdc } = useHoldingStream();
2014
+ const maxAmount = React2.useMemo(() => {
2015
+ var _a;
2016
+ if (!usdc || !usdc.holding)
2017
+ return 0;
2018
+ if (unsettledPnL >= 0)
2019
+ return (_a = usdc == null ? void 0 : usdc.holding) != null ? _a : 0;
2020
+ return new utils.Decimal(usdc.holding).add(unsettledPnL).toNumber();
2021
+ }, [usdc, unsettledPnL]);
2022
+ return { withdraw, isLoading, maxAmount, availableBalance, unsettledPnL };
2023
+ };
2024
+ var useDeposit = () => {
2025
+ const [balance, setBalance] = React2.useState("0");
2026
+ const [allowance, setAllowance] = React2.useState("0");
2027
+ const { account: account5, state } = useAccount();
2028
+ const fetchBalance = React2.useCallback(() => __async(void 0, null, function* () {
2029
+ const balance2 = yield account5.assetsManager.getBalance();
2030
+ setBalance(() => balance2);
2031
+ }), [state]);
2032
+ const fetchAllowance = React2.useCallback(() => __async(void 0, null, function* () {
2033
+ const allowance2 = yield account5.assetsManager.getAllowance();
2034
+ console.log("----- refresh allowance -----", allowance2);
2035
+ setAllowance(() => allowance2);
2036
+ return allowance2;
2037
+ }), []);
2038
+ React2.useEffect(() => {
2039
+ if (state.status < types.AccountStatusEnum.EnableTrading)
2040
+ return;
2041
+ fetchBalance();
2042
+ fetchAllowance();
2043
+ }, [state]);
2044
+ const approve = React2.useCallback(
2045
+ (amount) => {
2046
+ return account5.assetsManager.approve(amount).then((result) => {
2047
+ setAllowance((value) => new utils.Decimal(value).add(amount).toString());
2048
+ return result;
2049
+ });
2050
+ },
2051
+ [account5, fetchAllowance]
2052
+ );
2053
+ const deposit = React2.useCallback(
2054
+ (amount) => {
2055
+ return account5.assetsManager.deposit(amount).then((res) => {
2056
+ console.log("----- deposit -----", res);
2057
+ setAllowance((value) => new utils.Decimal(value).sub(amount).toString());
2058
+ setBalance((value) => new utils.Decimal(value).sub(amount).toString());
2059
+ return res;
2060
+ });
2061
+ },
2062
+ [account5, fetchBalance, fetchAllowance]
2063
+ );
2064
+ return {
2065
+ balance,
2066
+ allowance,
2067
+ approve,
2068
+ deposit
2069
+ };
2070
+ };
2071
+ var useWalletSubscription = (options) => {
2072
+ const ws = useWS();
2073
+ return useSWRSubscription__default.default("wallet", (_, { next }) => {
2074
+ const unsubscribe = ws.privateSubscribe(
2075
+ {
2076
+ id: "wallet",
2077
+ event: "subscribe",
2078
+ topic: "wallet",
2079
+ ts: Date.now()
2080
+ },
2081
+ {
2082
+ onMessage: (data) => {
2083
+ var _a;
2084
+ (_a = options == null ? void 0 : options.onMessage) == null ? void 0 : _a.call(options, data);
2085
+ next(data);
2086
+ }
2087
+ }
2088
+ );
2089
+ return () => unsubscribe();
2090
+ });
2091
+ };
2092
+ var useBalance = () => {
2093
+ const ws = useWS();
2094
+ const { data } = useSWRSubscription__default.default("balance", (_, { next }) => {
2095
+ const unsubscribe = ws.privateSubscribe("balance", {
2096
+ onMessage: (data2) => {
2097
+ console.log(data2);
2098
+ }
2099
+ });
2100
+ return () => unsubscribe();
2101
+ });
2102
+ return data;
2103
+ };
2104
+ var usePrivateDataObserver = () => {
2105
+ const ws = useWS();
2106
+ const { mutate: mutate2 } = useSWR.useSWRConfig();
2107
+ const ee = useEventEmitter();
2108
+ const { state } = useAccount();
2109
+ React2.useEffect(() => {
2110
+ const unsubscribe = ws.privateSubscribe("executionreport", {
2111
+ onMessage: (data) => {
2112
+ const key = ["/v1/orders?status=NEW", state.accountId];
2113
+ mutate2(key, (orders) => {
2114
+ return Promise.resolve().then(() => {
2115
+ if (!orders) {
2116
+ return orders;
2117
+ }
2118
+ if (data.status === types.OrderStatus.NEW) {
2119
+ return [
2120
+ __spreadProps(__spreadValues({}, data), {
2121
+ // average_executed_price:data.ava
2122
+ created_time: data.timestamp,
2123
+ order_id: data.orderId
2124
+ // reduce_only
2125
+ }),
2126
+ ...orders
2127
+ ];
2128
+ }
2129
+ if (data.status === types.OrderStatus.CANCELLED) {
2130
+ return orders.filter(
2131
+ (order2) => order2.order_id !== data.orderId
2132
+ );
2133
+ }
2134
+ return orders;
2135
+ }).catch((error) => {
2136
+ console.log("error", error, error.stack);
2137
+ });
2138
+ });
2139
+ ee.emit("orders:changed");
2140
+ }
2141
+ });
2142
+ return () => unsubscribe == null ? void 0 : unsubscribe();
2143
+ }, [state.accountId]);
2144
+ React2.useEffect(() => {
2145
+ console.log("subscribe: position: %s", state.accountId);
2146
+ if (!state.accountId)
2147
+ return;
2148
+ const key = ["/v1/positions", state.accountId];
2149
+ const unsubscribe = ws.privateSubscribe("position", {
2150
+ onMessage: (data) => {
2151
+ const { positions: nextPostions } = data;
2152
+ mutate2(key, (prevPositions) => {
2153
+ if (!!prevPositions) {
2154
+ return __spreadProps(__spreadValues({}, prevPositions), {
2155
+ rows: prevPositions.rows.map((row) => {
2156
+ const item = nextPostions.find(
2157
+ (item2) => item2.symbol === row.symbol
2158
+ );
2159
+ if (item) {
2160
+ return {
2161
+ symbol: item.symbol,
2162
+ position_qty: item.positionQty,
2163
+ cost_position: item.costPosition,
2164
+ last_sum_unitary_funding: item.lastSumUnitaryFunding,
2165
+ pending_long_qty: item.pendingLongQty,
2166
+ pending_short_qty: item.pendingShortQty,
2167
+ settle_price: item.settlePrice,
2168
+ average_open_price: item.averageOpenPrice,
2169
+ unsettled_pnl: item.unsettledPnl,
2170
+ mark_price: item.markPrice,
2171
+ est_liq_price: item.estLiqPrice,
2172
+ timestamp: Date.now(),
2173
+ imr: item.imr,
2174
+ mmr: item.mmr,
2175
+ IMR_withdraw_orders: item.imrwithOrders,
2176
+ MMR_with_orders: item.mmrwithOrders,
2177
+ pnl_24_h: item.pnl24H,
2178
+ fee_24_h: item.fee24H
2179
+ };
2180
+ }
2181
+ return row;
2182
+ })
2183
+ });
2184
+ }
2185
+ });
2186
+ }
2187
+ });
2188
+ return () => {
2189
+ console.log("unsubscribe: private subscription position");
2190
+ unsubscribe == null ? void 0 : unsubscribe();
2191
+ };
2192
+ }, [state.accountId]);
2193
+ };
2194
+ var useExecutionReport = () => {
2195
+ const ws = useWS();
2196
+ const { data } = useSWRSubscription__default.default("executionreport", (_, { next }) => {
2197
+ const unsubscribe = ws.privateSubscribe("executionreport", {
2198
+ onMessage: (data2) => {
2199
+ console.log(data2);
2200
+ }
2201
+ });
2202
+ return () => unsubscribe();
2203
+ });
2204
+ return data;
2205
+ };
2206
+
2207
+ // src/apis/index.ts
2208
+ var apis_exports = {};
2209
+ __export(apis_exports, {
2210
+ useFundingRateBySymbol: () => useFundingRateBySymbol,
2211
+ useInfo: () => useInfo,
2212
+ useToken: () => useToken
2213
+ });
2214
+
2215
+ // src/apis/useInfo.ts
2216
+ var useInfo = () => {
2217
+ return useQuery("/v1/public/info", {
2218
+ // refreshInterval: 1000 * 60 * 60 * 24,
2219
+ });
2220
+ };
2221
+
2222
+ // src/apis/useToken.ts
2223
+ var useToken = () => {
2224
+ return useQuery("/v1/public/token");
2225
+ };
2226
+
2227
+ // src/apis/useFundingRateBySymbol.ts
2228
+ var useFundingRateBySymbol = (symbol) => {
2229
+ if (!symbol) {
2230
+ throw new Error("symbol is required");
2231
+ }
2232
+ return useQuery(`/public/funding_rate/${symbol}`);
2233
+ };
2234
+
2235
+ Object.defineProperty(exports, 'SWRConfig', {
2236
+ enumerable: true,
2237
+ get: function () { return useSWR.SWRConfig; }
2238
+ });
2239
+ Object.defineProperty(exports, 'useSWR', {
2240
+ enumerable: true,
2241
+ get: function () { return useSWR__default.default; }
2242
+ });
2243
+ Object.defineProperty(exports, 'useConstant', {
2244
+ enumerable: true,
2245
+ get: function () { return useConstant__default.default; }
2246
+ });
2247
+ exports.DataSourceProvider = DataSourceProvider;
2248
+ exports.OrderStatus = OrderStatus;
2249
+ exports.OrderlyContext = OrderlyContext;
2250
+ exports.OrderlyProvider = OrderlyProvider;
2251
+ exports.apis = apis_exports;
2252
+ exports.useAccount = useAccount;
2253
+ exports.useAccountInfo = useAccountInfo;
2254
+ exports.useAccountInstance = useAccountInstance;
2255
+ exports.useAppState = useAppState;
2256
+ exports.useBalance = useBalance;
2257
+ exports.useChain = useChain;
2258
+ exports.useChains = useChains;
2259
+ exports.useCollateral = useCollateral;
2260
+ exports.useConfig = useConfig;
2261
+ exports.useDeposit = useDeposit;
2262
+ exports.useEventEmitter = useEventEmitter;
2263
+ exports.useExecutionReport = useExecutionReport;
2264
+ exports.useFetures = useFetures;
2265
+ exports.useFundingRate = useFundingRate;
2266
+ exports.useHoldingStream = useHoldingStream;
2267
+ exports.useLeverage = useLeverage;
2268
+ exports.useLocalStorage = useLocalStorage;
2269
+ exports.useMarginRatio = useMarginRatio;
2270
+ exports.useMarkPrice = useMarkPrice;
2271
+ exports.useMarkPricesStream = useMarkPricesStream;
2272
+ exports.useMarketTradeStream = useMarketTradeStream;
2273
+ exports.useMarketsStream = useMarketsStream;
2274
+ exports.useMaxQty = useMaxQty;
2275
+ exports.useMutation = useMutation;
2276
+ exports.useOrderEntry = useOrderEntry;
2277
+ exports.useOrderStream = useOrderStream;
2278
+ exports.useOrderbookStream = useOrderbookStream;
2279
+ exports.usePositionStream = usePositionStream;
2280
+ exports.usePreLoadData = usePreLoadData;
2281
+ exports.usePrivateDataObserver = usePrivateDataObserver;
2282
+ exports.usePrivateObserve = usePrivateObserve;
2283
+ exports.usePrivateQuery = usePrivateQuery;
2284
+ exports.useQuery = useQuery;
2285
+ exports.useRunOnce = useRunOnce;
2286
+ exports.useSessionStorage = useSessionStorage;
2287
+ exports.useSymbolsInfo = useSymbolsInfo;
2288
+ exports.useTickerStream = useTickerStream;
2289
+ exports.useTokenInfo = useTokenInfo;
2290
+ exports.useTopicObserve = useTopicObserve;
2291
+ exports.useTradingView = useTradingView;
2292
+ exports.useWS = useWS;
2293
+ exports.useWalletSubscription = useWalletSubscription;
2294
+ exports.useWithdraw = useWithdraw;
2295
+ //# sourceMappingURL=out.js.map
2296
+ //# sourceMappingURL=index.js.map