@orderly.network/hooks 0.0.39 → 0.0.40

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.
@@ -0,0 +1,331 @@
1
+ import useSWR, { SWRConfiguration, SWRResponse } from 'swr';
2
+ export { SWRConfig, SWRConfiguration, default as useSWR } from 'swr';
3
+ import { SWRMutationConfiguration } from 'swr/mutation';
4
+ import { Account, AccountState, ConfigStore, OrderlyKeyStore, getWalletAdapterFunc, IContract, EventEmitter } from '@orderly.network/core';
5
+ import * as react from 'react';
6
+ import react__default, { FC, PropsWithChildren } from 'react';
7
+ export { default as useConstant } from 'use-constant';
8
+ import { WS } from '@orderly.network/net';
9
+ import { OrderSide, OrderEntity, API, WSMessage } from '@orderly.network/types';
10
+ import * as swr__internal from 'swr/_internal';
11
+ import * as swr_subscription from 'swr/subscription';
12
+
13
+ type useQueryOptions<T> = SWRConfiguration & {
14
+ formatter?: (data: any) => T;
15
+ };
16
+
17
+ /**
18
+ * useQuery
19
+ * @description for public api
20
+ * @param query
21
+ * @param options
22
+ */
23
+ declare const useQuery: <T>(query: Parameters<typeof useSWR>["0"], options?: useQueryOptions<T> | undefined) => SWRResponse<T, any, any>;
24
+
25
+ type HTTP_METHOD = "POST" | "PUT" | "DELETE";
26
+ declare const useMutation: <T, E>(url: string, method?: HTTP_METHOD, options?: SWRMutationConfiguration<T, E> | undefined) => [any, any];
27
+
28
+ /**
29
+ * usePrivateQuery
30
+ * @description for private api
31
+ * @param query
32
+ * @param options
33
+ */
34
+ declare const usePrivateQuery: <T>(query: string, options?: useQueryOptions<T> | undefined) => SWRResponse<T, any, any>;
35
+
36
+ declare const useTradingView: () => {};
37
+
38
+ declare const usePrivateObserve: <T>() => {
39
+ data: T | undefined;
40
+ };
41
+
42
+ declare const useTopicObserve: <T>(topic: string) => {
43
+ data: T | undefined;
44
+ };
45
+
46
+ declare const useAccount: () => {
47
+ account: Account;
48
+ state: AccountState;
49
+ login: (address: string) => void;
50
+ createOrderlyKey: (remember: boolean) => Promise<string>;
51
+ createAccount: () => Promise<string>;
52
+ disconnect: () => Promise<void>;
53
+ connect: () => Promise<any>;
54
+ setChain: (chainId: number) => Promise<any>;
55
+ };
56
+
57
+ declare const useAccountInstance: () => Account;
58
+
59
+ interface OrderlyAppConfig {
60
+ logoUrl: string;
61
+ theme: any;
62
+ }
63
+ type AppStateErrors = {
64
+ ChainNetworkNotSupport: boolean;
65
+ IpNotSupport: boolean;
66
+ NetworkError: boolean;
67
+ };
68
+ interface OrderlyContextState extends OrderlyAppConfig {
69
+ fetcher?: (url: string, init: RequestInit) => Promise<any>;
70
+ apiBaseUrl: string;
71
+ klineDataUrl: string;
72
+ configStore: ConfigStore;
73
+ keyStore: OrderlyKeyStore;
74
+ getWalletAdapter: getWalletAdapterFunc;
75
+ contractManager: IContract;
76
+ networkId: string;
77
+ brokerId: string;
78
+ onWalletConnect?: () => Promise<any>;
79
+ onWalletDisconnect?: () => Promise<any>;
80
+ onSetChain?: (chainId: number) => Promise<any>;
81
+ ready: boolean;
82
+ onAppTestChange?: (name: string) => void;
83
+ errors: AppStateErrors;
84
+ }
85
+ declare const OrderlyContext: react.Context<OrderlyContextState>;
86
+ declare const OrderlyProvider: react.Provider<OrderlyContextState>;
87
+
88
+ declare const useAppState: () => {
89
+ errors: AppStateErrors;
90
+ ready: boolean;
91
+ };
92
+
93
+ declare const usePreLoadData: (onSuccess: (name: string) => void) => void;
94
+
95
+ declare const useEventEmitter: (channel?: string) => EventEmitter<string | symbol, any>;
96
+
97
+ declare function useSessionStorage<T>(key: string, initialValue: T): [T, (data: any) => void];
98
+
99
+ declare function useLocalStorage<T>(key: string, initialValue: T): [T, any];
100
+
101
+ type useRunOnceProps = {
102
+ fn: () => any;
103
+ sessionKey?: string;
104
+ };
105
+ declare const useRunOnce: react__default.FC<useRunOnceProps>;
106
+
107
+ declare const DataSourceProvider: FC<PropsWithChildren>;
108
+
109
+ declare const useWS: () => WS;
110
+
111
+ type OrderBookItem = number[];
112
+ type OrderbookData = {
113
+ asks: OrderBookItem[];
114
+ bids: OrderBookItem[];
115
+ };
116
+ type OrderbookOptions = {
117
+ level?: number;
118
+ };
119
+ /**
120
+ * @name useOrderbookStream
121
+ * @description React hook that returns the current orderbook for a given market
122
+ */
123
+ declare const useOrderbookStream: (symbol: string, initial?: OrderbookData, options?: OrderbookOptions) => ({
124
+ markPrice: any;
125
+ middlePrice: any;
126
+ asks: OrderBookItem[];
127
+ bids: OrderBookItem[];
128
+ onDepthChange?: undefined;
129
+ depth?: undefined;
130
+ allDepths?: undefined;
131
+ isLoading?: undefined;
132
+ onItemClick?: undefined;
133
+ } | {
134
+ onDepthChange: (depth: number) => void;
135
+ depth: number | undefined;
136
+ allDepths: any[];
137
+ isLoading: boolean;
138
+ onItemClick: (item: OrderBookItem) => void;
139
+ })[];
140
+
141
+ interface OrderEntryReturn {
142
+ onSubmit: (values: OrderEntity) => Promise<any>;
143
+ maxQty: number;
144
+ freeCollateral: number;
145
+ markPrice: number;
146
+ symbolConfig: API.SymbolExt;
147
+ helper: {
148
+ calculate: (values: any, field: string, value: any) => any;
149
+ validator: (values: any) => any;
150
+ };
151
+ }
152
+ type UseOrderEntryOptions = {
153
+ commify?: boolean;
154
+ validate?: (data: OrderEntity) => {
155
+ [P in keyof OrderEntity]?: string;
156
+ } | null | undefined;
157
+ };
158
+ /**
159
+ * 创建订单
160
+ * @param symbol
161
+ * @returns
162
+ */
163
+ declare const useOrderEntry: (symbol: string, side: OrderSide, reduceOnly?: boolean, options?: UseOrderEntryOptions) => OrderEntryReturn;
164
+
165
+ interface MarketInfo {
166
+ }
167
+ declare const useFetures: () => {
168
+ data: MarketInfo[] | undefined;
169
+ sortBy: (key: string) => void;
170
+ filterBy: (key: string) => void;
171
+ isLoading: boolean;
172
+ error: any;
173
+ };
174
+
175
+ declare const useSymbolsInfo: () => any;
176
+
177
+ declare const useAccountInfo: () => swr__internal.SWRResponse<API.AccountInfo, any, any>;
178
+
179
+ declare const useTokenInfo: () => any;
180
+
181
+ declare const useMarketsStream: () => {
182
+ data: WSMessage.Ticker[] | null;
183
+ };
184
+
185
+ declare const useMarkPricesStream: () => swr_subscription.SWRSubscriptionResponse<any, any>;
186
+
187
+ declare const useMarkPrice: (symbol: string) => swr_subscription.SWRSubscriptionResponse<any, any>;
188
+
189
+ declare const useLeverage: () => ({
190
+ update: (data: any) => any;
191
+ } | undefined)[];
192
+
193
+ declare const useTickerStream: (symbol: string) => any;
194
+
195
+ declare const useFundingRate: (symbol: string) => {
196
+ est_funding_rate: string;
197
+ countDown: string;
198
+ symbol?: string | undefined;
199
+ est_funding_rate_timestamp?: number | undefined;
200
+ last_funding_rate?: number | undefined;
201
+ last_funding_rate_timestamp?: number | undefined;
202
+ next_funding_time?: number | undefined;
203
+ sum_unitary_funding?: number | undefined;
204
+ };
205
+
206
+ declare const usePositionStream: (symbol?: string, options?: SWRConfiguration) => any[];
207
+
208
+ declare enum OrderStatus {
209
+ FILLED = "FILLED",
210
+ PARTIAL_FILLED = "PARTIAL_FILLED",
211
+ CANCELED = "CANCELED",
212
+ NEW = "NEW",
213
+ COMPLETED = "COMPLETED"
214
+ }
215
+ declare const useOrderStream: ({ status, symbol, side, size, }?: {
216
+ symbol?: string | undefined;
217
+ status?: OrderStatus | undefined;
218
+ size?: number | undefined;
219
+ side?: OrderSide | undefined;
220
+ }) => (any[] | {
221
+ cancelAllOrders: () => void;
222
+ updateOrder: (orderId: string, order: OrderEntity) => any;
223
+ cancelOrder: (orderId: string, symbol?: string) => any;
224
+ } | null)[];
225
+
226
+ interface MarketTradeStreamOptions {
227
+ limit?: number;
228
+ }
229
+ declare const useMarketTradeStream: (symbol: string, options?: MarketTradeStreamOptions) => {
230
+ data: API.Trade[];
231
+ isLoading: boolean;
232
+ };
233
+
234
+ type CollateralOutputs = {
235
+ totalCollateral: number;
236
+ freeCollateral: number;
237
+ totalValue: number;
238
+ availableBalance: number;
239
+ };
240
+ /**
241
+ * 用户保证金
242
+ * @returns
243
+ */
244
+ type Options = {
245
+ dp: number;
246
+ };
247
+ declare const useCollateral: (options?: Options) => CollateralOutputs;
248
+
249
+ declare const useMaxQty: (symbol: string, side: OrderSide, reduceOnly?: boolean) => number;
250
+
251
+ declare const useMarginRatio: () => {
252
+ marginRatio: number;
253
+ currentLeverage: number;
254
+ };
255
+
256
+ type inputOptions = {
257
+ filter?: (item: API.Chain) => boolean;
258
+ pick?: "dexs" | "network_infos" | "token_infos";
259
+ };
260
+ declare const useChains: (networkId?: "testnet" | "mainnet", options?: inputOptions & SWRConfiguration) => any[];
261
+
262
+ declare const useHolding: () => {
263
+ data: API.Holding[] | undefined;
264
+ usdc: API.Holding | undefined;
265
+ isLoading: boolean;
266
+ };
267
+
268
+ declare const useBalance: () => any;
269
+
270
+ declare const usePrivateDataObserver: () => void;
271
+
272
+ declare const useExecutionReport: () => any;
273
+
274
+ interface Info {
275
+ symbol: string;
276
+ quote_min: number;
277
+ quote_max: number;
278
+ quote_tick: number;
279
+ base_min: number;
280
+ base_max: number;
281
+ base_tick: number;
282
+ min_notional: number;
283
+ price_range: number;
284
+ created_time: number;
285
+ updated_time: number;
286
+ }
287
+ /**
288
+ * useInfo
289
+ * @returns
290
+ */
291
+ declare const useInfo: () => swr__internal.SWRResponse<Info[], any, any>;
292
+
293
+ interface Token {
294
+ token: string;
295
+ token_account_id: string;
296
+ decimals: number;
297
+ minimum_increment: number;
298
+ }
299
+ /**
300
+ * useToken
301
+ * @description get token info
302
+ */
303
+ declare const useToken: () => swr__internal.SWRResponse<Token[], any, any>;
304
+
305
+ interface FundingRate {
306
+ symbol: string;
307
+ est_funding_rate: number;
308
+ est_funding_rate_timestamp: number;
309
+ last_funding_rate: number;
310
+ last_funding_rate_timestamp: number;
311
+ next_funding_time: number;
312
+ sum_unitary_funding: number;
313
+ }
314
+ /**
315
+ * FundingRate
316
+ * @param symbol
317
+ */
318
+ declare const useFundingRateBySymbol: (symbol: string) => swr__internal.SWRResponse<FundingRate, any, any>;
319
+
320
+ declare const index_useFundingRateBySymbol: typeof useFundingRateBySymbol;
321
+ declare const index_useInfo: typeof useInfo;
322
+ declare const index_useToken: typeof useToken;
323
+ declare namespace index {
324
+ export {
325
+ index_useFundingRateBySymbol as useFundingRateBySymbol,
326
+ index_useInfo as useInfo,
327
+ index_useToken as useToken,
328
+ };
329
+ }
330
+
331
+ export { AppStateErrors, DataSourceProvider, OrderStatus, OrderlyAppConfig, OrderlyContext, OrderlyContextState, OrderlyProvider, index as apis, useAccount, useAccountInfo, useAccountInstance, useAppState, useBalance, useChains, useCollateral, useEventEmitter, useExecutionReport, useFetures, useFundingRate, useHolding, useLeverage, useLocalStorage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePreLoadData, usePrivateDataObserver, usePrivateObserve, usePrivateQuery, useQuery, useRunOnce, useSessionStorage, useSymbolsInfo, useTickerStream, useTokenInfo, useTopicObserve, useTradingView, useWS };
package/dist/index.mjs CHANGED
@@ -6,7 +6,7 @@ import useSWRMutation from 'swr/mutation';
6
6
  import useConstant from 'use-constant';
7
7
  export { default as useConstant } from 'use-constant';
8
8
  import { SimpleDI, Account, EventEmitter } from '@orderly.network/core';
9
- import { AccountStatusEnum, OrderSide, OrderType } from '@orderly.network/types';
9
+ import { AccountStatusEnum, OrderSide, OrderStatus as OrderStatus$1, OrderType } from '@orderly.network/types';
10
10
  import useSWRSubscription from 'swr/subscription';
11
11
  import { Decimal, zero, getPrecisionByNumber, timeConvertString } from '@orderly.network/utils';
12
12
  import { pathOr, propOr, compose, head, prop } from 'ramda';
@@ -205,8 +205,6 @@ var useAccount = () => {
205
205
  const {
206
206
  configStore,
207
207
  keyStore,
208
- walletAdapter,
209
- contractManager,
210
208
  onWalletConnect,
211
209
  onWalletDisconnect,
212
210
  onSetChain
@@ -1196,7 +1194,9 @@ var unsettledPnL = pathOr(0, [0, "aggregated", "unsettledPnL"]);
1196
1194
  var useCollateral = (options = { dp: 6 }) => {
1197
1195
  const { dp } = options;
1198
1196
  const positions2 = usePositionStream();
1199
- const { data: orders } = usePrivateQuery(`/v1/orders`);
1197
+ const { data: orders } = usePrivateQuery(
1198
+ `/v1/orders?status=NEW`
1199
+ );
1200
1200
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1201
1201
  const symbolInfo = useSymbolsInfo();
1202
1202
  const { data: markPrices } = useMarkPricesStream();
@@ -1709,13 +1709,13 @@ var usePrivateInfiniteQuery = (getKey, options) => {
1709
1709
  );
1710
1710
  return result;
1711
1711
  };
1712
- var OrderStatus = /* @__PURE__ */ ((OrderStatus2) => {
1713
- OrderStatus2["FILLED"] = "FILLED";
1714
- OrderStatus2["PARTIAL_FILLED"] = "PARTIAL_FILLED";
1715
- OrderStatus2["CANCELED"] = "CANCELED";
1716
- OrderStatus2["NEW"] = "NEW";
1717
- OrderStatus2["COMPLETED"] = "COMPLETED";
1718
- return OrderStatus2;
1712
+ var OrderStatus = /* @__PURE__ */ ((OrderStatus3) => {
1713
+ OrderStatus3["FILLED"] = "FILLED";
1714
+ OrderStatus3["PARTIAL_FILLED"] = "PARTIAL_FILLED";
1715
+ OrderStatus3["CANCELED"] = "CANCELED";
1716
+ OrderStatus3["NEW"] = "NEW";
1717
+ OrderStatus3["COMPLETED"] = "COMPLETED";
1718
+ return OrderStatus3;
1719
1719
  })(OrderStatus || {});
1720
1720
  var useOrderStream = ({
1721
1721
  status,
@@ -1941,14 +1941,40 @@ var usePrivateDataObserver = () => {
1941
1941
  const ee = useEventEmitter();
1942
1942
  const { state } = useAccount();
1943
1943
  useEffect(() => {
1944
- console.log("subscribe: executionreport");
1945
1944
  const unsubscribe = ws.privateSubscribe("executionreport", {
1946
1945
  onMessage: (data) => {
1946
+ const key = ["/v1/orders?status=NEW", state.accountId];
1947
+ mutate2(key, (orders) => {
1948
+ return Promise.resolve().then(() => {
1949
+ if (!orders) {
1950
+ return orders;
1951
+ }
1952
+ if (data.status === OrderStatus$1.NEW) {
1953
+ return [
1954
+ __spreadProps(__spreadValues({}, data), {
1955
+ // average_executed_price:data.ava
1956
+ created_time: data.timestamp,
1957
+ order_id: data.orderId
1958
+ // reduce_only
1959
+ }),
1960
+ ...orders
1961
+ ];
1962
+ }
1963
+ if (data.status === OrderStatus$1.CANCELLED) {
1964
+ return orders.filter(
1965
+ (order2) => order2.order_id !== data.orderId
1966
+ );
1967
+ }
1968
+ return orders;
1969
+ }).catch((error) => {
1970
+ console.log("error", error, error.stack);
1971
+ });
1972
+ });
1947
1973
  ee.emit("orders:changed");
1948
1974
  }
1949
1975
  });
1950
1976
  return () => unsubscribe == null ? void 0 : unsubscribe();
1951
- }, []);
1977
+ }, [state.accountId]);
1952
1978
  useEffect(() => {
1953
1979
  console.log("subscribe: position: %s", state.accountId);
1954
1980
  if (!state.accountId)
@@ -1957,9 +1983,7 @@ var usePrivateDataObserver = () => {
1957
1983
  const unsubscribe = ws.privateSubscribe("position", {
1958
1984
  onMessage: (data) => {
1959
1985
  const { positions: nextPostions } = data;
1960
- console.info("refresh positions:", nextPostions, state.accountId);
1961
1986
  mutate2(key, (prevPositions) => {
1962
- console.log("prevPositions:::::", prevPositions);
1963
1987
  if (!!prevPositions) {
1964
1988
  return __spreadProps(__spreadValues({}, prevPositions), {
1965
1989
  rows: prevPositions.rows.map((row) => {