@orderly.network/hooks 1.0.8 → 1.0.10

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.mjs CHANGED
@@ -8,7 +8,6 @@ export { default as useConstant } from 'use-constant';
8
8
  import { SimpleDI, Account, EventEmitter, MemoryConfigStore, LocalStorageStore, EtherAdapter, utils } from '@orderly.network/core';
9
9
  import { AccountStatusEnum, OrderStatus, OrderSide, chainsInfoMap, ARBITRUM_TESTNET_CHAINID, ARBITRUM_MAINNET_CHAINID, WS_WalletStatusEnum, OrderType } from '@orderly.network/types';
10
10
  import useSWRInfinite from 'swr/infinite';
11
- import { jsx } from 'react/jsx-runtime';
12
11
  import { Decimal, zero, getPrecisionByNumber, timeConvertString } from '@orderly.network/utils';
13
12
  import useSWRSubscription from 'swr/subscription';
14
13
  import { pathOr, propOr, compose, head, prop, mergeDeepRight, pick, min } from 'ramda';
@@ -22,9 +21,6 @@ var OrderlyContext = createContext({
22
21
  // configStore: new MemoryConfigStore(),
23
22
  });
24
23
  var OrderlyProvider = OrderlyContext.Provider;
25
- var useOrderlyContext = () => {
26
- return useContext(OrderlyContext);
27
- };
28
24
 
29
25
  // src/useConfig.ts
30
26
  var useConfig = (key, defaultValue) => {
@@ -280,22 +276,15 @@ var useBoolean = (initialValue = false) => {
280
276
  return [value, { setTrue, setFalse, toggle }];
281
277
  };
282
278
  var usePreLoadData = () => {
283
- const { configStore } = useContext(OrderlyContext);
284
- const { error: swapSupportError, data: swapSupportData } = useSWR(
285
- `${configStore.get("swapSupportApiUrl")}/swap_support`,
286
- (url) => fetch(url).then((res) => res.json()),
287
- {
288
- revalidateOnFocus: false
289
- }
290
- );
279
+ useContext(OrderlyContext);
291
280
  const { error: tokenError, data: tokenData } = useQuery("/v1/public/token", {
292
281
  revalidateOnFocus: false
293
282
  });
294
283
  const isDone = useMemo(() => {
295
- return !!swapSupportData && !!tokenData;
296
- }, [swapSupportData, tokenData]);
284
+ return !!tokenData;
285
+ }, [tokenData]);
297
286
  return {
298
- error: swapSupportError || tokenError,
287
+ error: tokenError,
299
288
  done: isDone
300
289
  };
301
290
  };
@@ -439,7 +428,7 @@ var useWS = () => {
439
428
  };
440
429
  var OrderlyConfigProvider = (props) => {
441
430
  const [account5, setAccount] = React.useState(null);
442
- const { configStore, keyStore, getWalletAdapter, brokerId, networkId } = props;
431
+ const { configStore, keyStore, getWalletAdapter, brokerId, networkId, enableSwapDeposit } = props;
443
432
  if (!brokerId && typeof configStore === "undefined") {
444
433
  console.error("[OrderlyConfigProvider]: brokerId is required");
445
434
  }
@@ -467,17 +456,19 @@ var OrderlyConfigProvider = (props) => {
467
456
  if (!account5) {
468
457
  return null;
469
458
  }
470
- return /* @__PURE__ */ jsx(
459
+ return /* @__PURE__ */ React.createElement(
471
460
  OrderlyProvider,
472
461
  {
473
462
  value: {
474
463
  configStore: innerConfigStore,
475
464
  keyStore: innerKeyStore,
476
465
  getWalletAdapter: innerGetWalletAdapter,
477
- networkId
478
- },
479
- children: props.children
480
- }
466
+ networkId,
467
+ enableSwapDeposit
468
+ // apiBaseUrl,
469
+ }
470
+ },
471
+ props.children
481
472
  );
482
473
  };
483
474
  var WalletConnectorContext = createContext({});
@@ -1094,8 +1085,8 @@ var usePositionStream = (symbol, options) => {
1094
1085
  const fundingRates = useFundingRates();
1095
1086
  const {
1096
1087
  data,
1097
- error
1098
- // mutate: updatePositions,
1088
+ error,
1089
+ mutate: updatePositions
1099
1090
  } = usePrivateQuery(`/v1/positions`, {
1100
1091
  // revalidateOnFocus: false,
1101
1092
  // revalidateOnReconnect: false,
@@ -1107,6 +1098,10 @@ var usePositionStream = (symbol, options) => {
1107
1098
  onError: (err) => {
1108
1099
  }
1109
1100
  });
1101
+ usePositionUpdateStream((positions2) => {
1102
+ console.log("position message", positions2);
1103
+ updatePositions();
1104
+ });
1110
1105
  const { data: markPrices } = useMarkPricesStream();
1111
1106
  const formatedPositions = useMemo(() => {
1112
1107
  if (!data?.rows || !symbolInfo || !accountInfo)
@@ -1255,6 +1250,41 @@ var pathOr_unsettledPnLPathOr = pathOr(0, [
1255
1250
  "aggregated",
1256
1251
  "unsettledPnL"
1257
1252
  ]);
1253
+ var usePositionUpdateStream = (callback) => {
1254
+ const ws = useWS();
1255
+ const positionList = useRef({});
1256
+ return useSWRSubscription("positionUpdate", (key, { next }) => {
1257
+ const unsubscribe = ws.privateSubscribe(
1258
+ // { event: "subscribe", topic: "markprices" },
1259
+ "position",
1260
+ {
1261
+ onMessage: (message) => {
1262
+ const { positions: positions2 } = message;
1263
+ let update = false;
1264
+ for (const p in positions2) {
1265
+ const { symbol, positionQty } = positions2[p];
1266
+ if (positionList.current[symbol] !== positionQty) {
1267
+ update = true;
1268
+ positionList.current[symbol] = positionQty;
1269
+ }
1270
+ }
1271
+ if (update) {
1272
+ callback(positions2.current);
1273
+ }
1274
+ next(null, positionList);
1275
+ },
1276
+ // onUnsubscribe: () => {
1277
+ // return "markprices";
1278
+ // },
1279
+ onError: (error) => {
1280
+ }
1281
+ }
1282
+ );
1283
+ return () => {
1284
+ unsubscribe?.();
1285
+ };
1286
+ });
1287
+ };
1258
1288
  var useHoldingStream = () => {
1259
1289
  const ws = useWS();
1260
1290
  const { data, isLoading, mutate: mutate2 } = usePrivateQuery(
@@ -1269,7 +1299,7 @@ var useHoldingStream = () => {
1269
1299
  const usdc2 = data?.find((item) => item.token === "USDC");
1270
1300
  return usdc2;
1271
1301
  }, [data]);
1272
- const { data: balance } = useSWRSubscription("holding", (_, { next }) => {
1302
+ useSWRSubscription("holding", (_, { next }) => {
1273
1303
  const unsubscribe = ws.privateSubscribe(
1274
1304
  {
1275
1305
  id: "balance",
@@ -1301,7 +1331,6 @@ var useHoldingStream = () => {
1301
1331
  return {
1302
1332
  data,
1303
1333
  usdc,
1304
- balance,
1305
1334
  isLoading
1306
1335
  };
1307
1336
  };
@@ -1532,11 +1561,37 @@ var useCollateral = (options = { dp: 6 }) => {
1532
1561
  var positionsPath2 = pathOr([], [0, "rows"]);
1533
1562
  var useMaxQty = (symbol, side, reduceOnly = false) => {
1534
1563
  const positionsData = usePositionStream();
1535
- const [orders] = useOrderStream({ status: OrderStatus.NEW });
1536
1564
  const { data: accountInfo } = usePrivateQuery("/v1/client/info");
1537
1565
  const symbolInfo = useSymbolsInfo();
1538
1566
  const { totalCollateral } = useCollateral();
1539
1567
  const { data: markPrices } = useMarkPricesStream();
1568
+ const {
1569
+ data: orders,
1570
+ error,
1571
+ mutate: updateOrder
1572
+ } = usePrivateQuery(`/v1/orders?status=NEW&size=99`, {
1573
+ formatter: (data) => data.rows,
1574
+ onError: (err) => {
1575
+ }
1576
+ });
1577
+ const ws = useWS();
1578
+ useEffect(() => {
1579
+ const unsubscribe = ws.privateSubscribe(
1580
+ {
1581
+ id: "executionreport_orders",
1582
+ event: "subscribe",
1583
+ topic: "executionreport",
1584
+ ts: Date.now()
1585
+ },
1586
+ {
1587
+ onMessage: (data) => {
1588
+ console.log("refresh orders", data);
1589
+ updateOrder();
1590
+ }
1591
+ }
1592
+ );
1593
+ return () => unsubscribe();
1594
+ }, []);
1540
1595
  const maxQty = useMemo(() => {
1541
1596
  if (!symbol)
1542
1597
  return 0;
@@ -3080,6 +3135,17 @@ var useChains = (networkId, options = {}) => {
3080
3135
  ...swrOptions
3081
3136
  }
3082
3137
  );
3138
+ const { data: chainInfos, error: chainInfoErr } = useQuery(
3139
+ "/v1/public/chain_info",
3140
+ {
3141
+ revalidateIfStale: false,
3142
+ revalidateOnFocus: false,
3143
+ revalidateOnReconnect: false,
3144
+ revalidateOnMount: true,
3145
+ dedupingInterval: 36e5,
3146
+ formatter: (data2) => data2.rows
3147
+ }
3148
+ );
3083
3149
  const { data: orderlyChains, error: tokenError } = useQuery(
3084
3150
  "/v1/public/token",
3085
3151
  {
@@ -3120,41 +3186,48 @@ var useChains = (networkId, options = {}) => {
3120
3186
  if (!options.filter(_chain))
3121
3187
  return;
3122
3188
  }
3189
+ if (_chain.chain_id === 421613) {
3190
+ const index = testnetArr.findIndex((item2) => item2.network_infos.chain_id === 421613);
3191
+ if (index > -1) {
3192
+ testnetArr[index] = _chain;
3193
+ }
3194
+ }
3123
3195
  map.current.set(chainId, _chain);
3124
3196
  orderlyChainsArr.push(_chain);
3125
3197
  });
3126
3198
  });
3127
- if (!wooSwapEnabled) {
3128
- let arr = orderlyChainsArr;
3129
- if (typeof options?.filter === "function") {
3130
- arr = orderlyChainsArr.filter(options.filter);
3131
- }
3132
- if (!!field) {
3133
- arr = arr.map((item) => item[field]);
3199
+ let testnetArr = [
3200
+ //@ts-ignore
3201
+ {
3202
+ network_infos: {
3203
+ name: "Arbitrum Goerli",
3204
+ shortName: "Arbitrum Goerli",
3205
+ public_rpc_url: "https://goerli-rollup.arbitrum.io/rpc",
3206
+ chain_id: 421613,
3207
+ currency_symbol: "ETH",
3208
+ bridge_enable: true,
3209
+ mainnet: false,
3210
+ explorer_base_url: "https://goerli.arbiscan.io/",
3211
+ est_txn_mins: null,
3212
+ woofi_dex_cross_chain_router: "",
3213
+ woofi_dex_depositor: ""
3214
+ },
3215
+ token_infos: [
3216
+ {
3217
+ symbol: "USDC",
3218
+ address: "0xfd064A18f3BF249cf1f87FC203E90D8f650f2d63",
3219
+ decimals: 6,
3220
+ swap_enable: false,
3221
+ woofi_dex_precision: 2
3222
+ }
3223
+ ]
3134
3224
  }
3135
- return arr;
3136
- } else {
3225
+ ];
3226
+ let mainnetArr = [];
3227
+ map.current.set(421613, testnetArr[0]);
3228
+ if (wooSwapEnabled) {
3137
3229
  if (!data || !data.data)
3138
3230
  return data;
3139
- let testnetArr = [
3140
- //@ts-ignore
3141
- {
3142
- network_infos: {
3143
- name: "Arbitrum Goerli",
3144
- shortName: "Arbitrum Goerli",
3145
- public_rpc_url: "https://goerli-rollup.arbitrum.io/rpc",
3146
- chain_id: 421613,
3147
- currency_symbol: "ETH",
3148
- bridge_enable: true,
3149
- mainnet: false,
3150
- explorer_base_url: "https://goerli.arbiscan.io/",
3151
- est_txn_mins: null,
3152
- woofi_dex_cross_chain_router: "",
3153
- woofi_dex_depositor: ""
3154
- }
3155
- }
3156
- ];
3157
- let mainnetArr = [];
3158
3231
  Object.keys(data.data).forEach((key) => {
3159
3232
  const chain = data.data[key];
3160
3233
  const item = mergeDeepRight(chain, {
@@ -3180,27 +3253,65 @@ var useChains = (networkId, options = {}) => {
3180
3253
  testnetArr.push(item);
3181
3254
  }
3182
3255
  });
3183
- mainnetArr.sort((a, b) => {
3184
- return a.network_infos.bridgeless ? -1 : 1;
3185
- });
3186
- testnetArr.sort((a, b) => {
3187
- return a.network_infos.bridgeless ? -1 : 1;
3256
+ } else {
3257
+ if (!chainInfos)
3258
+ return void 0;
3259
+ orderlyChainsArr.forEach((chain) => {
3260
+ let _chain = chain;
3261
+ const networkInfo = chainInfos.find((item) => {
3262
+ console.log(item.chain_id, chain.network_infos.chain_id);
3263
+ return item.chain_id == chain.network_infos.chain_id;
3264
+ });
3265
+ if (networkInfo) {
3266
+ const { name, public_rpc_url, chain_id, currency_symbol, explorer_base_url } = networkInfo;
3267
+ _chain.network_infos = {
3268
+ ..._chain.network_infos,
3269
+ name,
3270
+ shortName: name,
3271
+ public_rpc_url,
3272
+ currency_symbol,
3273
+ bridge_enable: true,
3274
+ mainnet: true,
3275
+ explorer_base_url,
3276
+ est_txn_mins: null,
3277
+ woofi_dex_cross_chain_router: "",
3278
+ woofi_dex_depositor: ""
3279
+ };
3280
+ }
3281
+ map.current.set(_chain.network_infos.chain_id, _chain);
3282
+ if (_chain.network_infos.chain_id === 421613) {
3283
+ const index = testnetArr.findIndex((item) => item.network_infos.chain_id === 421613);
3284
+ if (index > -1) {
3285
+ testnetArr[index] = _chain;
3286
+ }
3287
+ }
3288
+ if (typeof options?.filter === "function") {
3289
+ if (!options.filter(_chain))
3290
+ return;
3291
+ }
3292
+ mainnetArr.push(_chain);
3188
3293
  });
3189
- if (!!field) {
3190
- testnetArr = testnetArr.map((item) => item[field]);
3191
- mainnetArr = mainnetArr.map((item) => item[field]);
3192
- }
3193
- if (networkId === "mainnet") {
3194
- return mainnetArr;
3195
- }
3196
- if (networkId === "testnet") {
3197
- return testnetArr;
3198
- }
3199
- return {
3200
- testnet: testnetArr,
3201
- mainnet: mainnetArr
3202
- };
3203
3294
  }
3295
+ mainnetArr.sort((a, b) => {
3296
+ return a.network_infos.bridgeless ? -1 : 1;
3297
+ });
3298
+ testnetArr.sort((a, b) => {
3299
+ return a.network_infos.bridgeless ? -1 : 1;
3300
+ });
3301
+ if (!!field) {
3302
+ testnetArr = testnetArr.map((item) => item[field]);
3303
+ mainnetArr = mainnetArr.map((item) => item[field]);
3304
+ }
3305
+ if (networkId === "mainnet") {
3306
+ return mainnetArr;
3307
+ }
3308
+ if (networkId === "testnet") {
3309
+ return testnetArr;
3310
+ }
3311
+ return {
3312
+ testnet: testnetArr,
3313
+ mainnet: mainnetArr
3314
+ };
3204
3315
  }, [data, networkId, field, options, orderlyChains, wooSwapEnabled]);
3205
3316
  const findByChainId = useCallback(
3206
3317
  (chainId, field2) => {
@@ -3269,11 +3380,11 @@ var useWithdraw = () => {
3269
3380
  return { withdraw, isLoading, maxAmount, availableBalance, unsettledPnL };
3270
3381
  };
3271
3382
  var useDeposit = (options) => {
3272
- const { onlyTestnet } = useContext(OrderlyContext);
3383
+ const { onlyTestnet, enableSwapDeposit } = useContext(OrderlyContext);
3273
3384
  const [balanceRevalidating, setBalanceRevalidating] = useState(false);
3274
3385
  const [allowanceRevalidating, setAllowanceRevalidating] = useState(false);
3275
3386
  const [_, { findByChainId }] = useChains(void 0, {
3276
- wooSwapEnabled: true
3387
+ wooSwapEnabled: enableSwapDeposit
3277
3388
  });
3278
3389
  const [balance, setBalance] = useState("0");
3279
3390
  const [allowance, setAllowance] = useState("0");
@@ -3281,7 +3392,7 @@ var useDeposit = (options) => {
3281
3392
  const prevAddress = useRef();
3282
3393
  const getBalanceListener = useRef();
3283
3394
  const dst = useMemo(() => {
3284
- const chain = onlyTestnet ? findByChainId(ARBITRUM_TESTNET_CHAINID) : findByChainId(ARBITRUM_MAINNET_CHAINID);
3395
+ const chain = onlyTestnet || 421613 == options?.srcChainId ? findByChainId(ARBITRUM_TESTNET_CHAINID) : findByChainId(ARBITRUM_MAINNET_CHAINID);
3285
3396
  const USDC = chain?.token_infos.find((token) => token.symbol === "USDC");
3286
3397
  if (!chain) {
3287
3398
  throw new Error("dst chain not found");
@@ -3501,17 +3612,6 @@ var usePrivateDataObserver = () => {
3501
3612
  const ws = useWS();
3502
3613
  const { mutate: mutate2 } = useSWRConfig();
3503
3614
  const { state } = useAccount();
3504
- useEffect(() => {
3505
- console.log("----!!!usePrivateDataObserver!!!----");
3506
- }, []);
3507
- useEffect(() => {
3508
- const unsubscribe = ws.privateSubscribe("executionreport", {
3509
- onMessage: (data) => {
3510
- console.log(data);
3511
- }
3512
- });
3513
- return () => unsubscribe?.();
3514
- }, [state.accountId]);
3515
3615
  useEffect(() => {
3516
3616
  if (!state.accountId)
3517
3617
  return;
@@ -3519,7 +3619,6 @@ var usePrivateDataObserver = () => {
3519
3619
  const unsubscribe = ws.privateSubscribe("position", {
3520
3620
  onMessage: (data) => {
3521
3621
  const { positions: nextPostions } = data;
3522
- console.log("ws-----data-----", data);
3523
3622
  mutate2(key, (prevPositions) => {
3524
3623
  if (!!prevPositions) {
3525
3624
  return {
@@ -4164,6 +4263,6 @@ var useSwap = () => {
4164
4263
  };
4165
4264
  };
4166
4265
 
4167
- export { OrderlyConfigProvider, OrderlyContext, OrderlyProvider, WalletConnectorContext, useAccount, useAccountInfo, useAccountInstance, useBoolean, useChain, useChains, useCollateral, useConfig, useCrossSwap, useDeposit, useEventEmitter, useFundingRate, useHoldingStream, useIndexPrice, useLazyQuery, useLeverage, useLocalStorage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbookStream, useOrderlyContext, usePositionStream, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, useSessionStorage, useSettleSubscription, useSwap, useSymbolsInfo, useTickerStream, useWS, useWalletConnector, useWalletSubscription, useWithdraw, useWooCrossSwapQuery, useWooSwapQuery };
4266
+ export { OrderlyConfigProvider, OrderlyContext, OrderlyProvider, WalletConnectorContext, useAccount, useAccountInfo, useAccountInstance, useBoolean, useChain, useChains, useCollateral, useConfig, useCrossSwap, useDeposit, useEventEmitter, useFundingRate, useHoldingStream, useIndexPrice, useLazyQuery, useLeverage, useLocalStorage, useMarginRatio, useMarkPrice, useMarkPricesStream, useMarketTradeStream, useMarketsStream, useMaxQty, useMutation, useOrderEntry, useOrderStream, useOrderbookStream, usePositionStream, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, useSessionStorage, useSettleSubscription, useSwap, useSymbolsInfo, useTickerStream, useWS, useWalletConnector, useWalletSubscription, useWithdraw, useWooCrossSwapQuery, useWooSwapQuery };
4168
4267
  //# sourceMappingURL=out.js.map
4169
4268
  //# sourceMappingURL=index.mjs.map