@orderly.network/hooks 0.0.39 → 0.0.41

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 DELETED
@@ -1,2110 +0,0 @@
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(`${apiBaseUrl}${url}`, init, { formatter }),
97
- swrOptions
98
- );
99
- };
100
- var useAccountInstance = () => {
101
- const { configStore, keyStore, contractManager, getWalletAdapter } = React2.useContext(OrderlyContext);
102
- if (!configStore)
103
- throw new Error("configStore is not defined, please use OrderlyProvider");
104
- if (!keyStore) {
105
- throw new Error(
106
- "keyStore is not defined, please use OrderlyProvider and provide keyStore"
107
- );
108
- }
109
- const account5 = useConstant__default.default(() => {
110
- let account6 = core.SimpleDI.get("account");
111
- if (!account6) {
112
- account6 = new core.Account(
113
- configStore,
114
- keyStore,
115
- contractManager,
116
- getWalletAdapter
117
- // walletAdapter
118
- );
119
- core.SimpleDI.registerByName("account", account6);
120
- }
121
- return account6;
122
- });
123
- return account5;
124
- };
125
-
126
- // src/useMutation.ts
127
- var fetcher2 = (url, options) => {
128
- const init = {
129
- method: options.arg.method,
130
- headers: __spreadValues({}, options.arg.signature)
131
- };
132
- if (options.arg.data) {
133
- init.body = JSON.stringify(options.arg.data);
134
- }
135
- if (typeof options.arg.params === "object" && Object.keys(options.arg.params).length) {
136
- let search = new URLSearchParams(options.arg.params);
137
- url = `${url}?${search.toString()}`;
138
- }
139
- return net.mutate(url, init);
140
- };
141
- var useMutation = (url, method = "POST", options) => {
142
- const { apiBaseUrl } = React2.useContext(OrderlyContext);
143
- let fullUrl = url;
144
- if (!url.startsWith("http")) {
145
- fullUrl = `${apiBaseUrl}${url}`;
146
- }
147
- const account5 = useAccountInstance();
148
- const signer = account5.signer;
149
- const { trigger, data, error, reset, isMutating } = useSWRMutation__default.default(
150
- fullUrl,
151
- // method === "POST" ? fetcher : deleteFetcher,
152
- fetcher2,
153
- options
154
- );
155
- const mutation = (data2, params) => __async(void 0, null, function* () {
156
- let newUrl = url;
157
- if (typeof params === "object" && Object.keys(params).length) {
158
- let search = new URLSearchParams(params);
159
- newUrl = `${url}?${search.toString()}`;
160
- }
161
- const payload = {
162
- method,
163
- url: newUrl,
164
- data: data2
165
- };
166
- const signature = yield signer.sign(payload);
167
- return trigger({
168
- data: data2,
169
- params,
170
- method,
171
- signature: __spreadProps(__spreadValues({}, signature), {
172
- "orderly-account-id": account5.accountId
173
- })
174
- });
175
- });
176
- return [
177
- mutation,
178
- {
179
- data,
180
- error,
181
- reset,
182
- isMutating
183
- }
184
- ];
185
- };
186
- var signatureMiddleware = (useSWRNext) => {
187
- const { apiBaseUrl } = React2.useContext(OrderlyContext);
188
- return (key, fetcher4, config) => {
189
- try {
190
- const extendedFetcher = (args) => __async(void 0, null, function* () {
191
- let url = Array.isArray(args) ? args[0] : args;
192
- let account5 = core.SimpleDI.get("account");
193
- let fullUrl = `${apiBaseUrl}${url}`;
194
- const signer = account5.signer;
195
- const payload = {
196
- method: "GET",
197
- url
198
- };
199
- const signature = yield signer.sign(payload);
200
- return fetcher4(fullUrl, {
201
- headers: __spreadProps(__spreadValues({}, signature), {
202
- "orderly-account-id": account5.accountId
203
- })
204
- });
205
- });
206
- return useSWRNext(key, extendedFetcher, config);
207
- } catch (e) {
208
- console.error("signature error:", e);
209
- throw e;
210
- }
211
- };
212
- };
213
- var useAccount = () => {
214
- const {
215
- configStore,
216
- keyStore,
217
- walletAdapter,
218
- contractManager,
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 useTickerStream = (symbol) => {
508
- if (!symbol) {
509
- throw new Error("useFuturesForSymbol requires a symbol");
510
- }
511
- const { data: info } = useQuery(
512
- `/v1/public/futures/${symbol}`,
513
- {
514
- revalidateOnFocus: false
515
- }
516
- );
517
- const ws = useWS();
518
- const { data: ticker } = useSWRSubscription__default.default(
519
- `${symbol}@ticker`,
520
- (key, { next }) => {
521
- const unsubscribe = ws.subscribe(
522
- // { event: "subscribe", topic: "markprices" },
523
- `${symbol}@ticker`,
524
- {
525
- onMessage: (message) => {
526
- next(null, message);
527
- }
528
- // onUnsubscribe: () => {
529
- // return "markprices";
530
- // },
531
- // onError: (error: any) => {
532
- // console.log("error", error);
533
- // },
534
- }
535
- );
536
- return () => {
537
- console.log("unsubscribe!!!!!!!");
538
- unsubscribe == null ? void 0 : unsubscribe();
539
- };
540
- }
541
- );
542
- const value = React2.useMemo(() => {
543
- if (!info)
544
- return null;
545
- if (!ticker)
546
- return info;
547
- const config = __spreadValues({}, info);
548
- if (ticker.close !== void 0) {
549
- config["24h_close"] = ticker.close;
550
- }
551
- if (ticker.open !== void 0) {
552
- config["24h_open"] = ticker.open;
553
- }
554
- if (ticker.volume !== void 0) {
555
- config["24h_volumn"] = ticker.volume;
556
- }
557
- if (ticker.close !== void 0 && ticker.open !== void 0) {
558
- config["change"] = new utils.Decimal(ticker.close).minus(ticker.open).div(ticker.open).toNumber();
559
- }
560
- return config;
561
- }, [info, ticker]);
562
- return value;
563
- };
564
- var useMarkPrice = (symbol) => {
565
- const ws = useWS();
566
- return useSWRSubscription__default.default(`${symbol}@markprice`, (key, { next }) => {
567
- const unsubscribe = ws.subscribe(`${symbol}@markprice`, {
568
- onMessage: (message) => {
569
- next(null, message.price);
570
- }
571
- });
572
- return () => {
573
- console.log("unsubscribe useMarkPrice !!!!!!!");
574
- unsubscribe == null ? void 0 : unsubscribe();
575
- };
576
- });
577
- };
578
-
579
- // src/utils/createGetter.ts
580
- function createGetter(data, depth = 2) {
581
- return new Proxy(data || {}, {
582
- get(target, property, receiver) {
583
- if (depth === 1) {
584
- return (defaultValue) => {
585
- var _a;
586
- if (!target)
587
- return defaultValue;
588
- return (_a = target[property]) != null ? _a : defaultValue;
589
- };
590
- }
591
- return (key, defaultValue) => {
592
- var _a, _b;
593
- if (key) {
594
- return (_b = (_a = target[property]) == null ? void 0 : _a[key]) != null ? _b : defaultValue;
595
- } else {
596
- return target[property];
597
- }
598
- };
599
- }
600
- });
601
- }
602
- var useSymbolsInfo = () => {
603
- const { data = {} } = useQuery(`/v1/public/info`, {
604
- focusThrottleInterval: 1e3 * 60 * 60 * 24,
605
- dedupingInterval: 1e3 * 60 * 60 * 24,
606
- revalidateOnFocus: false,
607
- formatter(data2) {
608
- var _a;
609
- if (!(data2 == null ? void 0 : data2.rows) || !((_a = data2 == null ? void 0 : data2.rows) == null ? void 0 : _a.length)) {
610
- return {};
611
- }
612
- const obj = /* @__PURE__ */ Object.create(null);
613
- for (let index = 0; index < data2.rows.length; index++) {
614
- const item = data2.rows[index];
615
- const arr = item.symbol.split("_");
616
- const base_dp = utils.getPrecisionByNumber(item.base_tick);
617
- const quote_dp = utils.getPrecisionByNumber(item.quote_tick);
618
- obj[item.symbol] = __spreadProps(__spreadValues({}, item), {
619
- base_dp,
620
- quote_dp,
621
- base: arr[1],
622
- quote: arr[2],
623
- type: arr[0],
624
- name: `${arr[1]}-${arr[0]}`
625
- });
626
- }
627
- return obj;
628
- }
629
- });
630
- return createGetter(data);
631
- };
632
- var paddingFn = (len) => Array(len).fill([Number.NaN, Number.NaN, Number.NaN]);
633
- var asksSortFn = (a, b) => a[0] - b[0];
634
- var bidsSortFn = (a, b) => b[0] - a[0];
635
- var reduceItems = (depth, level, data, asks = false) => {
636
- if (!Array.isArray(data) || data.length === 0) {
637
- return [];
638
- }
639
- let newData = [...data];
640
- const result = [];
641
- if (typeof depth !== "undefined") {
642
- const prices = /* @__PURE__ */ new Map();
643
- for (let i = 0; i < data.length; i++) {
644
- const [price, quantity] = data[i];
645
- if (isNaN(price) || isNaN(quantity))
646
- continue;
647
- let priceKey;
648
- if (asks) {
649
- priceKey = new utils.Decimal(Math.ceil(price / depth)).mul(depth).toNumber();
650
- } else {
651
- priceKey = new utils.Decimal(Math.floor(price / depth)).mul(depth).toNumber();
652
- }
653
- if (prices.has(priceKey)) {
654
- const item = prices.get(priceKey);
655
- const itemPrice = new utils.Decimal(item[1]).add(quantity).toNumber();
656
- prices.set(priceKey, [priceKey, itemPrice]);
657
- } else {
658
- prices.set(priceKey, [priceKey, quantity]);
659
- }
660
- }
661
- newData = Array.from(prices.values());
662
- }
663
- for (let i = 0; i < newData.length; i++) {
664
- const [price, quantity] = newData[i];
665
- if (isNaN(price) || isNaN(quantity))
666
- continue;
667
- const newQuantity = new utils.Decimal(quantity).add(result.length > 0 ? result[result.length - 1][2] : 0).toNumber();
668
- result.push([price, quantity, newQuantity]);
669
- if (i + 1 >= level) {
670
- break;
671
- }
672
- }
673
- return result;
674
- };
675
- var reduceOrderbook = (depth, level, data) => {
676
- const asks = reduceItems(depth, level, data.asks, true).reverse();
677
- const bids = reduceItems(depth, level, data.bids);
678
- return {
679
- asks: asks.length < level ? paddingFn(level - asks.length).concat(asks) : asks,
680
- bids: bids.length < level ? bids.concat(paddingFn(level - bids.length)) : bids
681
- };
682
- };
683
- var mergeItems = (data, update) => {
684
- if (data.length === 0)
685
- return update;
686
- data = data.filter(([price]) => !isNaN(price));
687
- while (update.length > 0) {
688
- const item = update.shift();
689
- if (item) {
690
- const [price, quantity] = item;
691
- const index = data.findIndex(([p], index2) => p === price);
692
- if (index === -1) {
693
- if (quantity === 0)
694
- continue;
695
- data.push(item);
696
- } else {
697
- if (quantity === 0) {
698
- data.splice(index, 1);
699
- continue;
700
- } else {
701
- data[index] = item;
702
- }
703
- }
704
- }
705
- }
706
- return data;
707
- };
708
- var mergeOrderbook = (data, update) => {
709
- return {
710
- asks: mergeItems(data.asks, update.asks).sort(asksSortFn),
711
- bids: mergeItems(data.bids, update.bids).sort(bidsSortFn)
712
- };
713
- };
714
- var useOrderbookStream = (symbol, initial = { asks: [], bids: [] }, options) => {
715
- if (!symbol) {
716
- throw new Error("useOrderbookStream requires a symbol");
717
- }
718
- const [requestData, setRequestData] = React2.useState(null);
719
- const [data, setData] = React2.useState(initial);
720
- const [isLoading, setIsLoading] = React2.useState(true);
721
- const [level, setLevel] = React2.useState(() => {
722
- var _a;
723
- return (_a = options == null ? void 0 : options.level) != null ? _a : 10;
724
- });
725
- const config = useSymbolsInfo()[symbol];
726
- const [depth, setDepth] = React2.useState();
727
- const depths = React2.useMemo(() => {
728
- const tick = config("quote_tick");
729
- return [tick, tick * 10, tick * 100, tick * 1e3];
730
- }, [config("quote_tick")]);
731
- React2.useEffect(() => {
732
- setDepth(config("quote_tick"));
733
- }, [config("quote_tick")]);
734
- const ws = useWS();
735
- const ticker = useTickerStream(symbol);
736
- const eventEmitter = useEventEmitter();
737
- React2.useEffect(() => {
738
- ws.onceSubscribe(
739
- {
740
- event: "request",
741
- id: `${symbol}@orderbook`,
742
- params: {
743
- type: "orderbook",
744
- symbol
745
- }
746
- },
747
- {
748
- onMessage: (message) => {
749
- if (!!message) {
750
- const reduceOrderbookData = reduceOrderbook(depth, level, message);
751
- setRequestData(reduceOrderbookData);
752
- setData(reduceOrderbookData);
753
- }
754
- setIsLoading(false);
755
- }
756
- }
757
- );
758
- return () => {
759
- setRequestData(null);
760
- };
761
- }, [symbol, depth]);
762
- const { data: markPrice } = useMarkPrice(symbol);
763
- React2.useEffect(() => {
764
- if (!requestData)
765
- return;
766
- const subscription = ws.subscribe(
767
- {
768
- event: "subscribe",
769
- topic: `${symbol}@orderbookupdate`
770
- },
771
- {
772
- onMessage: (message) => {
773
- setData((data2) => {
774
- const mergedData = !message.asks && !message.bids ? data2 : mergeOrderbook(data2, message);
775
- const reducedData = reduceOrderbook(depth, level, mergedData);
776
- return reducedData;
777
- });
778
- }
779
- }
780
- );
781
- return () => {
782
- subscription == null ? void 0 : subscription();
783
- };
784
- }, [symbol, requestData]);
785
- const onItemClick = React2.useCallback((item) => {
786
- eventEmitter.emit("orderbook:item:click", item);
787
- }, []);
788
- const onDepthChange = React2.useCallback((depth2) => {
789
- setDepth(() => depth2);
790
- }, []);
791
- const middlePrice = React2.useMemo(() => {
792
- let asksFrist = 0, bidsFirst = 0;
793
- if (data.asks.length > 0) {
794
- asksFrist = data.asks[data.asks.length - 1][0];
795
- }
796
- if (data.bids.length > 0) {
797
- bidsFirst = data.bids[0][0];
798
- }
799
- if (isNaN(asksFrist) || isNaN(bidsFirst) || !ticker)
800
- return 0;
801
- return [asksFrist, bidsFirst, ticker["24h_close"]].sort()[1];
802
- }, [ticker, data]);
803
- return [
804
- __spreadProps(__spreadValues({}, data), { markPrice, middlePrice }),
805
- { onDepthChange, depth, allDepths: depths, isLoading, onItemClick }
806
- ];
807
- };
808
-
809
- // src/orderly/useTokenInfo.ts
810
- var useTokenInfo = () => {
811
- const { data = {} } = useQuery(
812
- "/v1/public/token",
813
- {
814
- focusThrottleInterval: 1e3 * 60 * 60 * 24,
815
- revalidateOnFocus: false,
816
- formatter(data2) {
817
- var _a;
818
- if (!(data2 == null ? void 0 : data2.rows) || !((_a = data2 == null ? void 0 : data2.rows) == null ? void 0 : _a.length)) {
819
- return {};
820
- }
821
- const obj = /* @__PURE__ */ Object.create(null);
822
- for (let index = 0; index < data2.rows.length; index++) {
823
- const item = data2.rows[index];
824
- obj[item.token] = item;
825
- }
826
- return obj;
827
- }
828
- }
829
- );
830
- return createGetter(data);
831
- };
832
- var needNumberOnlyFields = ["order_quantity", "order_price", "total"];
833
- function baseInputHandle(inputs) {
834
- let [values, input, value, markPrice, config] = inputs;
835
- if (needNumberOnlyFields.includes(input)) {
836
- value = value.toString();
837
- value = value.replace(/,/g, "");
838
- value = value.replace(/[^\d.]/g, "");
839
- }
840
- return [
841
- __spreadProps(__spreadValues({}, values), {
842
- [input]: value
843
- }),
844
- input,
845
- value,
846
- markPrice,
847
- config
848
- ];
849
- }
850
- function orderEntityFormatHandle(baseTick, quoteTick) {
851
- return function(inputs) {
852
- const [values, input, value, markPrice, config] = inputs;
853
- return [values, input, value, markPrice, config];
854
- };
855
- }
856
- function priceInputHandle(inputs) {
857
- const [values, input, value, markPrice, config] = inputs;
858
- if (value === "") {
859
- return [__spreadProps(__spreadValues({}, values), { total: "" }), input, value, markPrice, config];
860
- }
861
- const price = new utils.Decimal(value);
862
- const priceDP = price.dp();
863
- if (priceDP > config.quoteDP) {
864
- values.order_price = price.toDecimalPlaces(config.quoteDP).toString();
865
- }
866
- price.toDecimalPlaces(Math.min(priceDP, config.quoteDP));
867
- if (!values.order_quantity) {
868
- return [values, input, value, markPrice, config];
869
- }
870
- const total = price.mul(values.order_quantity);
871
- return [
872
- __spreadProps(__spreadValues({}, values), {
873
- total: total.todp(2).toString()
874
- }),
875
- input,
876
- value,
877
- markPrice,
878
- config
879
- ];
880
- }
881
- function quantityInputHandle(inputs) {
882
- const [values, input, value, markPrice, config] = inputs;
883
- if (value === "") {
884
- return [__spreadProps(__spreadValues({}, values), { total: "" }), input, value, markPrice, config];
885
- }
886
- let quantity = new utils.Decimal(value);
887
- const quantityDP = quantity.dp();
888
- if (quantityDP > config.baseDP) {
889
- quantity = quantity.toDecimalPlaces(config.baseDP);
890
- values.order_quantity = quantity.toNumber();
891
- }
892
- if (values.order_type === types.OrderType.MARKET) {
893
- const price = markPrice;
894
- values.total = quantity.mul(price).todp(2).toNumber();
895
- }
896
- if (values.order_type === types.OrderType.LIMIT) {
897
- if (values.order_price) {
898
- const price = Number(values.order_price);
899
- const total = quantity.mul(price);
900
- values.total = total.todp(2).toNumber();
901
- } else {
902
- values.total = "";
903
- }
904
- }
905
- return [
906
- __spreadValues({}, values),
907
- input,
908
- value,
909
- markPrice,
910
- config
911
- ];
912
- }
913
- function totalInputHandle(inputs) {
914
- const [values, input, value, markPrice, config] = inputs;
915
- if (value === "") {
916
- return [__spreadProps(__spreadValues({}, values), { order_quantity: "" }), input, value, markPrice, config];
917
- }
918
- let price = markPrice;
919
- if (values.order_type === types.OrderType.LIMIT && !!values.order_price) {
920
- price = Number(values.order_price);
921
- }
922
- let total = new utils.Decimal(value);
923
- const totalDP = total.dp();
924
- if (totalDP > config.quoteDP) {
925
- total = total.toDecimalPlaces(config.quoteDP);
926
- values.total = total.toNumber();
927
- }
928
- const quantity = total.div(price);
929
- return [
930
- __spreadProps(__spreadValues({}, values), {
931
- order_quantity: quantity.toDecimalPlaces(Math.min(config.baseDP, quantity.dp())).toNumber()
932
- }),
933
- input,
934
- value,
935
- markPrice,
936
- config
937
- ];
938
- }
939
- function otherInputHandle(inputs) {
940
- return inputs;
941
- }
942
- var getCalculateHandler = (fieldName) => {
943
- switch (fieldName) {
944
- case "order_quantity": {
945
- return quantityInputHandle;
946
- }
947
- case "order_price": {
948
- return priceInputHandle;
949
- }
950
- case "total": {
951
- return totalInputHandle;
952
- }
953
- default:
954
- return otherInputHandle;
955
- }
956
- };
957
-
958
- // src/orderly/useFundingRates.ts
959
- var useFundingRates = () => {
960
- const { data } = useQuery(
961
- `/v1/public/funding_rates`,
962
- {
963
- focusThrottleInterval: 1e3 * 60 * 60 * 24,
964
- revalidateOnFocus: false,
965
- formatter(data2) {
966
- var _a;
967
- if (!(data2 == null ? void 0 : data2.rows) || !((_a = data2 == null ? void 0 : data2.rows) == null ? void 0 : _a.length)) {
968
- return {};
969
- }
970
- const obj = /* @__PURE__ */ Object.create(null);
971
- for (let index = 0; index < data2.rows.length; index++) {
972
- const item = data2.rows[index];
973
- obj[item.symbol] = item;
974
- }
975
- return obj;
976
- }
977
- }
978
- );
979
- return createGetter(data);
980
- };
981
- var useMarkPricesStream = () => {
982
- const ws = useWS();
983
- return useSWRSubscription__default.default("markPrices", (key, { next }) => {
984
- const unsubscribe = ws.subscribe(
985
- // { event: "subscribe", topic: "markprices" },
986
- "markprices",
987
- {
988
- onMessage: (message) => {
989
- const data = /* @__PURE__ */ Object.create(null);
990
- for (let index = 0; index < message.length; index++) {
991
- const element = message[index];
992
- data[element.symbol] = element.price;
993
- }
994
- next(null, data);
995
- },
996
- // onUnsubscribe: () => {
997
- // return "markprices";
998
- // },
999
- onError: (error) => {
1000
- console.log("error", error);
1001
- }
1002
- }
1003
- );
1004
- return () => {
1005
- console.log("unsubscribe!!!!!!!");
1006
- unsubscribe == null ? void 0 : unsubscribe();
1007
- };
1008
- });
1009
- };
1010
-
1011
- // src/utils/parseHolding.ts
1012
- var parseHolding = (holding, markPrices) => {
1013
- const nonUSDC = [];
1014
- let USDC_holding = 0;
1015
- holding.forEach((item) => {
1016
- var _a;
1017
- if (item.token === "USDC") {
1018
- USDC_holding = item.holding;
1019
- } else {
1020
- nonUSDC.push({
1021
- holding: item.holding,
1022
- markPrice: (_a = markPrices[item.token]) != null ? _a : 0,
1023
- // markPrice: 0,
1024
- discount: 0
1025
- });
1026
- }
1027
- });
1028
- return [USDC_holding, nonUSDC];
1029
- };
1030
- var usePositionStream = (symbol, options) => {
1031
- var _a;
1032
- const symbolInfo = useSymbolsInfo();
1033
- useEventEmitter();
1034
- const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1035
- const { data: holding } = usePrivateQuery(
1036
- "/v1/client/holding",
1037
- {
1038
- formatter: (data2) => {
1039
- return data2.holding;
1040
- }
1041
- }
1042
- );
1043
- const fundingRates = useFundingRates();
1044
- const {
1045
- data,
1046
- error
1047
- // mutate: updatePositions,
1048
- } = usePrivateQuery(`/v1/positions`, __spreadProps(__spreadValues({}, options), {
1049
- formatter: (data2) => data2,
1050
- onError: (err) => {
1051
- console.log("usePositionStream error", err);
1052
- }
1053
- }));
1054
- const { data: markPrices } = useMarkPricesStream();
1055
- const formatedPositions = React2.useMemo(() => {
1056
- if (!(data == null ? void 0 : data.rows) || !symbolInfo || !accountInfo)
1057
- return null;
1058
- const filteredData = typeof symbol === "undefined" || symbol === "" ? data.rows : data.rows.filter((item) => {
1059
- return item.symbol === symbol;
1060
- });
1061
- let unrealPnL_total = utils.zero, notional_total = utils.zero, unsettlementPnL_total = utils.zero;
1062
- const formatted = filteredData.map((item) => {
1063
- var _a2;
1064
- const price = ramda.propOr(
1065
- item.mark_price,
1066
- item.symbol,
1067
- markPrices
1068
- );
1069
- const notional = futures.positions.notional(item.position_qty, price);
1070
- const unrealPnl = futures.positions.unrealizedPnL({
1071
- qty: item.position_qty,
1072
- openPrice: item.average_open_price,
1073
- markPrice: price
1074
- });
1075
- const unsettlementPnL = futures.positions.unsettlementPnL({
1076
- positionQty: item.position_qty,
1077
- markPrice: price,
1078
- costPosition: item.cost_position,
1079
- sumUnitaryFunding: (_a2 = fundingRates[item.symbol]) == null ? void 0 : _a2.call(
1080
- fundingRates,
1081
- "sum_unitary_funding",
1082
- 0
1083
- ),
1084
- lastSumUnitaryFunding: item.last_sum_unitary_funding
1085
- });
1086
- unrealPnL_total = unrealPnL_total.add(unrealPnl);
1087
- notional_total = notional_total.add(notional);
1088
- unsettlementPnL_total = unsettlementPnL_total.add(unsettlementPnL);
1089
- return __spreadProps(__spreadValues({}, item), {
1090
- mark_price: price,
1091
- mm: 0,
1092
- notional,
1093
- unsettlement_pnl: unsettlementPnL,
1094
- unrealized_pnl: unrealPnl
1095
- });
1096
- });
1097
- return [
1098
- formatted,
1099
- {
1100
- unrealPnL: unrealPnL_total.toNumber(),
1101
- notional: notional_total.toNumber(),
1102
- unsettledPnL: unsettlementPnL_total.toNumber()
1103
- }
1104
- ];
1105
- }, [data == null ? void 0 : data.rows, symbolInfo, accountInfo, markPrices, symbol, holding]);
1106
- const [totalCollateral, totalValue, totalUnrealizedROI] = React2.useMemo(() => {
1107
- if (!holding || !markPrices) {
1108
- return [utils.zero, utils.zero, 0];
1109
- }
1110
- const unsettlemnedPnL = ramda.pathOr(0, [1, "unsettledPnL"])(formatedPositions);
1111
- const unrealizedPnL = ramda.pathOr(0, [1, "unrealPnL"])(formatedPositions);
1112
- const [USDC_holding, nonUSDC] = parseHolding(holding, markPrices);
1113
- const totalCollateral2 = futures.account.totalCollateral({
1114
- USDCHolding: USDC_holding,
1115
- nonUSDCHolding: nonUSDC,
1116
- unsettlementPnL: unsettlemnedPnL
1117
- });
1118
- const totalValue2 = futures.account.totalValue({
1119
- totalUnsettlementPnL: unsettlemnedPnL,
1120
- USDCHolding: USDC_holding,
1121
- nonUSDCHolding: nonUSDC
1122
- });
1123
- const totalUnrealizedROI2 = futures.account.totalUnrealizedROI({
1124
- totalUnrealizedPnL: unrealizedPnL,
1125
- totalValue: totalValue2.toNumber()
1126
- });
1127
- return [totalCollateral2, totalValue2, totalUnrealizedROI2];
1128
- }, [holding, formatedPositions, markPrices]);
1129
- const positionsRows = React2.useMemo(() => {
1130
- if (!formatedPositions)
1131
- return null;
1132
- if (!symbolInfo || !accountInfo)
1133
- return formatedPositions[0];
1134
- const total = totalCollateral.toNumber();
1135
- return formatedPositions[0].filter((item) => item.position_qty !== 0).map((item) => {
1136
- const info = symbolInfo == null ? void 0 : symbolInfo[item.symbol];
1137
- const MMR = futures.positions.MMR({
1138
- baseMMR: info("base_mmr"),
1139
- baseIMR: info("base_imr"),
1140
- IMRFactor: accountInfo.imr_factor[info("base")],
1141
- positionNotional: item.notional,
1142
- IMR_factor_power: 4 / 5
1143
- });
1144
- return __spreadProps(__spreadValues({}, item), {
1145
- mm: futures.positions.maintenanceMargin({
1146
- positionQty: item.position_qty,
1147
- markPrice: item.mark_price,
1148
- MMR
1149
- }),
1150
- est_liq_price: futures.positions.liqPrice({
1151
- markPrice: item.mark_price,
1152
- totalCollateral: total,
1153
- positionQty: item.position_qty,
1154
- MMR
1155
- }),
1156
- MMR
1157
- });
1158
- });
1159
- }, [formatedPositions, symbolInfo, accountInfo, totalCollateral]);
1160
- return [
1161
- {
1162
- rows: positionsRows,
1163
- aggregated: (_a = formatedPositions == null ? void 0 : formatedPositions[1]) != null ? _a : {},
1164
- totalCollateral,
1165
- totalValue,
1166
- totalUnrealizedROI
1167
- },
1168
- createGetter(data, 1),
1169
- {
1170
- // close: onClosePosition,
1171
- loading: false,
1172
- // showSymbol,
1173
- error,
1174
- loadMore: () => {
1175
- },
1176
- refresh: () => {
1177
- }
1178
- }
1179
- ];
1180
- };
1181
- var useHolding = () => {
1182
- const { data, isLoading } = usePrivateQuery(
1183
- "/v1/client/holding",
1184
- {
1185
- formatter: (data2) => {
1186
- return data2.holding;
1187
- }
1188
- }
1189
- );
1190
- const usdc = React2.useMemo(() => {
1191
- const usdc2 = data == null ? void 0 : data.find((item) => item.token === "USDC");
1192
- return usdc2;
1193
- }, [data]);
1194
- return {
1195
- data,
1196
- usdc,
1197
- isLoading
1198
- };
1199
- };
1200
-
1201
- // src/orderly/useCollateral.ts
1202
- var positionsPath = ramda.pathOr([], [0, "rows"]);
1203
- ramda.pathOr(0, [0, "totalCollateral"]);
1204
- var unsettledPnL = ramda.pathOr(0, [0, "aggregated", "unsettledPnL"]);
1205
- var useCollateral = (options = { dp: 6 }) => {
1206
- const { dp } = options;
1207
- const positions2 = usePositionStream();
1208
- const { data: orders } = usePrivateQuery(`/v1/orders`);
1209
- const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1210
- const symbolInfo = useSymbolsInfo();
1211
- const { data: markPrices } = useMarkPricesStream();
1212
- const { usdc } = useHolding();
1213
- const [totalCollateral, totalValue] = React2.useMemo(() => {
1214
- return [
1215
- ramda.pathOr(utils.zero, [0, "totalCollateral"], positions2),
1216
- ramda.pathOr(utils.zero, [0, "totalValue"], positions2)
1217
- ];
1218
- }, [positions2, markPrices]);
1219
- const totalInitialMarginWithOrders = React2.useMemo(() => {
1220
- if (!accountInfo || !symbolInfo || !markPrices) {
1221
- return 0;
1222
- }
1223
- return futures.account.totalInitialMarginWithOrders({
1224
- positions: positionsPath(positions2),
1225
- orders: orders != null ? orders : [],
1226
- markPrices,
1227
- IMR_Factors: accountInfo.imr_factor,
1228
- maxLeverage: accountInfo.max_leverage,
1229
- symbolInfo
1230
- });
1231
- }, [positions2, orders, markPrices, accountInfo, symbolInfo]);
1232
- const freeCollateral = React2.useMemo(() => {
1233
- return futures.account.freeCollateral({
1234
- totalCollateral,
1235
- totalInitialMarginWithOrders
1236
- });
1237
- }, [totalCollateral, totalInitialMarginWithOrders]);
1238
- const availableBalance = React2.useMemo(() => {
1239
- var _a;
1240
- return futures.account.availableBalance({
1241
- USDCHolding: (_a = usdc == null ? void 0 : usdc.holding) != null ? _a : 0,
1242
- unsettlementPnL: unsettledPnL(positions2)
1243
- });
1244
- }, [usdc]);
1245
- return {
1246
- totalCollateral: totalCollateral.toDecimalPlaces(dp).toNumber(),
1247
- freeCollateral: freeCollateral.toDecimalPlaces(dp).toNumber(),
1248
- totalValue: totalValue.toDecimalPlaces(dp).toNumber(),
1249
- availableBalance
1250
- };
1251
- };
1252
- var positionsPath2 = ramda.pathOr([], [0, "rows"]);
1253
- var useMaxQty = (symbol, side, reduceOnly = false) => {
1254
- const positionsData = usePositionStream();
1255
- const { data: orders } = usePrivateQuery(
1256
- `/v1/orders?status=NEW`
1257
- );
1258
- const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1259
- const symbolInfo = useSymbolsInfo();
1260
- const { totalCollateral } = useCollateral();
1261
- const { data: markPrices } = useMarkPricesStream();
1262
- const maxQty = React2.useMemo(() => {
1263
- if (!symbol)
1264
- return 0;
1265
- const positions2 = positionsPath2(positionsData);
1266
- const positionQty = futures.account.getQtyFromPositions(positions2, symbol);
1267
- if (reduceOnly) {
1268
- if (positionQty > 0) {
1269
- if (side === types.OrderSide.BUY) {
1270
- return 0;
1271
- } else {
1272
- return Math.abs(positionQty);
1273
- }
1274
- }
1275
- if (positionQty < 0) {
1276
- if (side === types.OrderSide.BUY) {
1277
- return Math.abs(positionQty);
1278
- } else {
1279
- return 0;
1280
- }
1281
- }
1282
- return 0;
1283
- }
1284
- if (!markPrices || !markPrices[symbol] || !orders || !accountInfo)
1285
- return 0;
1286
- const getSymbolInfo = symbolInfo[symbol];
1287
- const buyOrdersQty = futures.account.getQtyFromOrdersBySide(
1288
- orders,
1289
- symbol,
1290
- types.OrderSide.BUY
1291
- );
1292
- const sellOrdersQty = futures.account.getQtyFromOrdersBySide(
1293
- orders,
1294
- symbol,
1295
- types.OrderSide.SELL
1296
- );
1297
- const otherPositions = positions2.filter(
1298
- (item) => item.symbol !== symbol
1299
- );
1300
- const otherOrders = orders.filter(
1301
- (item) => item.symbol !== symbol
1302
- );
1303
- const otherIMs = futures.account.otherIMs({
1304
- orders: otherOrders,
1305
- positions: otherPositions,
1306
- symbolInfo,
1307
- markPrices,
1308
- IMR_Factors: accountInfo.imr_factor,
1309
- maxLeverage: accountInfo.max_leverage
1310
- });
1311
- return futures.account.maxQty(side, {
1312
- markPrice: markPrices[symbol],
1313
- symbol,
1314
- baseMaxQty: getSymbolInfo("base_max"),
1315
- totalCollateral,
1316
- maxLeverage: accountInfo.max_leverage,
1317
- takerFeeRate: accountInfo.taker_fee_rate,
1318
- baseIMR: getSymbolInfo("base_imr"),
1319
- otherIMs,
1320
- positionQty,
1321
- buyOrdersQty,
1322
- sellOrdersQty,
1323
- IMR_Factor: accountInfo.imr_factor[getSymbolInfo("base")]
1324
- });
1325
- }, [
1326
- orders,
1327
- positionsData,
1328
- markPrices,
1329
- accountInfo,
1330
- symbolInfo,
1331
- symbol,
1332
- side,
1333
- totalCollateral,
1334
- reduceOnly
1335
- ]);
1336
- return maxQty;
1337
- };
1338
- var { maxPrice, minPrice } = futures.order;
1339
- var BaseOrderCreator = class {
1340
- baseOrder(data) {
1341
- const order2 = {
1342
- // symbol: data.symbol,
1343
- order_type: data.order_type === types.OrderType.LIMIT ? !!data.order_type_ext ? data.order_type_ext : data.order_type : data.order_type,
1344
- side: data.side,
1345
- reduce_only: data.reduce_only,
1346
- order_quantity: data.order_quantity
1347
- };
1348
- if (data.visible_quantity === 0) {
1349
- order2.visible_quantity = data.visible_quantity;
1350
- }
1351
- return order2;
1352
- }
1353
- baseValidate(values, configs) {
1354
- const errors = {};
1355
- const { maxQty } = configs;
1356
- const { order_quantity, total } = values;
1357
- if (!order_quantity) {
1358
- errors.order_quantity = {
1359
- type: "required",
1360
- message: "quantity is required"
1361
- };
1362
- } else {
1363
- const { base_min, quote_dp, base_dp } = configs.symbol;
1364
- const qty = new utils.Decimal(order_quantity);
1365
- if (qty.lt(base_min)) {
1366
- errors.order_quantity = {
1367
- type: "min",
1368
- message: `quantity must be greater than ${new utils.Decimal(base_min).todp(
1369
- base_dp
1370
- )}`
1371
- };
1372
- } else if (qty.gt(maxQty)) {
1373
- errors.order_quantity = {
1374
- type: "max",
1375
- message: `quantity must be less than ${new utils.Decimal(maxQty).todp(
1376
- base_dp
1377
- )}`
1378
- };
1379
- }
1380
- }
1381
- if (!!total) {
1382
- const { quote_max, quote_min, quote_dp } = configs.symbol;
1383
- const totalNumber = new utils.Decimal(total);
1384
- if (totalNumber.lt(quote_min)) {
1385
- errors.total = {
1386
- type: "min",
1387
- message: `Quantity should be greater or equal than ${new utils.Decimal(
1388
- quote_min
1389
- ).todp(quote_dp)}`
1390
- };
1391
- } else if (totalNumber.gt(quote_max)) {
1392
- errors.total = {
1393
- type: "max",
1394
- message: `Quantity should be less or equal than ${new utils.Decimal(
1395
- quote_max
1396
- ).todp(quote_dp)}`
1397
- };
1398
- }
1399
- }
1400
- return Promise.resolve(errors);
1401
- }
1402
- };
1403
- var LimitOrderCreator = class extends BaseOrderCreator {
1404
- create(values) {
1405
- return __spreadProps(__spreadValues({}, this.baseOrder(values)), {
1406
- order_price: values.order_price
1407
- });
1408
- }
1409
- validate(values, config) {
1410
- return this.baseValidate(values, config).then((errors) => {
1411
- const { order_price } = values;
1412
- if (!order_price) {
1413
- errors.order_price = {
1414
- type: "required",
1415
- message: "price is required"
1416
- };
1417
- } else {
1418
- const price = new utils.Decimal(order_price);
1419
- const { symbol } = config;
1420
- const { price_range } = symbol;
1421
- const maxPriceNumber = maxPrice(config.markPrice, price_range);
1422
- const minPriceNumber = minPrice(config.markPrice, price_range);
1423
- if (price.lt(minPriceNumber)) {
1424
- errors.order_price = {
1425
- type: "min",
1426
- message: `price must be greater than ${new utils.Decimal(
1427
- minPriceNumber
1428
- ).todp(symbol.quote_dp)}`
1429
- };
1430
- } else if (price.gt(maxPriceNumber)) {
1431
- errors.order_price = {
1432
- type: "max",
1433
- message: `price must be less than ${new utils.Decimal(
1434
- maxPriceNumber
1435
- ).todp(symbol.quote_dp)}`
1436
- };
1437
- }
1438
- }
1439
- return errors;
1440
- });
1441
- }
1442
- };
1443
- var MarketOrderCreator = class extends BaseOrderCreator {
1444
- create(values) {
1445
- const data = this.baseOrder(values);
1446
- delete data["order_price"];
1447
- return __spreadValues({}, data);
1448
- }
1449
- validate(values, configs) {
1450
- return this.baseValidate(values, configs);
1451
- }
1452
- };
1453
- var PostOnlyOrderCreator = class extends LimitOrderCreator {
1454
- };
1455
- var FOKOrderCreator = class extends LimitOrderCreator {
1456
- };
1457
- var IOCOrderCreator = class extends LimitOrderCreator {
1458
- };
1459
- var GeneralOrderCreator = class extends BaseOrderCreator {
1460
- create(data) {
1461
- return __spreadProps(__spreadValues({}, this.baseOrder(data)), {
1462
- order_price: data.order_price,
1463
- order_quantity: data.order_quantity
1464
- });
1465
- }
1466
- validate(values, configs) {
1467
- return super.baseValidate(values, configs);
1468
- }
1469
- };
1470
- var OrderFactory = class {
1471
- static create(type) {
1472
- switch (type) {
1473
- case types.OrderType.LIMIT:
1474
- return new LimitOrderCreator();
1475
- case types.OrderType.MARKET:
1476
- return new MarketOrderCreator();
1477
- case types.OrderType.IOC:
1478
- return new IOCOrderCreator();
1479
- case types.OrderType.FOK:
1480
- return new FOKOrderCreator();
1481
- case types.OrderType.POST_ONLY:
1482
- return new PostOnlyOrderCreator();
1483
- default:
1484
- return new GeneralOrderCreator();
1485
- }
1486
- }
1487
- };
1488
-
1489
- // src/orderly/useOrderEntry.ts
1490
- var useOrderEntry = (symbol, side, reduceOnly = false, options) => {
1491
- const [doCreateOrder] = useMutation("/v1/order");
1492
- const { freeCollateral } = useCollateral();
1493
- const symbolInfo = useSymbolsInfo();
1494
- const tokenInfo = useTokenInfo();
1495
- const baseDP = React2.useMemo(
1496
- () => utils.getPrecisionByNumber(symbolInfo[symbol]("base_tick", 0)),
1497
- [symbolInfo]
1498
- );
1499
- const quoteDP = React2.useMemo(() => {
1500
- return tokenInfo.USDC("decimals", 0);
1501
- }, [tokenInfo]);
1502
- const { data: markPrice } = useMarkPrice(symbol);
1503
- const maxQty = useMaxQty(
1504
- symbol,
1505
- side,
1506
- // orderExtraValues.reduce_only
1507
- reduceOnly
1508
- );
1509
- const onSubmit = (values) => {
1510
- if (!values || typeof values.order_type === "undefined" || values.order_type !== types.OrderType.MARKET && values.order_type !== types.OrderType.LIMIT) {
1511
- throw new Error("order_type is error");
1512
- }
1513
- const orderCreator = OrderFactory.create(
1514
- !!values.order_type_ext ? values.order_type_ext : values.order_type
1515
- );
1516
- if (!orderCreator) {
1517
- return Promise.reject(new Error("orderCreator is null"));
1518
- }
1519
- return orderCreator == null ? void 0 : orderCreator.validate(values, {
1520
- symbol: symbolInfo[symbol](),
1521
- token: tokenInfo[symbol](),
1522
- maxQty,
1523
- markPrice
1524
- }).then(() => {
1525
- if (!orderCreator) {
1526
- throw new Error("orderCreator is null");
1527
- }
1528
- if (!symbol) {
1529
- throw new Error("symbol is null");
1530
- }
1531
- const data = orderCreator.create(values);
1532
- return doCreateOrder(__spreadProps(__spreadValues({}, data), {
1533
- symbol
1534
- }));
1535
- });
1536
- };
1537
- const calculate = React2.useCallback(
1538
- (values, field, value) => {
1539
- console.log("calculate", values, field, value, markPrice);
1540
- const fieldHandler = getCalculateHandler(field);
1541
- const newValues = ramda.compose(
1542
- ramda.head,
1543
- orderEntityFormatHandle(),
1544
- fieldHandler,
1545
- baseInputHandle
1546
- )([values, field, value, markPrice, { baseDP, quoteDP }]);
1547
- return newValues;
1548
- },
1549
- [markPrice]
1550
- );
1551
- const validator = (values) => {
1552
- const creator = OrderFactory.create(values.order_type);
1553
- return creator == null ? void 0 : creator.validate(values, {
1554
- symbol: symbolInfo[symbol](),
1555
- token: tokenInfo[symbol](),
1556
- maxQty,
1557
- markPrice
1558
- });
1559
- };
1560
- return {
1561
- maxQty,
1562
- freeCollateral,
1563
- markPrice,
1564
- onSubmit,
1565
- helper: {
1566
- calculate,
1567
- validator
1568
- },
1569
- symbolConfig: symbolInfo[symbol]()
1570
- };
1571
- };
1572
- var useFetures = () => {
1573
- const { data, isLoading, error } = useQuery(
1574
- `/v1/public/futures`,
1575
- {
1576
- revalidateOnFocus: false
1577
- }
1578
- );
1579
- const [sortedData, setSortedData] = React2.useState(data);
1580
- useWS();
1581
- React2.useEffect(() => {
1582
- }, []);
1583
- React2.useEffect(() => {
1584
- if (data) {
1585
- const sortedData2 = data.sort((a, b) => {
1586
- return 0;
1587
- });
1588
- setSortedData(sortedData2);
1589
- }
1590
- }, [data]);
1591
- const sortBy = React2.useCallback((key) => {
1592
- }, [data]);
1593
- const filterBy = React2.useCallback((key) => {
1594
- }, [data]);
1595
- return {
1596
- // ...data,
1597
- data: sortedData,
1598
- sortBy,
1599
- filterBy,
1600
- isLoading,
1601
- error
1602
- };
1603
- };
1604
-
1605
- // src/orderly/useAccountInfo.ts
1606
- var useAccountInfo = () => {
1607
- return usePrivateQuery("/v1/client/info");
1608
- };
1609
- var useMarketsStream = () => {
1610
- const ws = useWS();
1611
- const { data: futures } = useQuery(`/v1/public/futures`, {
1612
- revalidateOnFocus: false
1613
- });
1614
- const { data: tickers } = useSWRSubscription__default.default("tickers", (_, { next }) => {
1615
- const unsubscribe = ws.subscribe(
1616
- // { event: "subscribe", topic: "markprices" },
1617
- "tickers",
1618
- {
1619
- onMessage: (message) => {
1620
- next(null, message);
1621
- }
1622
- // onUnsubscribe: () => {
1623
- // return "markprices";
1624
- // },
1625
- // onError: (error: any) => {
1626
- // console.log("error", error);
1627
- // },
1628
- }
1629
- );
1630
- return () => {
1631
- console.log("unsubscribe!!!!!!!");
1632
- unsubscribe == null ? void 0 : unsubscribe();
1633
- };
1634
- });
1635
- const value = React2.useMemo(() => {
1636
- if (!futures)
1637
- return null;
1638
- if (!tickers)
1639
- return futures;
1640
- return futures.map((item) => {
1641
- const ticker = tickers.find(
1642
- (t) => t.symbol === item.symbol
1643
- );
1644
- if (ticker) {
1645
- return __spreadProps(__spreadValues({}, item), {
1646
- ["24h_close"]: ticker.close,
1647
- ["24h_open"]: ticker.open,
1648
- ["24h_volumn"]: ticker.volume,
1649
- change: 0
1650
- });
1651
- }
1652
- return item;
1653
- });
1654
- }, [futures, tickers]);
1655
- return { data: value };
1656
- };
1657
- var useLeverage = () => {
1658
- const { data, mutate: mutate2 } = usePrivateQuery("/v1/client/info");
1659
- const [update] = useMutation("/v1/client/leverage");
1660
- const updateLeverage = React2.useCallback((data2) => {
1661
- return update(data2).then((res) => {
1662
- return mutate2();
1663
- });
1664
- }, []);
1665
- return [ramda.prop("max_leverage", data), { update: updateLeverage }];
1666
- };
1667
- var useFundingRate = (symbol) => {
1668
- var _a;
1669
- if (!symbol) {
1670
- throw new Error("useFuturesForSymbol requires a symbol");
1671
- }
1672
- const [countDown, setCountDown] = React2.useState("00:00:00");
1673
- const { data } = useQuery(
1674
- `/v1/public/funding_rate/${symbol}`,
1675
- {
1676
- fallbackData: {
1677
- est_funding_rate: 0,
1678
- next_funing_time: 0
1679
- }
1680
- }
1681
- );
1682
- React2.useEffect(() => {
1683
- if (!data)
1684
- return;
1685
- const { next_funding_time } = data;
1686
- if (!next_funding_time || next_funding_time <= 0) {
1687
- return;
1688
- }
1689
- const timer = setInterval(() => {
1690
- const diff = new Date(next_funding_time).getTime() - Date.now();
1691
- const result = utils.timeConvertString(diff);
1692
- if (result.length === 3) {
1693
- setCountDown(
1694
- `${result[0].toString().padStart(2, "0")}:${result[1].toString().padStart(2, "0")}:${result[2].toString().padStart(2, "0")}`
1695
- );
1696
- }
1697
- }, 1e3);
1698
- return () => {
1699
- clearInterval(timer);
1700
- };
1701
- }, [data]);
1702
- return __spreadProps(__spreadValues({}, data), {
1703
- est_funding_rate: (Number((_a = data == null ? void 0 : data.est_funding_rate) != null ? _a : 0) * 100).toFixed(4),
1704
- countDown
1705
- });
1706
- };
1707
- var fetcher3 = (url, init) => net.get(url, init);
1708
- var usePrivateInfiniteQuery = (getKey, options) => {
1709
- var _a;
1710
- const account5 = useAccount();
1711
- const middleware = Array.isArray(options == null ? void 0 : options.use) ? (_a = options == null ? void 0 : options.use) != null ? _a : [] : [];
1712
- const result = useSWRInfinite__default.default(
1713
- (pageIndex, previousPageData) => account5.state.status >= types.AccountStatusEnum.EnableTrading ? getKey(pageIndex, previousPageData) : null,
1714
- fetcher3,
1715
- __spreadProps(__spreadValues({}, options), {
1716
- use: [signatureMiddleware, ...middleware]
1717
- })
1718
- );
1719
- return result;
1720
- };
1721
- var OrderStatus = /* @__PURE__ */ ((OrderStatus2) => {
1722
- OrderStatus2["FILLED"] = "FILLED";
1723
- OrderStatus2["PARTIAL_FILLED"] = "PARTIAL_FILLED";
1724
- OrderStatus2["CANCELED"] = "CANCELED";
1725
- OrderStatus2["NEW"] = "NEW";
1726
- OrderStatus2["COMPLETED"] = "COMPLETED";
1727
- return OrderStatus2;
1728
- })(OrderStatus || {});
1729
- var useOrderStream = ({
1730
- status,
1731
- symbol,
1732
- side,
1733
- size = 100
1734
- } = {}) => {
1735
- const ee = useEventEmitter();
1736
- const { data: markPrices = {} } = useMarkPricesStream();
1737
- const [doCancelOrder] = useMutation("/v1/order", "DELETE");
1738
- const [doUpdateOrder] = useMutation("/v1/order", "PUT");
1739
- const ordersResponse = usePrivateInfiniteQuery(
1740
- (pageIndex, previousPageData) => {
1741
- const search = new URLSearchParams([
1742
- ["size", size.toString()],
1743
- ["page", `${pageIndex + 1}`]
1744
- // [`status`, status],
1745
- ]);
1746
- if (status) {
1747
- search.set(`status`, status);
1748
- }
1749
- if (symbol) {
1750
- search.set(`symbol`, symbol);
1751
- }
1752
- if (side) {
1753
- search.set(`side`, side);
1754
- }
1755
- return `/v1/orders?${search.toString()}`;
1756
- },
1757
- {
1758
- initialSize: 1,
1759
- onError: (err) => {
1760
- console.error("fetch failed::::", err);
1761
- }
1762
- }
1763
- );
1764
- const orders = React2.useMemo(() => {
1765
- var _a;
1766
- if (!ordersResponse.data) {
1767
- return null;
1768
- }
1769
- return (_a = ordersResponse.data) == null ? void 0 : _a.flat().map((item) => {
1770
- var _a2;
1771
- return __spreadProps(__spreadValues({}, item), {
1772
- mark_price: (_a2 = markPrices[item.symbol]) != null ? _a2 : 0
1773
- });
1774
- });
1775
- }, [ordersResponse.data, markPrices]);
1776
- React2.useEffect(() => {
1777
- const handler = () => ordersResponse.mutate();
1778
- ee.on("orders:changed", handler);
1779
- return () => {
1780
- ee.off("orders:changed", handler);
1781
- };
1782
- }, []);
1783
- const cancelAllOrders = React2.useCallback(() => {
1784
- }, [ordersResponse.data]);
1785
- const updateOrder = React2.useCallback((orderId, order2) => {
1786
- return doUpdateOrder(__spreadProps(__spreadValues({}, order2), { order_id: orderId }));
1787
- }, []);
1788
- const cancelOrder = React2.useCallback((orderId, symbol2) => {
1789
- return doCancelOrder(null, {
1790
- order_id: orderId,
1791
- symbol: symbol2
1792
- }).then((res) => {
1793
- if (res.success) {
1794
- return ordersResponse.mutate().then(() => {
1795
- return res;
1796
- });
1797
- } else {
1798
- throw new Error(res.message);
1799
- }
1800
- });
1801
- }, []);
1802
- return [
1803
- orders,
1804
- {
1805
- cancelAllOrders,
1806
- updateOrder,
1807
- cancelOrder
1808
- }
1809
- ];
1810
- };
1811
- var useMarketTradeStream = (symbol, options = {}) => {
1812
- if (!symbol) {
1813
- throw new Error("useTradeStream: symbol is required");
1814
- }
1815
- const [trades, setTrades] = React2.useState([]);
1816
- const [isLoading, setIsLoading] = React2.useState(false);
1817
- React2.useState(() => symbol);
1818
- const { limit = 50 } = options;
1819
- const ws = useWS();
1820
- React2.useEffect(() => {
1821
- setIsLoading(true);
1822
- setTrades(() => []);
1823
- ws.onceSubscribe(
1824
- {
1825
- id: `${symbol}@trade`,
1826
- event: "request",
1827
- params: {
1828
- type: "trade",
1829
- symbol,
1830
- limit
1831
- }
1832
- },
1833
- {
1834
- onMessage: (data) => {
1835
- setIsLoading(false);
1836
- setTrades(() => data);
1837
- }
1838
- }
1839
- );
1840
- }, [symbol]);
1841
- React2.useEffect(() => {
1842
- const unsubscript = ws.subscribe(
1843
- {
1844
- id: `${symbol}@trade`,
1845
- event: "subscribe",
1846
- topic: `${symbol}@trade`,
1847
- ts: Date.now()
1848
- },
1849
- {
1850
- onMessage: (data) => {
1851
- setTrades((prev) => {
1852
- const arr = [__spreadProps(__spreadValues({}, data), { ts: Date.now() }), ...prev];
1853
- if (arr.length > limit) {
1854
- arr.pop();
1855
- }
1856
- return arr;
1857
- });
1858
- }
1859
- }
1860
- );
1861
- return () => {
1862
- unsubscript == null ? void 0 : unsubscript();
1863
- };
1864
- }, [symbol]);
1865
- console.log("trades", trades);
1866
- return { data: trades, isLoading };
1867
- };
1868
- var useMarginRatio = () => {
1869
- const [{ rows }] = usePositionStream();
1870
- const { data: markPrices } = useMarkPricesStream();
1871
- const { totalCollateral } = useCollateral();
1872
- const marginRatio = React2.useMemo(() => {
1873
- if (!rows || !markPrices || !totalCollateral || rows.length === 0) {
1874
- return 0;
1875
- }
1876
- const ratio = futures.account.totalMarginRatio({
1877
- totalCollateral,
1878
- markPrices,
1879
- positions: rows != null ? rows : []
1880
- });
1881
- return ratio;
1882
- }, [rows, markPrices, totalCollateral]);
1883
- const currentLeverage = React2.useMemo(() => {
1884
- return futures.account.currentLeverage(marginRatio);
1885
- }, [marginRatio]);
1886
- return { marginRatio, currentLeverage };
1887
- };
1888
- var useChains = (networkId, options = {}) => {
1889
- const _a = options, swrOptions = __objRest(_a, ["filter", "pick"]);
1890
- const field = options == null ? void 0 : options.pick;
1891
- const { data } = useSWR__default.default(
1892
- "https://fi-api.woo.org/swap_support",
1893
- (url) => fetch(url).then((res) => res.json()),
1894
- __spreadValues({
1895
- revalidateOnFocus: false,
1896
- revalidateOnReconnect: false
1897
- }, swrOptions)
1898
- );
1899
- const chains = React2.useMemo(() => {
1900
- if (!data || !data.data)
1901
- return data;
1902
- let arr = [];
1903
- Object.keys(data.data).forEach((key) => {
1904
- const item = data.data[key];
1905
- arr.push(__spreadProps(__spreadValues({}, item), {
1906
- name: key
1907
- }));
1908
- });
1909
- if (networkId === "mainnet") {
1910
- arr = arr.filter((item) => item.network_infos.mainnet);
1911
- }
1912
- if (networkId === "testnet") {
1913
- arr = arr.filter((item) => !item.network_infos.mainnet);
1914
- }
1915
- if (typeof (options == null ? void 0 : options.filter) === "function") {
1916
- arr = arr.filter(options.filter);
1917
- }
1918
- if (typeof field !== "undefined") {
1919
- return arr.map((item) => {
1920
- return item[field];
1921
- });
1922
- }
1923
- return arr;
1924
- }, [data, networkId, field, options]);
1925
- const findByChainId = React2.useCallback(
1926
- (chainId) => {
1927
- if (!data || !data.data)
1928
- return void 0;
1929
- return data.data[chainId];
1930
- },
1931
- [data]
1932
- );
1933
- return [chains, { findByChainId }];
1934
- };
1935
- var useBalance = () => {
1936
- const ws = useWS();
1937
- const { data } = useSWRSubscription__default.default("balance", (_, { next }) => {
1938
- const unsubscribe = ws.privateSubscribe("balance", {
1939
- onMessage: (data2) => {
1940
- console.log(data2);
1941
- }
1942
- });
1943
- return () => unsubscribe();
1944
- });
1945
- return data;
1946
- };
1947
- var usePrivateDataObserver = () => {
1948
- const ws = useWS();
1949
- const { mutate: mutate2 } = useSWR.useSWRConfig();
1950
- const ee = useEventEmitter();
1951
- const { state } = useAccount();
1952
- React2.useEffect(() => {
1953
- console.log("subscribe: executionreport");
1954
- const unsubscribe = ws.privateSubscribe("executionreport", {
1955
- onMessage: (data) => {
1956
- ee.emit("orders:changed");
1957
- }
1958
- });
1959
- return () => unsubscribe == null ? void 0 : unsubscribe();
1960
- }, []);
1961
- React2.useEffect(() => {
1962
- console.log("subscribe: position: %s", state.accountId);
1963
- if (!state.accountId)
1964
- return;
1965
- const key = ["/v1/positions", state.accountId];
1966
- const unsubscribe = ws.privateSubscribe("position", {
1967
- onMessage: (data) => {
1968
- const { positions: nextPostions } = data;
1969
- console.info("refresh positions:", nextPostions, state.accountId);
1970
- mutate2(key, (prevPositions) => {
1971
- console.log("prevPositions:::::", prevPositions);
1972
- if (!!prevPositions) {
1973
- return __spreadProps(__spreadValues({}, prevPositions), {
1974
- rows: prevPositions.rows.map((row) => {
1975
- const item = nextPostions.find(
1976
- (item2) => item2.symbol === row.symbol
1977
- );
1978
- if (item) {
1979
- return {
1980
- symbol: item.symbol,
1981
- position_qty: item.positionQty,
1982
- cost_position: item.costPosition,
1983
- last_sum_unitary_funding: item.lastSumUnitaryFunding,
1984
- pending_long_qty: item.pendingLongQty,
1985
- pending_short_qty: item.pendingShortQty,
1986
- settle_price: item.settlePrice,
1987
- average_open_price: item.averageOpenPrice,
1988
- unsettled_pnl: item.unsettledPnl,
1989
- mark_price: item.markPrice,
1990
- est_liq_price: item.estLiqPrice,
1991
- timestamp: Date.now(),
1992
- imr: item.imr,
1993
- mmr: item.mmr,
1994
- IMR_withdraw_orders: item.imrwithOrders,
1995
- MMR_with_orders: item.mmrwithOrders,
1996
- pnl_24_h: item.pnl24H,
1997
- fee_24_h: item.fee24H
1998
- };
1999
- }
2000
- return row;
2001
- })
2002
- });
2003
- }
2004
- });
2005
- }
2006
- });
2007
- return () => {
2008
- console.log("unsubscribe: private subscription position");
2009
- unsubscribe == null ? void 0 : unsubscribe();
2010
- };
2011
- }, [state.accountId]);
2012
- };
2013
- var useExecutionReport = () => {
2014
- const ws = useWS();
2015
- const { data } = useSWRSubscription__default.default("executionreport", (_, { next }) => {
2016
- const unsubscribe = ws.privateSubscribe("executionreport", {
2017
- onMessage: (data2) => {
2018
- console.log(data2);
2019
- }
2020
- });
2021
- return () => unsubscribe();
2022
- });
2023
- return data;
2024
- };
2025
-
2026
- // src/apis/index.ts
2027
- var apis_exports = {};
2028
- __export(apis_exports, {
2029
- useFundingRateBySymbol: () => useFundingRateBySymbol,
2030
- useInfo: () => useInfo,
2031
- useToken: () => useToken
2032
- });
2033
-
2034
- // src/apis/useInfo.ts
2035
- var useInfo = () => {
2036
- return useQuery("/v1/public/info", {
2037
- // refreshInterval: 1000 * 60 * 60 * 24,
2038
- });
2039
- };
2040
-
2041
- // src/apis/useToken.ts
2042
- var useToken = () => {
2043
- return useQuery("/v1/public/token");
2044
- };
2045
-
2046
- // src/apis/useFundingRateBySymbol.ts
2047
- var useFundingRateBySymbol = (symbol) => {
2048
- if (!symbol) {
2049
- throw new Error("symbol is required");
2050
- }
2051
- return useQuery(`/public/funding_rate/${symbol}`);
2052
- };
2053
-
2054
- Object.defineProperty(exports, 'SWRConfig', {
2055
- enumerable: true,
2056
- get: function () { return useSWR.SWRConfig; }
2057
- });
2058
- Object.defineProperty(exports, 'useSWR', {
2059
- enumerable: true,
2060
- get: function () { return useSWR__default.default; }
2061
- });
2062
- Object.defineProperty(exports, 'useConstant', {
2063
- enumerable: true,
2064
- get: function () { return useConstant__default.default; }
2065
- });
2066
- exports.DataSourceProvider = DataSourceProvider;
2067
- exports.OrderStatus = OrderStatus;
2068
- exports.OrderlyContext = OrderlyContext;
2069
- exports.OrderlyProvider = OrderlyProvider;
2070
- exports.apis = apis_exports;
2071
- exports.useAccount = useAccount;
2072
- exports.useAccountInfo = useAccountInfo;
2073
- exports.useAccountInstance = useAccountInstance;
2074
- exports.useAppState = useAppState;
2075
- exports.useBalance = useBalance;
2076
- exports.useChains = useChains;
2077
- exports.useCollateral = useCollateral;
2078
- exports.useEventEmitter = useEventEmitter;
2079
- exports.useExecutionReport = useExecutionReport;
2080
- exports.useFetures = useFetures;
2081
- exports.useFundingRate = useFundingRate;
2082
- exports.useHolding = useHolding;
2083
- exports.useLeverage = useLeverage;
2084
- exports.useLocalStorage = useLocalStorage;
2085
- exports.useMarginRatio = useMarginRatio;
2086
- exports.useMarkPrice = useMarkPrice;
2087
- exports.useMarkPricesStream = useMarkPricesStream;
2088
- exports.useMarketTradeStream = useMarketTradeStream;
2089
- exports.useMarketsStream = useMarketsStream;
2090
- exports.useMaxQty = useMaxQty;
2091
- exports.useMutation = useMutation;
2092
- exports.useOrderEntry = useOrderEntry;
2093
- exports.useOrderStream = useOrderStream;
2094
- exports.useOrderbookStream = useOrderbookStream;
2095
- exports.usePositionStream = usePositionStream;
2096
- exports.usePreLoadData = usePreLoadData;
2097
- exports.usePrivateDataObserver = usePrivateDataObserver;
2098
- exports.usePrivateObserve = usePrivateObserve;
2099
- exports.usePrivateQuery = usePrivateQuery;
2100
- exports.useQuery = useQuery;
2101
- exports.useRunOnce = useRunOnce;
2102
- exports.useSessionStorage = useSessionStorage;
2103
- exports.useSymbolsInfo = useSymbolsInfo;
2104
- exports.useTickerStream = useTickerStream;
2105
- exports.useTokenInfo = useTokenInfo;
2106
- exports.useTopicObserve = useTopicObserve;
2107
- exports.useTradingView = useTradingView;
2108
- exports.useWS = useWS;
2109
- //# sourceMappingURL=out.js.map
2110
- //# sourceMappingURL=index.js.map