@orderly.network/hooks 1.0.9 → 1.0.11

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
@@ -5,10 +5,9 @@ import React, { createContext, useContext, useState, useEffect, useCallback, use
5
5
  import useSWRMutation from 'swr/mutation';
6
6
  import useConstant4 from 'use-constant';
7
7
  export { default as useConstant } from 'use-constant';
8
- import { SimpleDI, Account, EventEmitter, MemoryConfigStore, LocalStorageStore, EtherAdapter, utils } from '@orderly.network/core';
8
+ import { SimpleDI, Account, EventEmitter, DefaultConfigStore, 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,12 +428,12 @@ 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
  }
446
435
  const innerConfigStore = useConstant4(() => {
447
- return configStore || new MemoryConfigStore({ brokerId });
436
+ return configStore || new DefaultConfigStore({ brokerId, networkId });
448
437
  });
449
438
  const innerKeyStore = useConstant4(() => {
450
439
  return keyStore || new LocalStorageStore(networkId);
@@ -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,8 +3135,20 @@ 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
- "/v1/public/token",
3150
+ // wooSwapEnabled ? "/v1/public/token" :
3151
+ "https://api-evm.orderly.org/v1/public/token",
3085
3152
  {
3086
3153
  revalidateIfStale: false,
3087
3154
  revalidateOnFocus: false,
@@ -3120,41 +3187,48 @@ var useChains = (networkId, options = {}) => {
3120
3187
  if (!options.filter(_chain))
3121
3188
  return;
3122
3189
  }
3190
+ if (_chain.chain_id === 421613) {
3191
+ const index = testnetArr.findIndex((item2) => item2.network_infos.chain_id === 421613);
3192
+ if (index > -1) {
3193
+ testnetArr[index] = _chain;
3194
+ }
3195
+ }
3123
3196
  map.current.set(chainId, _chain);
3124
3197
  orderlyChainsArr.push(_chain);
3125
3198
  });
3126
3199
  });
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]);
3200
+ let testnetArr = [
3201
+ //@ts-ignore
3202
+ {
3203
+ network_infos: {
3204
+ name: "Arbitrum Goerli",
3205
+ shortName: "Arbitrum Goerli",
3206
+ public_rpc_url: "https://goerli-rollup.arbitrum.io/rpc",
3207
+ chain_id: 421613,
3208
+ currency_symbol: "ETH",
3209
+ bridge_enable: true,
3210
+ mainnet: false,
3211
+ explorer_base_url: "https://goerli.arbiscan.io/",
3212
+ est_txn_mins: null,
3213
+ woofi_dex_cross_chain_router: "",
3214
+ woofi_dex_depositor: ""
3215
+ },
3216
+ token_infos: [
3217
+ {
3218
+ symbol: "USDC",
3219
+ address: "0xfd064A18f3BF249cf1f87FC203E90D8f650f2d63",
3220
+ decimals: 6,
3221
+ swap_enable: false,
3222
+ woofi_dex_precision: 2
3223
+ }
3224
+ ]
3134
3225
  }
3135
- return arr;
3136
- } else {
3226
+ ];
3227
+ let mainnetArr = [];
3228
+ map.current.set(421613, testnetArr[0]);
3229
+ if (wooSwapEnabled) {
3137
3230
  if (!data || !data.data)
3138
3231
  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
3232
  Object.keys(data.data).forEach((key) => {
3159
3233
  const chain = data.data[key];
3160
3234
  const item = mergeDeepRight(chain, {
@@ -3180,27 +3254,65 @@ var useChains = (networkId, options = {}) => {
3180
3254
  testnetArr.push(item);
3181
3255
  }
3182
3256
  });
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;
3257
+ } else {
3258
+ if (!chainInfos)
3259
+ return void 0;
3260
+ orderlyChainsArr.forEach((chain) => {
3261
+ let _chain = chain;
3262
+ const networkInfo = chainInfos.find((item) => {
3263
+ console.log(item.chain_id, chain.network_infos.chain_id);
3264
+ return item.chain_id == chain.network_infos.chain_id;
3265
+ });
3266
+ if (networkInfo) {
3267
+ const { name, public_rpc_url, chain_id, currency_symbol, explorer_base_url } = networkInfo;
3268
+ _chain.network_infos = {
3269
+ ..._chain.network_infos,
3270
+ name,
3271
+ shortName: name,
3272
+ public_rpc_url,
3273
+ currency_symbol,
3274
+ bridge_enable: true,
3275
+ mainnet: true,
3276
+ explorer_base_url,
3277
+ est_txn_mins: null,
3278
+ woofi_dex_cross_chain_router: "",
3279
+ woofi_dex_depositor: ""
3280
+ };
3281
+ }
3282
+ map.current.set(_chain.network_infos.chain_id, _chain);
3283
+ if (_chain.network_infos.chain_id === 421613) {
3284
+ const index = testnetArr.findIndex((item) => item.network_infos.chain_id === 421613);
3285
+ if (index > -1) {
3286
+ testnetArr[index] = _chain;
3287
+ }
3288
+ }
3289
+ if (typeof options?.filter === "function") {
3290
+ if (!options.filter(_chain))
3291
+ return;
3292
+ }
3293
+ mainnetArr.push(_chain);
3188
3294
  });
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
3295
  }
3296
+ mainnetArr.sort((a, b) => {
3297
+ return a.network_infos.bridgeless ? -1 : 1;
3298
+ });
3299
+ testnetArr.sort((a, b) => {
3300
+ return a.network_infos.bridgeless ? -1 : 1;
3301
+ });
3302
+ if (!!field) {
3303
+ testnetArr = testnetArr.map((item) => item[field]);
3304
+ mainnetArr = mainnetArr.map((item) => item[field]);
3305
+ }
3306
+ if (networkId === "mainnet") {
3307
+ return mainnetArr;
3308
+ }
3309
+ if (networkId === "testnet") {
3310
+ return testnetArr;
3311
+ }
3312
+ return {
3313
+ testnet: testnetArr,
3314
+ mainnet: mainnetArr
3315
+ };
3204
3316
  }, [data, networkId, field, options, orderlyChains, wooSwapEnabled]);
3205
3317
  const findByChainId = useCallback(
3206
3318
  (chainId, field2) => {
@@ -3269,11 +3381,12 @@ var useWithdraw = () => {
3269
3381
  return { withdraw, isLoading, maxAmount, availableBalance, unsettledPnL };
3270
3382
  };
3271
3383
  var useDeposit = (options) => {
3272
- const { onlyTestnet } = useContext(OrderlyContext);
3384
+ const { onlyTestnet, enableSwapDeposit } = useContext(OrderlyContext);
3385
+ const networkId = useConfig("networkId");
3273
3386
  const [balanceRevalidating, setBalanceRevalidating] = useState(false);
3274
3387
  const [allowanceRevalidating, setAllowanceRevalidating] = useState(false);
3275
3388
  const [_, { findByChainId }] = useChains(void 0, {
3276
- wooSwapEnabled: true
3389
+ wooSwapEnabled: enableSwapDeposit
3277
3390
  });
3278
3391
  const [balance, setBalance] = useState("0");
3279
3392
  const [allowance, setAllowance] = useState("0");
@@ -3281,8 +3394,10 @@ var useDeposit = (options) => {
3281
3394
  const prevAddress = useRef();
3282
3395
  const getBalanceListener = useRef();
3283
3396
  const dst = useMemo(() => {
3284
- const chain = onlyTestnet ? findByChainId(ARBITRUM_TESTNET_CHAINID) : findByChainId(ARBITRUM_MAINNET_CHAINID);
3285
- const USDC = chain?.token_infos.find((token) => token.symbol === "USDC");
3397
+ const chain = networkId === "testnet" ? findByChainId(ARBITRUM_TESTNET_CHAINID) : findByChainId(ARBITRUM_MAINNET_CHAINID);
3398
+ const USDC = chain?.token_infos.find(
3399
+ (token) => token.symbol === "USDC"
3400
+ );
3286
3401
  if (!chain) {
3287
3402
  throw new Error("dst chain not found");
3288
3403
  }
@@ -3294,7 +3409,7 @@ var useDeposit = (options) => {
3294
3409
  network: chain.network_infos.shortName
3295
3410
  // chainId: 42161,
3296
3411
  };
3297
- }, []);
3412
+ }, [networkId]);
3298
3413
  const isNativeToken = useMemo(
3299
3414
  () => isNativeTokenChecker(options?.address || ""),
3300
3415
  [options?.address]
@@ -3501,17 +3616,6 @@ var usePrivateDataObserver = () => {
3501
3616
  const ws = useWS();
3502
3617
  const { mutate: mutate2 } = useSWRConfig();
3503
3618
  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
3619
  useEffect(() => {
3516
3620
  if (!state.accountId)
3517
3621
  return;
@@ -3519,7 +3623,6 @@ var usePrivateDataObserver = () => {
3519
3623
  const unsubscribe = ws.privateSubscribe("position", {
3520
3624
  onMessage: (data) => {
3521
3625
  const { positions: nextPostions } = data;
3522
- console.log("ws-----data-----", data);
3523
3626
  mutate2(key, (prevPositions) => {
3524
3627
  if (!!prevPositions) {
3525
3628
  return {
@@ -4164,6 +4267,6 @@ var useSwap = () => {
4164
4267
  };
4165
4268
  };
4166
4269
 
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 };
4270
+ 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
4271
  //# sourceMappingURL=out.js.map
4169
4272
  //# sourceMappingURL=index.mjs.map