@orderly.network/hooks 2.6.1 → 2.6.2

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
@@ -6,7 +6,7 @@ export { unstable_serialize, default as useSWR, useSWRConfig } from 'swr';
6
6
  import { TesntTokenFallback, ArbitrumSepoliaTokenInfo, SolanaDevnetTokenInfo, OrderType, OrderSide, SDKError, TrackerEventName, AccountStatusEnum, EMPTY_LIST, AlgoOrderType, AlgoOrderRootType, OrderStatus, EMPTY_OBJECT, ArbitrumSepoliaChainInfo, SolanaDevnetChainInfo, ARBITRUM_TESTNET_CHAINID, SOLANA_TESTNET_CHAINID, MONAD_TESTNET_CHAINID, ABSTRACT_TESTNET_CHAINID, BSC_TESTNET_CHAINID, nativeTokenAddress, ChainKey, chainsInfoMap, ARBITRUM_MAINNET_CHAINID, isNativeTokenChecker, ChainNamespace, MaxUint256, ETHEREUM_MAINNET_CHAINID, DEPOSIT_FEE_RATE, LedgerWalletKey, SolanaChains, PositionType, DistributionType, TriggerPriceType } from '@orderly.network/types';
7
7
  import React2, { createContext, useContext, useCallback, useState, useEffect, useMemo, useRef, useId, useLayoutEffect } from 'react';
8
8
  import useSWRMutation from 'swr/mutation';
9
- import { zero, windowGuard, getTimestamp, getGlobalObject, Decimal, timeConvertString, isTestnet, getPrecisionByNumber, camelCaseToUnderscoreCase, removeTrailingZeros, commify, todpIfNeed } from '@orderly.network/utils';
9
+ import { zero, windowGuard, getTimestamp, getGlobalObject, Decimal, timeConvertString, isTestnet, getPrecisionByNumber, camelCaseToUnderscoreCase, commify, todpIfNeed } from '@orderly.network/utils';
10
10
  import useConstant from 'use-constant';
11
11
  export { default as useConstant } from 'use-constant';
12
12
  import { SimpleDI, Account, EventEmitter, DefaultConfigStore, EVENT_NAMES, LocalStorageStore } from '@orderly.network/core';
@@ -36,9 +36,9 @@ var __export = (target, all) => {
36
36
  // src/version.ts
37
37
  if (typeof window !== "undefined") {
38
38
  window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};
39
- window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.6.1";
39
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.6.2";
40
40
  }
41
- var version_default = "2.6.1";
41
+ var version_default = "2.6.2";
42
42
  var fetcher = (url, init2 = {}, queryOptions) => get(url, init2, queryOptions?.formatter);
43
43
  var OrderlyContext = createContext({
44
44
  // configStore: new MemoryConfigStore(),
@@ -47,6 +47,8 @@ var useOrderlyContext = () => {
47
47
  return useContext(OrderlyContext);
48
48
  };
49
49
  var OrderlyProvider = OrderlyContext.Provider;
50
+
51
+ // src/useConfig.ts
50
52
  function useConfig(key, defaultValue) {
51
53
  const { configStore } = useContext(OrderlyContext);
52
54
  if (!configStore) {
@@ -278,7 +280,7 @@ var useWS = () => {
278
280
  networkId: configStore.get("networkId"),
279
281
  publicUrl: configStore.get("publicWsUrl"),
280
282
  privateUrl: configStore.get("privateWsUrl"),
281
- onSigntureRequest: async (accountId) => {
283
+ onSigntureRequest: async () => {
282
284
  const signer = account9.signer;
283
285
  const timestamp = getTimestamp();
284
286
  const result = await signer.signText(timestamp.toString());
@@ -680,10 +682,28 @@ var apiKeyMap = {
680
682
  staging: "dffc00e003479b86d410c448e00f2304",
681
683
  prod: "3ab9ae56ed16cc57bc2ac97ffc1098c2"
682
684
  };
685
+ function getAmplitudeConfig(env, amplitudeConfig) {
686
+ if (!amplitudeConfig) {
687
+ return {
688
+ amplitudeId: apiKeyMap[env],
689
+ options: {
690
+ serverZone: "EU"
691
+ }
692
+ };
693
+ }
694
+ const { amplitudeId, serverZone } = amplitudeConfig;
695
+ return {
696
+ amplitudeId,
697
+ options: serverZone ? {
698
+ serverZone
699
+ } : {}
700
+ };
701
+ }
683
702
  var AmplitudeTracker = class {
684
- constructor(env, sdkInfo) {
703
+ constructor(env, amplitudeConfig, sdkInfo) {
685
704
  this._ee = SimpleDI.get("EE");
686
- amplitude.init(apiKeyMap[env], { serverZone: "EU" });
705
+ const { amplitudeId, options } = getAmplitudeConfig(env, amplitudeConfig);
706
+ amplitude.init(amplitudeId, options);
687
707
  this.setSdkInfo(sdkInfo);
688
708
  this._bindEvents();
689
709
  }
@@ -735,15 +755,16 @@ AmplitudeTracker.instanceName = "amplitudeTracker";
735
755
 
736
756
  // src/useTrackInstance.ts
737
757
  var useTrackingInstance = () => {
738
- const { configStore } = useContext(OrderlyContext);
739
- if (!configStore)
758
+ const { configStore, amplitudeConfig } = useContext(OrderlyContext);
759
+ if (!configStore) {
740
760
  throw new Error("configStore is not defined, please use OrderlyProvider");
761
+ }
741
762
  const env = configStore.get("env");
742
763
  const brokerId = configStore.get("brokerId");
743
764
  const trackInstace = useConstant(() => {
744
765
  let instance = SimpleDI.get("amplitudeTracker");
745
766
  if (!instance) {
746
- instance = new AmplitudeTracker(env, {
767
+ instance = new AmplitudeTracker(env, amplitudeConfig ?? void 0, {
747
768
  brokerId,
748
769
  sdk_version: window?.__ORDERLY_VERSION__?.["@orderly.network/net"] ?? ""
749
770
  });
@@ -820,6 +841,9 @@ var DEFAULT_TICK_SIZES = {
820
841
  PERP_ETH_USDC: "0.1",
821
842
  PERP_SOL_USDC: "0.01"
822
843
  };
844
+ var DEFAULT_SYMBOL_DEPTHS = {
845
+ PERP_ETH_USDC: [0.01, 0.1, 0.5, 1, 10]
846
+ };
823
847
  var ProxyConfigStore = class {
824
848
  constructor(_originConfigStore) {
825
849
  this._originConfigStore = _originConfigStore;
@@ -1933,8 +1957,9 @@ var CalculatorService = class {
1933
1957
  this.ctx?.clearCache();
1934
1958
  }
1935
1959
  get windowIsVisible() {
1936
- if (typeof document === "undefined")
1960
+ if (typeof document === "undefined") {
1937
1961
  return true;
1962
+ }
1938
1963
  return document.visibilityState === "visible";
1939
1964
  }
1940
1965
  };
@@ -2418,7 +2443,7 @@ var PortfolioCalculator = class extends BaseCalculator {
2418
2443
  accountInfo,
2419
2444
  symbolsInfo,
2420
2445
  indexPrices,
2421
- tokensInfo: tokensInfo ?? []
2446
+ tokensInfo: tokensInfo ?? EMPTY_LIST
2422
2447
  });
2423
2448
  }
2424
2449
  getPortfolio(ctx) {
@@ -2485,7 +2510,7 @@ var PortfolioCalculator = class extends BaseCalculator {
2485
2510
  };
2486
2511
  }
2487
2512
  update(data, scope) {
2488
- if (!!data) {
2513
+ if (data) {
2489
2514
  useAppStore.getState().actions.batchUpdateForPortfolio({
2490
2515
  totalCollateral: data.totalCollateral,
2491
2516
  totalValue: data.totalValue,
@@ -2630,8 +2655,12 @@ var OrderbookService = class _OrderbookService {
2630
2655
  }
2631
2656
  const askMap = /* @__PURE__ */ new Map();
2632
2657
  const bidMap = /* @__PURE__ */ new Map();
2633
- rawOrderBook.asks.forEach((ask) => askMap.set(ask[0], ask[1]));
2634
- rawOrderBook.bids.forEach((bid) => bidMap.set(bid[0], bid[1]));
2658
+ rawOrderBook.asks.forEach((ask) => {
2659
+ askMap.set(ask[0], ask[1]);
2660
+ });
2661
+ rawOrderBook.bids.forEach((bid) => {
2662
+ bidMap.set(bid[0], bid[1]);
2663
+ });
2635
2664
  update.asks.forEach(
2636
2665
  (ask) => ask[1] === 0 ? askMap.delete(ask[0]) : askMap.set(ask[0], ask[1])
2637
2666
  );
@@ -2647,9 +2676,9 @@ var OrderbookService = class _OrderbookService {
2647
2676
  rawOrderBook.ts = update.ts;
2648
2677
  }
2649
2678
  applyBufferedUpdatesToRawOrderBooks(symbol) {
2650
- this.bufferedOrderBookUpdates[symbol]?.forEach(
2651
- (update) => this.applyUpdateToRawOrderBook(symbol, update)
2652
- );
2679
+ this.bufferedOrderBookUpdates[symbol]?.forEach((update) => {
2680
+ this.applyUpdateToRawOrderBook(symbol, update);
2681
+ });
2653
2682
  }
2654
2683
  deleteBufferedOrderBookUpdates(symbol) {
2655
2684
  delete this.bufferedOrderBookUpdates[symbol];
@@ -2876,63 +2905,56 @@ var useTickerStream = (symbol) => {
2876
2905
  };
2877
2906
 
2878
2907
  // src/orderly/useOrderbookStream.ts
2879
- var paddingFn = (len) => Array(len).fill([
2880
- Number.NaN,
2881
- Number.NaN,
2882
- Number.NaN,
2883
- Number.NaN
2884
- ]);
2885
- var reduceItems = (depth, level, data, asks = false) => {
2908
+ var paddingFn = (len) => Array(len).fill([Number.NaN, Number.NaN, Number.NaN, Number.NaN]);
2909
+ var isNumber = (val) => {
2910
+ return typeof val === "number" && !Number.isNaN(val);
2911
+ };
2912
+ var getPriceKey = (rawPrice, depth, isAsks) => {
2913
+ return new Decimal(rawPrice).div(depth).toDecimalPlaces(0, isAsks ? Decimal.ROUND_CEIL : Decimal.ROUND_FLOOR).mul(depth).toNumber();
2914
+ };
2915
+ var reduceItems = (depth, data, isAsks) => {
2886
2916
  if (!Array.isArray(data) || data.length === 0) {
2887
2917
  return [];
2888
2918
  }
2889
2919
  let newData = [...data];
2890
2920
  const result = [];
2891
2921
  if (typeof depth !== "undefined") {
2892
- const prices = /* @__PURE__ */ new Map();
2893
- for (let i = 0; i < data.length; i++) {
2894
- const [price, quantity] = data[i];
2895
- if (isNaN(price) || isNaN(quantity))
2922
+ const pricesMap = /* @__PURE__ */ new Map();
2923
+ const len = data.length;
2924
+ for (let i = 0; i < len; i++) {
2925
+ const [rawPrice, quantity] = data[i];
2926
+ if (!isNumber(rawPrice) || !isNumber(quantity)) {
2896
2927
  continue;
2897
- let priceKey;
2898
- if (asks) {
2899
- priceKey = new Decimal(Math.ceil(price / depth)).mul(depth).toNumber();
2900
- } else {
2901
- priceKey = new Decimal(Math.floor(price / depth)).mul(depth).toNumber();
2902
- }
2903
- if (depth < 1 && depth > 0 && priceKey.toString().indexOf(".") !== -1) {
2904
- const priceStr = price.toString();
2905
- const index = priceStr.indexOf(".");
2906
- const decimal = priceStr.slice(index + 1);
2907
- const decimalDepth = removeTrailingZeros(depth).toString().slice(2).length;
2908
- const decimalStr = decimal.slice(0, min(decimal.length, decimalDepth));
2909
- priceKey = new Decimal(
2910
- priceStr.slice(0, index) + "." + decimalStr
2911
- ).toNumber();
2912
- }
2913
- if (prices.has(priceKey)) {
2914
- const item = prices.get(priceKey);
2915
- const itemPrice = new Decimal(item[1]).add(quantity).toNumber();
2916
- prices.set(priceKey, [priceKey, itemPrice]);
2928
+ }
2929
+ const priceKey = getPriceKey(rawPrice, depth, isAsks);
2930
+ const amtByRaw = new Decimal(rawPrice).mul(quantity).toNumber();
2931
+ if (pricesMap.has(priceKey)) {
2932
+ const item = pricesMap.get(priceKey);
2933
+ const sumQty = new Decimal(item[1]).add(quantity).toNumber();
2934
+ const sumAmtByRaw = new Decimal(item[2] ?? 0).add(amtByRaw).toNumber();
2935
+ pricesMap.set(priceKey, [priceKey, sumQty, sumAmtByRaw]);
2917
2936
  } else {
2918
- prices.set(priceKey, [priceKey, quantity]);
2937
+ pricesMap.set(priceKey, [priceKey, quantity, amtByRaw]);
2919
2938
  }
2920
2939
  }
2921
- newData = Array.from(prices.values());
2940
+ newData = Array.from(pricesMap.values());
2922
2941
  }
2923
2942
  for (let i = 0; i < newData.length; i++) {
2924
- const [price, quantity] = newData[i];
2925
- if (isNaN(price) || isNaN(quantity))
2943
+ const [price, quantity, sumAmtByRaw] = newData[i];
2944
+ if (!isNumber(price) || !isNumber(quantity)) {
2926
2945
  continue;
2927
- const newQuantity = new Decimal(quantity).add(result.length > 0 ? result[result.length - 1][2] : 0).toNumber();
2928
- const newAmount = new Decimal(quantity * price).add(result.length > 0 ? result[result.length - 1][3] : 0).toNumber();
2946
+ }
2947
+ const resLen = result.length;
2948
+ const newQuantity = new Decimal(quantity).add(resLen ? result[resLen - 1][2] : 0).toNumber();
2949
+ const pieceAmount = isNumber(sumAmtByRaw) ? sumAmtByRaw : new Decimal(quantity).mul(price).toNumber();
2950
+ const newAmount = new Decimal(pieceAmount).add(resLen ? result[resLen - 1][3] : 0).toNumber();
2929
2951
  result.push([price, quantity, newQuantity, newAmount]);
2930
2952
  }
2931
2953
  return result;
2932
2954
  };
2933
2955
  var reduceOrderbook = (depth, level, padding, data) => {
2934
- let asks = reduceItems(depth, level, data.asks, true);
2935
- let bids = reduceItems(depth, level, data.bids);
2956
+ let asks = reduceItems(depth, data.asks, true);
2957
+ let bids = reduceItems(depth, data.bids, false);
2936
2958
  if (asks.length !== 0 && bids.length !== 0 && asks[0][0] <= bids[0][0]) {
2937
2959
  if (asks.length === 1) {
2938
2960
  const [price, qty, newQuantity, newAmount] = asks[0];
@@ -2949,14 +2971,14 @@ var reduceOrderbook = (depth, level, padding, data) => {
2949
2971
  const [askPrice, askQty, newQuantity, newAmount] = asks[0];
2950
2972
  if (askPrice <= bidPrice) {
2951
2973
  asks.shift();
2952
- for (let index = 0; index < asks.length; index++) {
2953
- if (index === 0) {
2954
- const quantity = asks[index][1] + askQty;
2955
- asks[index][1] = quantity;
2956
- asks[index][2] = quantity;
2957
- asks[index][3] = Math.ceil(quantity) * asks[index][0];
2974
+ for (let i = 0; i < asks.length; i++) {
2975
+ if (i === 0) {
2976
+ const quantity = new Decimal(asks[i][1]).add(askQty);
2977
+ asks[i][1] = quantity.toNumber();
2978
+ asks[i][2] = quantity.toNumber();
2979
+ asks[i][3] = quantity.toDecimalPlaces(0, Decimal.ROUND_CEIL).mul(asks[i][0]).toNumber();
2958
2980
  } else {
2959
- asks[index][3] = asks[index][0] * asks[index][1] + asks[index - 1][3];
2981
+ asks[i][3] = new Decimal(asks[i][0]).mul(asks[i][1]).add(asks[i - 1][3]).toNumber();
2960
2982
  }
2961
2983
  }
2962
2984
  } else {
@@ -2975,6 +2997,7 @@ var reduceOrderbook = (depth, level, padding, data) => {
2975
2997
  bids
2976
2998
  };
2977
2999
  };
3000
+ var ORDERLY_ORDERBOOK_DEPTH_KEY = "orderly_orderbook_depth_key";
2978
3001
  var INIT_DATA = {
2979
3002
  asks: [],
2980
3003
  bids: []
@@ -2987,14 +3010,23 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
2987
3010
  const padding = options?.padding ?? true;
2988
3011
  const symbolRef = useRef(symbol);
2989
3012
  symbolRef.current = symbol;
2990
- const { defaultOrderbookTickSizes: DEFAULT_TICK_SIZES2 } = useContext(OrderlyContext);
3013
+ const {
3014
+ defaultOrderbookTickSizes: DEFAULT_TICK_SIZES2 = {},
3015
+ defaultOrderbookSymbolDepths: DEFAULT_SYMBOL_DEPTHS2 = {}
3016
+ } = useContext(OrderlyContext);
2991
3017
  const [data, setData] = useState(initial);
2992
3018
  const [isLoading, setIsLoading] = useState(true);
2993
3019
  const config = useSymbolsInfo()[symbol];
2994
- const [depth, setDepth] = useState();
3020
+ const [depthObject, setDepthObject] = useLocalStorage(
3021
+ ORDERLY_ORDERBOOK_DEPTH_KEY,
3022
+ {}
3023
+ );
2995
3024
  const prevMiddlePrice = useRef(0);
3025
+ const tick = config("quote_tick");
2996
3026
  const depths = useMemo(() => {
2997
- const tick = config("quote_tick");
3027
+ if (DEFAULT_SYMBOL_DEPTHS2[symbol]) {
3028
+ return DEFAULT_SYMBOL_DEPTHS2[symbol];
3029
+ }
2998
3030
  if (typeof tick === "undefined") {
2999
3031
  return [];
3000
3032
  }
@@ -3006,26 +3038,40 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
3006
3038
  base.mul(100).toNumber(),
3007
3039
  base.mul(1e3).toNumber()
3008
3040
  ];
3009
- } catch (e) {
3041
+ } catch {
3010
3042
  }
3011
3043
  return [tick];
3012
- }, [config("quote_tick")]);
3044
+ }, [symbol, tick]);
3013
3045
  useEffect(() => {
3046
+ if (depthObject[symbol]) {
3047
+ return;
3048
+ }
3014
3049
  if (DEFAULT_TICK_SIZES2[symbol]) {
3015
- setDepth(Number(DEFAULT_TICK_SIZES2[symbol]));
3050
+ setDepthObject((prev) => ({
3051
+ ...prev,
3052
+ [symbol]: Number(DEFAULT_TICK_SIZES2[symbol])
3053
+ }));
3016
3054
  } else {
3017
- setDepth(config("quote_tick"));
3055
+ setDepthObject((prev) => ({
3056
+ ...prev,
3057
+ [symbol]: tick
3058
+ }));
3018
3059
  }
3019
- }, [config("quote_tick"), symbol, DEFAULT_TICK_SIZES2]);
3060
+ }, [depthObject, tick, symbol, DEFAULT_TICK_SIZES2]);
3061
+ const onDepthChange = useCallback(
3062
+ (val) => {
3063
+ setDepthObject((prev) => ({ ...prev, [symbol]: val }));
3064
+ },
3065
+ [symbol]
3066
+ );
3020
3067
  const ws = useWS();
3021
3068
  const ticker = useTickerStream(symbol);
3022
3069
  const eventEmitter = useEventEmitter();
3023
3070
  useEffect(() => {
3024
3071
  let needRequestFullOrderbook = true;
3025
3072
  setIsLoading(true);
3026
- let orderBookUpdateSub;
3027
3073
  let fullOrderBookUpdateSub;
3028
- orderBookUpdateSub = ws.subscribe(
3074
+ const orderBookUpdateSub = ws.subscribe(
3029
3075
  {
3030
3076
  event: "subscribe",
3031
3077
  topic: `${symbol}@orderbookupdate`
@@ -3042,7 +3088,9 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
3042
3088
  orderbook_service_default.updateOrderbook(
3043
3089
  symbol2,
3044
3090
  { asks, bids, ts, prevTs },
3045
- () => needRequestFullOrderbook = true
3091
+ () => {
3092
+ needRequestFullOrderbook = true;
3093
+ }
3046
3094
  );
3047
3095
  const data2 = orderbook_service_default.getRawOrderbook(symbol2);
3048
3096
  setData({ bids: data2.bids, asks: data2.asks });
@@ -3087,25 +3135,23 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
3087
3135
  const onItemClick = useCallback((item) => {
3088
3136
  eventEmitter.emit("orderbook:item:click", item);
3089
3137
  }, []);
3090
- const onDepthChange = useCallback((depth2) => {
3091
- setDepth(() => depth2);
3092
- }, []);
3093
- const reducedData = reduceOrderbook(depth, level, padding, {
3094
- asks: [...data.asks],
3095
- bids: [...data.bids]
3138
+ const reducedData = reduceOrderbook(depthObject[symbol], level, padding, {
3139
+ asks: data.asks,
3140
+ bids: data.bids
3096
3141
  });
3097
3142
  useEffect(() => {
3098
3143
  eventEmitter.emit("orderbook:update", reducedData);
3099
3144
  }, [reducedData]);
3100
3145
  const middlePrice = useMemo(() => {
3101
- let asksFrist = 0, bidsFirst = 0;
3146
+ let asksFrist = 0;
3147
+ let bidsFirst = 0;
3102
3148
  if (data.asks.length > 0) {
3103
3149
  asksFrist = reducedData.asks?.[reducedData.asks.length - 1]?.[0];
3104
3150
  }
3105
3151
  if (data.bids.length > 0) {
3106
3152
  bidsFirst = data.bids[0][0];
3107
3153
  }
3108
- if (isNaN(asksFrist) || isNaN(bidsFirst) || !ticker) {
3154
+ if (!isNumber(asksFrist) || !isNumber(bidsFirst) || !ticker) {
3109
3155
  return 0;
3110
3156
  }
3111
3157
  return [asksFrist, bidsFirst, ticker["24h_close"]].sort()[1];
@@ -3120,7 +3166,13 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
3120
3166
  markPrice,
3121
3167
  middlePrice: [prevMiddlePrice.current, middlePrice]
3122
3168
  },
3123
- { onDepthChange, depth, allDepths: depths, isLoading, onItemClick }
3169
+ {
3170
+ onDepthChange,
3171
+ depth: depthObject[symbol],
3172
+ allDepths: depths,
3173
+ isLoading,
3174
+ onItemClick
3175
+ }
3124
3176
  ];
3125
3177
  };
3126
3178
 
@@ -3138,6 +3190,8 @@ var useFundingRatesStore = () => {
3138
3190
  const data = useAppStore((state) => state.fundingRates);
3139
3191
  return data;
3140
3192
  };
3193
+
3194
+ // src/orderly/useMarket.ts
3141
3195
  var DefaultTab = { name: "Popular", id: 1 };
3142
3196
  var marketsKey = "markets";
3143
3197
  var useMarket = (type) => {
@@ -3177,12 +3231,13 @@ var useMarket = (type) => {
3177
3231
  const curData = getStore("favorites", []);
3178
3232
  const tabs = getFavoriteTabs;
3179
3233
  const result = [];
3180
- for (let index = 0; index < curData.length; index++) {
3234
+ const len = curData.length;
3235
+ for (let index = 0; index < len; index++) {
3181
3236
  const favData = curData[index];
3182
- var favTabs = favData.tabs.filter(
3237
+ const favTabs = favData.tabs.filter(
3183
3238
  (tab) => tabs.findIndex((item) => tab.id === item.id) !== -1
3184
3239
  );
3185
- if (favTabs.length > 0) {
3240
+ if (favTabs.length) {
3186
3241
  result.push({ ...favData, tabs: favTabs });
3187
3242
  }
3188
3243
  }
@@ -3206,7 +3261,7 @@ var useMarket = (type) => {
3206
3261
  saveTabs(tab);
3207
3262
  return;
3208
3263
  }
3209
- var tabs = [...favoriteTabs];
3264
+ const tabs = [...favoriteTabs];
3210
3265
  const index = tabs.findIndex((item) => item.id === tab.id);
3211
3266
  if (operator?.add) {
3212
3267
  tabs.push(tab);
@@ -3349,7 +3404,7 @@ var useMarket = (type) => {
3349
3404
  };
3350
3405
  const markets = getData(type);
3351
3406
  return [
3352
- markets || [],
3407
+ markets || EMPTY_LIST,
3353
3408
  {
3354
3409
  favoriteTabs,
3355
3410
  favorites,
@@ -3405,13 +3460,13 @@ var useIndexPricesStream = () => {
3405
3460
  getIndexPrice: useMemoizedFn(getIndexPrice)
3406
3461
  };
3407
3462
  };
3408
- var generateLeverageLevers = (max3) => {
3409
- const min3 = 1;
3463
+ var generateLeverageLevers = (max2) => {
3464
+ const min2 = 1;
3410
3465
  const parts = 5;
3411
- const step = (max3 - min3) / (parts - 1);
3466
+ const step = (max2 - min2) / (parts - 1);
3412
3467
  const result = [];
3413
3468
  for (let i = 0; i < parts; i++) {
3414
- result.push(Math.floor(min3 + step * i));
3469
+ result.push(Math.floor(min2 + step * i));
3415
3470
  }
3416
3471
  return result;
3417
3472
  };
@@ -5733,12 +5788,12 @@ var OrderValidation = class {
5733
5788
  value
5734
5789
  };
5735
5790
  }
5736
- static range(key, min3, max3) {
5791
+ static range(key, min2, max2) {
5737
5792
  return {
5738
5793
  type: "range",
5739
- message: `${this.getLabel(key)} must be in the range of ${min3} to ${max3}`,
5740
- min: min3,
5741
- max: max3
5794
+ message: `${this.getLabel(key)} must be in the range of ${min2} to ${max2}`,
5795
+ min: min2,
5796
+ max: max2
5742
5797
  };
5743
5798
  }
5744
5799
  };
@@ -5994,81 +6049,6 @@ var BBOOrderCreator = class extends BaseOrderCreator {
5994
6049
  });
5995
6050
  }
5996
6051
  };
5997
- var { maxPrice, minPrice, scopePrice } = order;
5998
- var LimitOrderCreator = class extends BaseOrderCreator {
5999
- constructor() {
6000
- super(...arguments);
6001
- this.orderType = OrderType.LIMIT;
6002
- }
6003
- create(values2, config) {
6004
- const order = {
6005
- ...this.baseOrder(values2),
6006
- order_price: values2.order_price
6007
- };
6008
- this.totalToQuantity(order, config);
6009
- return pick(
6010
- [
6011
- "symbol",
6012
- "order_price",
6013
- "order_quantity",
6014
- "visible_quantity",
6015
- "reduce_only",
6016
- "side",
6017
- "order_type",
6018
- "algo_type",
6019
- "child_orders"
6020
- ],
6021
- order
6022
- );
6023
- }
6024
- validate(values2, config) {
6025
- return this.baseValidate(values2, config).then((errors) => {
6026
- const { order_price, side } = values2;
6027
- if (!order_price) {
6028
- errors.order_price = OrderValidation.required("order_price");
6029
- } else {
6030
- const price = new Decimal(order_price);
6031
- const { symbol } = config;
6032
- const { price_range, price_scope, quote_max, quote_min } = symbol;
6033
- const maxPriceNumber = maxPrice(config.markPrice, price_range);
6034
- const minPriceNumber = minPrice(config.markPrice, price_range);
6035
- const scopePriceNumber = scopePrice(
6036
- config.markPrice,
6037
- price_scope,
6038
- side
6039
- );
6040
- const priceRange = side === "BUY" ? {
6041
- min: scopePriceNumber,
6042
- max: maxPriceNumber
6043
- } : {
6044
- min: minPriceNumber,
6045
- max: scopePriceNumber
6046
- };
6047
- if (price.gt(quote_max)) {
6048
- errors.order_price = OrderValidation.max("order_price", quote_max);
6049
- } else {
6050
- if (price.gt(priceRange?.max)) {
6051
- errors.order_price = OrderValidation.max(
6052
- "order_price",
6053
- new Decimal(priceRange.max).todp(symbol.quote_dp).toString()
6054
- );
6055
- }
6056
- }
6057
- if (price.lt(quote_min)) {
6058
- errors.order_price = OrderValidation.min("order_price", quote_min);
6059
- } else {
6060
- if (price.lt(priceRange?.min)) {
6061
- errors.order_price = OrderValidation.min(
6062
- "order_price",
6063
- new Decimal(priceRange.min).todp(symbol.quote_dp).toString()
6064
- );
6065
- }
6066
- }
6067
- }
6068
- return errors;
6069
- });
6070
- }
6071
- };
6072
6052
  function getOrderPrice(order, askAndBid) {
6073
6053
  const orderPrice = Number(order.order_price);
6074
6054
  if (order.order_type === OrderType.MARKET || order.order_type === OrderType.STOP_MARKET) {
@@ -6301,6 +6281,81 @@ async function bracketOrderValidator(values2, config) {
6301
6281
  }
6302
6282
  return Object.keys(result).length > 0 ? result : null;
6303
6283
  }
6284
+ var { maxPrice, minPrice, scopePrice } = order;
6285
+ var LimitOrderCreator = class extends BaseOrderCreator {
6286
+ constructor() {
6287
+ super(...arguments);
6288
+ this.orderType = OrderType.LIMIT;
6289
+ }
6290
+ create(values2, config) {
6291
+ const order = {
6292
+ ...this.baseOrder(values2),
6293
+ order_price: values2.order_price
6294
+ };
6295
+ this.totalToQuantity(order, config);
6296
+ return pick(
6297
+ [
6298
+ "symbol",
6299
+ "order_price",
6300
+ "order_quantity",
6301
+ "visible_quantity",
6302
+ "reduce_only",
6303
+ "side",
6304
+ "order_type",
6305
+ "algo_type",
6306
+ "child_orders"
6307
+ ],
6308
+ order
6309
+ );
6310
+ }
6311
+ validate(values2, config) {
6312
+ return this.baseValidate(values2, config).then((errors) => {
6313
+ const { order_price, side } = values2;
6314
+ if (!order_price) {
6315
+ errors.order_price = OrderValidation.required("order_price");
6316
+ } else {
6317
+ const price = new Decimal(order_price);
6318
+ const { symbol } = config;
6319
+ const { price_range, price_scope, quote_max, quote_min } = symbol;
6320
+ const maxPriceNumber = maxPrice(config.markPrice, price_range);
6321
+ const minPriceNumber = minPrice(config.markPrice, price_range);
6322
+ const scopePriceNumber = scopePrice(
6323
+ config.markPrice,
6324
+ price_scope,
6325
+ side
6326
+ );
6327
+ const priceRange = side === "BUY" ? {
6328
+ min: scopePriceNumber,
6329
+ max: maxPriceNumber
6330
+ } : {
6331
+ min: minPriceNumber,
6332
+ max: scopePriceNumber
6333
+ };
6334
+ if (price.gt(quote_max)) {
6335
+ errors.order_price = OrderValidation.max("order_price", quote_max);
6336
+ } else {
6337
+ if (price.gt(priceRange?.max)) {
6338
+ errors.order_price = OrderValidation.max(
6339
+ "order_price",
6340
+ new Decimal(priceRange.max).todp(symbol.quote_dp).toString()
6341
+ );
6342
+ }
6343
+ }
6344
+ if (price.lt(quote_min)) {
6345
+ errors.order_price = OrderValidation.min("order_price", quote_min);
6346
+ } else {
6347
+ if (price.lt(priceRange?.min)) {
6348
+ errors.order_price = OrderValidation.min(
6349
+ "order_price",
6350
+ new Decimal(priceRange.min).todp(symbol.quote_dp).toString()
6351
+ );
6352
+ }
6353
+ }
6354
+ }
6355
+ return errors;
6356
+ });
6357
+ }
6358
+ };
6304
6359
 
6305
6360
  // src/services/orderCreator/bracketLimitOrderCreator.ts
6306
6361
  var BracketLimitOrderCreator = class extends LimitOrderCreator {
@@ -6444,7 +6499,7 @@ function calcScaledOrderWeights(inputs) {
6444
6499
  }
6445
6500
  const sumWeights = weights.reduce((acc, cur) => acc.plus(cur), zero);
6446
6501
  const minWeight = weights.reduce(
6447
- (min3, current) => current.lt(min3) ? current : min3,
6502
+ (min2, current) => current.lt(min2) ? current : min2,
6448
6503
  weights?.[0]
6449
6504
  );
6450
6505
  return {
@@ -6594,7 +6649,7 @@ function calcScaledOrderMinTotalAmountByMinNotional(order, symbolInfo, askAndBid
6594
6649
  return new Decimal(min_notional).mul(sumWeights).div(new Decimal(weights[i]).mul(orderPrice));
6595
6650
  });
6596
6651
  const max_minQty = minQtys.reduce(
6597
- (max3, current) => current.gt(max3) ? current : max3,
6652
+ (max2, current) => current.gt(max2) ? current : max2,
6598
6653
  minQtys?.[0]
6599
6654
  );
6600
6655
  return max_minQty.todp(base_dp, Decimal.ROUND_UP).toNumber();
@@ -7302,6 +7357,152 @@ var OrderFactory = class {
7302
7357
  }
7303
7358
  }
7304
7359
  };
7360
+
7361
+ // src/next/useOrderEntry/helper.ts
7362
+ var getCreateOrderUrl = (order) => {
7363
+ const isAlgoOrder = order?.order_type === OrderType.STOP_LIMIT || order?.order_type === OrderType.STOP_MARKET || order?.order_type === OrderType.CLOSE_POSITION || order.algo_type && order.algo_type === AlgoOrderRootType.BRACKET || isBracketOrder(order);
7364
+ if (order.order_type === OrderType.SCALED) {
7365
+ return "/v1/batch-order";
7366
+ }
7367
+ return isAlgoOrder ? "/v1/algo/order" : "/v1/order";
7368
+ };
7369
+ var getOrderCreator = (order) => {
7370
+ let type;
7371
+ if (isBracketOrder(order)) {
7372
+ type = `${AlgoOrderRootType.BRACKET}:${order.order_type}`;
7373
+ } else if (order.order_type === OrderType.LIMIT) {
7374
+ type = order.order_type_ext || order.order_type;
7375
+ } else {
7376
+ type = order.order_type;
7377
+ }
7378
+ return OrderFactory.create(type);
7379
+ };
7380
+ var tpslFields = [
7381
+ "tp_trigger_price",
7382
+ "sl_trigger_price",
7383
+ "tp_pnl",
7384
+ "sl_pnl",
7385
+ "tp_offset",
7386
+ "sl_offset",
7387
+ "tp_offset_percentage",
7388
+ "sl_offset_percentage"
7389
+ ];
7390
+ var isBracketOrder = (order) => {
7391
+ if (order.sl_enable || order.tp_enable) {
7392
+ return true;
7393
+ }
7394
+ return !!order.tp_trigger_price || !!order.sl_trigger_price;
7395
+ };
7396
+ var hasTPSL = (order) => {
7397
+ return tpslFields.some((field) => !!order[field]);
7398
+ };
7399
+ var getPriceAndQty = (order, symbolInfo, askAndBid) => {
7400
+ let quantity = Number(order.order_quantity);
7401
+ const orderPrice = Number(order.order_price);
7402
+ if (isNaN(quantity) || quantity <= 0) {
7403
+ return null;
7404
+ }
7405
+ if (askAndBid.length === 0) {
7406
+ return null;
7407
+ }
7408
+ if ((order.order_type === OrderType.LIMIT || order.order_type === OrderType.STOP_LIMIT) && isNaN(orderPrice)) {
7409
+ return null;
7410
+ }
7411
+ let price;
7412
+ if (order.order_type === OrderType.SCALED) {
7413
+ price = calcScaledOrderAvgPrice(order, symbolInfo, askAndBid);
7414
+ const orders = calcScaledOrderBatchBody(order, symbolInfo);
7415
+ const sumQtys = orders.reduce((acc, order2) => {
7416
+ return acc.plus(new Decimal(order2.order_quantity));
7417
+ }, zero);
7418
+ quantity = sumQtys.todp(symbolInfo.base_dp).toNumber();
7419
+ if (!quantity || isNaN(quantity)) {
7420
+ return null;
7421
+ }
7422
+ } else {
7423
+ price = getOrderPrice(order, askAndBid);
7424
+ }
7425
+ if (!price || isNaN(price)) {
7426
+ return null;
7427
+ }
7428
+ if (order.side === OrderSide.SELL) {
7429
+ quantity = -quantity;
7430
+ }
7431
+ return { price, quantity };
7432
+ };
7433
+ var calcEstLiqPrice = (order$1, askAndBid, inputs) => {
7434
+ const { symbolInfo } = inputs;
7435
+ const result = getPriceAndQty(order$1, symbolInfo, askAndBid);
7436
+ if (!result)
7437
+ return null;
7438
+ const { price, quantity } = result;
7439
+ if (!price || !quantity)
7440
+ return null;
7441
+ const {
7442
+ symbol,
7443
+ imr_factor,
7444
+ markPrice,
7445
+ totalCollateral,
7446
+ futures_taker_fee_rate,
7447
+ positions: positions3
7448
+ } = inputs;
7449
+ const orderFee = order.orderFee({
7450
+ qty: quantity,
7451
+ price,
7452
+ futuresTakeFeeRate: Number(futures_taker_fee_rate) / 1e4
7453
+ });
7454
+ const liqPrice = order.estLiqPrice({
7455
+ markPrice,
7456
+ baseIMR: symbolInfo.base_imr,
7457
+ baseMMR: symbolInfo.base_mmr,
7458
+ totalCollateral,
7459
+ positions: positions3 == null ? [] : positions3,
7460
+ IMR_Factor: imr_factor,
7461
+ orderFee,
7462
+ newOrder: {
7463
+ qty: quantity,
7464
+ price,
7465
+ symbol
7466
+ }
7467
+ });
7468
+ if (liqPrice <= 0)
7469
+ return null;
7470
+ return liqPrice;
7471
+ };
7472
+ var calcEstLeverage = (order$1, askAndBid, inputs) => {
7473
+ const { totalCollateral, positions: positions3, symbol, symbolInfo } = inputs;
7474
+ const result = getPriceAndQty(order$1, symbolInfo, askAndBid);
7475
+ if (!result)
7476
+ return null;
7477
+ const { price, quantity } = result;
7478
+ if (!price || !quantity)
7479
+ return null;
7480
+ return order.estLeverage({
7481
+ totalCollateral,
7482
+ positions: positions3,
7483
+ newOrder: {
7484
+ symbol,
7485
+ qty: result.quantity,
7486
+ price: result.price
7487
+ }
7488
+ });
7489
+ };
7490
+ function isBBOOrder(options) {
7491
+ const { order_type, order_type_ext } = options;
7492
+ return order_type === OrderType.LIMIT && [OrderType.ASK, OrderType.BID].includes(order_type_ext);
7493
+ }
7494
+ function appendOrderMetadata(order, orderMetadata) {
7495
+ if (Array.isArray(order)) {
7496
+ return order.map((item) => ({
7497
+ ...item,
7498
+ ...typeof orderMetadata === "function" ? orderMetadata(item) : orderMetadata
7499
+ }));
7500
+ }
7501
+ return {
7502
+ ...order,
7503
+ ...typeof orderMetadata === "function" ? orderMetadata(order) : orderMetadata
7504
+ };
7505
+ }
7305
7506
  function useSubAccountQuery(query, options) {
7306
7507
  const { formatter, accountId, ...swrOptions } = options || {};
7307
7508
  const { state, account: account9 } = useAccount();
@@ -8141,6 +8342,13 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
8141
8342
  const [doUpdateOrder, { isMutating: isUpdateMutating }] = useSubAccountMutation("/v1/algo/order", "PUT");
8142
8343
  const [doDeleteOrder] = useMutation("/v1/algo/order", "DELETE");
8143
8344
  const [errors, setErrors] = useState(null);
8345
+ const [meta, setMeta] = useState({
8346
+ dirty: {},
8347
+ submitted: false,
8348
+ validated: false,
8349
+ errors: null
8350
+ });
8351
+ const { orderMetadata } = useOrderlyContext();
8144
8352
  useEffect(() => {
8145
8353
  if (!isEditing || !options?.defaultOrder)
8146
8354
  return;
@@ -8179,6 +8387,14 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
8179
8387
  symbol: symbolInfo
8180
8388
  }
8181
8389
  );
8390
+ const newValueAll = {
8391
+ ...prev,
8392
+ ...newValue,
8393
+ ignoreValidate: options2?.ignoreValidate
8394
+ };
8395
+ interactiveValidate(
8396
+ newValueAll
8397
+ );
8182
8398
  return {
8183
8399
  ...prev,
8184
8400
  ...newValue,
@@ -8219,19 +8435,28 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
8219
8435
  maxQty: Math.abs(position.position_qty),
8220
8436
  markPrice
8221
8437
  };
8222
- useEffect(() => {
8223
- requestAnimationFrame(() => {
8224
- if (order.ignoreValidate)
8225
- return;
8226
- if (!order.quantity) {
8227
- return;
8438
+ const interactiveValidate = (order2) => {
8439
+ validateFunc(order2).then((errors2) => {
8440
+ const keys = Object.keys(errors2 ?? {});
8441
+ if (keys.length > 0) {
8442
+ setMeta(
8443
+ produce((draft) => {
8444
+ draft.errors = errors2;
8445
+ })
8446
+ );
8447
+ } else {
8448
+ setMeta(
8449
+ produce((draft) => {
8450
+ draft.errors = null;
8451
+ })
8452
+ );
8228
8453
  }
8229
- const orderCreator = getOrderCreator2();
8230
- orderCreator.validate(order, valueConfig).then((errors2) => {
8231
- setErrors(errors2);
8232
- });
8233
8454
  });
8234
- }, [order, valueConfig.markPrice, order.quantity]);
8455
+ };
8456
+ const validateFunc = async (order2) => {
8457
+ const creator = getOrderCreator2();
8458
+ return creator.validate(order2, valueConfig);
8459
+ };
8235
8460
  const setValues = (values2) => {
8236
8461
  const keys = Object.keys(values2);
8237
8462
  keys.forEach((key) => {
@@ -8249,6 +8474,21 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
8249
8474
  valueConfig
8250
8475
  ).then((errors2) => {
8251
8476
  if (errors2) {
8477
+ const keys = Object.keys(errors2);
8478
+ if (keys.length > 0) {
8479
+ setMeta(
8480
+ produce((draft) => {
8481
+ draft.errors = errors2;
8482
+ })
8483
+ );
8484
+ if (!meta.validated) {
8485
+ setMeta(
8486
+ produce((draft) => {
8487
+ draft.validated = true;
8488
+ })
8489
+ );
8490
+ }
8491
+ }
8252
8492
  setErrors(errors2);
8253
8493
  return reject(errors2);
8254
8494
  }
@@ -8302,7 +8542,8 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
8302
8542
  orderBody.child_orders = orderBody.child_orders.filter(
8303
8543
  (order2) => order2.is_activated
8304
8544
  );
8305
- return doCreateOrder(orderBody, {}, params);
8545
+ const body = appendOrderMetadata(orderBody, orderMetadata);
8546
+ return doCreateOrder(body, {}, params);
8306
8547
  };
8307
8548
  const deleteOrder = (orderId, symbol) => {
8308
8549
  return doDeleteOrder(null, {
@@ -8348,6 +8589,7 @@ var useTaskProfitAndStopLossInternal = (position, options) => {
8348
8589
  // createPositionTPSL: submit,
8349
8590
  // createTPSL: submit,
8350
8591
  validate,
8592
+ metaState: meta,
8351
8593
  errors,
8352
8594
  isCreateMutating,
8353
8595
  isUpdateMutating
@@ -9125,7 +9367,12 @@ var OrderlyConfigProvider = (props) => {
9125
9367
  enableSwapDeposit = false,
9126
9368
  chainTransformer,
9127
9369
  dataAdapter,
9128
- notification
9370
+ notification,
9371
+ amplitudeConfig,
9372
+ orderbookDefaultTickSizes,
9373
+ orderbookDefaultSymbolDepths,
9374
+ children,
9375
+ orderMetadata
9129
9376
  } = props;
9130
9377
  if (typeof configStore !== "undefined" && !configStore.get("brokerId")) {
9131
9378
  throw new SDKError(
@@ -9139,7 +9386,11 @@ var OrderlyConfigProvider = (props) => {
9139
9386
  }
9140
9387
  const innerConfigStore = useMemo(() => {
9141
9388
  return new ProxyConfigStore(
9142
- configStore || new ExtendedConfigStore({ brokerId, brokerName, networkId })
9389
+ configStore || new ExtendedConfigStore({
9390
+ brokerId,
9391
+ brokerName,
9392
+ networkId
9393
+ })
9143
9394
  );
9144
9395
  }, [configStore, brokerId, brokerName, networkId]);
9145
9396
  const innerKeyStore = useMemo(() => {
@@ -9152,8 +9403,11 @@ var OrderlyConfigProvider = (props) => {
9152
9403
  ];
9153
9404
  }, [walletAdapters]);
9154
9405
  const defaultOrderbookTickSizes = useMemo(() => {
9155
- return props.orderbookDefaultTickSizes || DEFAULT_TICK_SIZES;
9156
- }, [props.orderbookDefaultTickSizes]);
9406
+ return orderbookDefaultTickSizes || DEFAULT_TICK_SIZES;
9407
+ }, [orderbookDefaultTickSizes]);
9408
+ const defaultOrderbookSymbolDepths = useMemo(() => {
9409
+ return orderbookDefaultSymbolDepths || DEFAULT_SYMBOL_DEPTHS;
9410
+ }, [orderbookDefaultSymbolDepths]);
9157
9411
  useLayoutEffect(() => {
9158
9412
  let account10 = SimpleDI.get(Account.instanceName);
9159
9413
  if (!account10) {
@@ -9175,7 +9429,7 @@ var OrderlyConfigProvider = (props) => {
9175
9429
  return chainFilter(innerConfigStore);
9176
9430
  }
9177
9431
  return chainFilter;
9178
- }, [props.chainFilter, innerConfigStore]);
9432
+ }, [chainFilter, innerConfigStore]);
9179
9433
  const memoizedValue = useMemo(() => {
9180
9434
  return {
9181
9435
  configStore: innerConfigStore,
@@ -9186,9 +9440,12 @@ var OrderlyConfigProvider = (props) => {
9186
9440
  customChains,
9187
9441
  enableSwapDeposit,
9188
9442
  defaultOrderbookTickSizes,
9443
+ defaultOrderbookSymbolDepths,
9189
9444
  chainTransformer,
9190
9445
  dataAdapter,
9191
- notification
9446
+ notification,
9447
+ amplitudeConfig,
9448
+ orderMetadata
9192
9449
  };
9193
9450
  }, [
9194
9451
  innerConfigStore,
@@ -9199,14 +9456,17 @@ var OrderlyConfigProvider = (props) => {
9199
9456
  customChains,
9200
9457
  enableSwapDeposit,
9201
9458
  defaultOrderbookTickSizes,
9459
+ defaultOrderbookSymbolDepths,
9202
9460
  dataAdapter,
9203
9461
  notification,
9204
- chainTransformer
9462
+ chainTransformer,
9463
+ amplitudeConfig,
9464
+ orderMetadata
9205
9465
  ]);
9206
9466
  if (!account9) {
9207
9467
  return null;
9208
9468
  }
9209
- return /* @__PURE__ */ jsx(OrderlyProvider, { value: memoizedValue, children: /* @__PURE__ */ jsx(StatusProvider, { children: /* @__PURE__ */ jsx(DataCenterProvider, { children: props.children }) }) });
9469
+ return /* @__PURE__ */ jsx(OrderlyProvider, { value: memoizedValue, children: /* @__PURE__ */ jsx(StatusProvider, { children: /* @__PURE__ */ jsx(DataCenterProvider, { children }) }) });
9210
9470
  };
9211
9471
  var needNumberOnlyFields = [
9212
9472
  "order_quantity",
@@ -16162,138 +16422,6 @@ function getQueryParamsFromObject(obj) {
16162
16422
  }
16163
16423
  return queryParams.toString();
16164
16424
  }
16165
- var getCreateOrderUrl = (order) => {
16166
- const isAlgoOrder = order?.order_type === OrderType.STOP_LIMIT || order?.order_type === OrderType.STOP_MARKET || order?.order_type === OrderType.CLOSE_POSITION || order.algo_type && order.algo_type === AlgoOrderRootType.BRACKET || isBracketOrder(order);
16167
- if (order.order_type === OrderType.SCALED) {
16168
- return "/v1/batch-order";
16169
- }
16170
- return isAlgoOrder ? "/v1/algo/order" : "/v1/order";
16171
- };
16172
- var getOrderCreator = (order) => {
16173
- let type;
16174
- if (isBracketOrder(order)) {
16175
- type = `${AlgoOrderRootType.BRACKET}:${order.order_type}`;
16176
- } else if (order.order_type === OrderType.LIMIT) {
16177
- type = order.order_type_ext || order.order_type;
16178
- } else {
16179
- type = order.order_type;
16180
- }
16181
- return OrderFactory.create(type);
16182
- };
16183
- var tpslFields = [
16184
- "tp_trigger_price",
16185
- "sl_trigger_price",
16186
- "tp_pnl",
16187
- "sl_pnl",
16188
- "tp_offset",
16189
- "sl_offset",
16190
- "tp_offset_percentage",
16191
- "sl_offset_percentage"
16192
- ];
16193
- var isBracketOrder = (order) => {
16194
- if (order.sl_enable || order.tp_enable) {
16195
- return true;
16196
- }
16197
- return !!order.tp_trigger_price || !!order.sl_trigger_price;
16198
- };
16199
- var hasTPSL = (order) => {
16200
- return tpslFields.some((field) => !!order[field]);
16201
- };
16202
- var getPriceAndQty = (order, symbolInfo, askAndBid) => {
16203
- let quantity = Number(order.order_quantity);
16204
- const orderPrice = Number(order.order_price);
16205
- if (isNaN(quantity) || quantity <= 0) {
16206
- return null;
16207
- }
16208
- if (askAndBid.length === 0) {
16209
- return null;
16210
- }
16211
- if ((order.order_type === OrderType.LIMIT || order.order_type === OrderType.STOP_LIMIT) && isNaN(orderPrice)) {
16212
- return null;
16213
- }
16214
- let price;
16215
- if (order.order_type === OrderType.SCALED) {
16216
- price = calcScaledOrderAvgPrice(order, symbolInfo, askAndBid);
16217
- const orders = calcScaledOrderBatchBody(order, symbolInfo);
16218
- const sumQtys = orders.reduce((acc, order2) => {
16219
- return acc.plus(new Decimal(order2.order_quantity));
16220
- }, zero);
16221
- quantity = sumQtys.todp(symbolInfo.base_dp).toNumber();
16222
- if (!quantity || isNaN(quantity)) {
16223
- return null;
16224
- }
16225
- } else {
16226
- price = getOrderPrice(order, askAndBid);
16227
- }
16228
- if (!price || isNaN(price)) {
16229
- return null;
16230
- }
16231
- if (order.side === OrderSide.SELL) {
16232
- quantity = -quantity;
16233
- }
16234
- return { price, quantity };
16235
- };
16236
- var calcEstLiqPrice = (order$1, askAndBid, inputs) => {
16237
- const { symbolInfo } = inputs;
16238
- const result = getPriceAndQty(order$1, symbolInfo, askAndBid);
16239
- if (!result)
16240
- return null;
16241
- const { price, quantity } = result;
16242
- if (!price || !quantity)
16243
- return null;
16244
- const {
16245
- symbol,
16246
- imr_factor,
16247
- markPrice,
16248
- totalCollateral,
16249
- futures_taker_fee_rate,
16250
- positions: positions3
16251
- } = inputs;
16252
- const orderFee = order.orderFee({
16253
- qty: quantity,
16254
- price,
16255
- futuresTakeFeeRate: Number(futures_taker_fee_rate) / 1e4
16256
- });
16257
- const liqPrice = order.estLiqPrice({
16258
- markPrice,
16259
- baseIMR: symbolInfo.base_imr,
16260
- baseMMR: symbolInfo.base_mmr,
16261
- totalCollateral,
16262
- positions: positions3 == null ? [] : positions3,
16263
- IMR_Factor: imr_factor,
16264
- orderFee,
16265
- newOrder: {
16266
- qty: quantity,
16267
- price,
16268
- symbol
16269
- }
16270
- });
16271
- if (liqPrice <= 0)
16272
- return null;
16273
- return liqPrice;
16274
- };
16275
- var calcEstLeverage = (order$1, askAndBid, inputs) => {
16276
- const { totalCollateral, positions: positions3, symbol, symbolInfo } = inputs;
16277
- const result = getPriceAndQty(order$1, symbolInfo, askAndBid);
16278
- if (!result)
16279
- return null;
16280
- const { price, quantity } = result;
16281
- if (!price || !quantity)
16282
- return null;
16283
- return order.estLeverage({
16284
- totalCollateral,
16285
- positions: positions3,
16286
- newOrder: {
16287
- symbol,
16288
- qty: result.quantity,
16289
- price: result.price
16290
- }
16291
- });
16292
- };
16293
- function isBBOOrder(options) {
16294
- const { order_type, order_type_ext } = options;
16295
- return order_type === OrderType.LIMIT && [OrderType.ASK, OrderType.BID].includes(order_type_ext);
16296
- }
16297
16425
  var initialOrderState = {
16298
16426
  order_price: "",
16299
16427
  order_quantity: "",
@@ -16606,6 +16734,7 @@ var useOrderEntry2 = (symbol, options = {}) => {
16606
16734
  const positions3 = usePositions();
16607
16735
  const symbolInfo = symbolConfig[symbol]();
16608
16736
  const markPrice = actions.getMarkPriceBySymbol(symbol);
16737
+ const { orderMetadata } = useOrderlyContext();
16609
16738
  const {
16610
16739
  formattedOrder,
16611
16740
  setValue: setValueInternal,
@@ -16921,7 +17050,9 @@ var useOrderEntry2 = (symbol, options = {}) => {
16921
17050
  }
16922
17051
  const order = generateOrder(creator, prepareData());
16923
17052
  const isScaledOrder = order.order_type === OrderType.SCALED;
16924
- const params = isScaledOrder ? { orders: order.orders } : order;
17053
+ const params = isScaledOrder ? {
17054
+ orders: appendOrderMetadata(order.orders, orderMetadata)
17055
+ } : appendOrderMetadata(order, orderMetadata);
16925
17056
  const result = await doCreateOrder(params);
16926
17057
  if (result.success) {
16927
17058
  let trackParams = {
@@ -17222,6 +17353,7 @@ var usePositionClose = (options) => {
17222
17353
  const symbolsInfo = useSymbolsInfo();
17223
17354
  const { data: markPrices } = useMarkPricesStream();
17224
17355
  const markPricesRef = useRef(markPrices);
17356
+ const { orderMetadata } = useOrderlyContext();
17225
17357
  useEffect(() => {
17226
17358
  markPricesRef.current = markPrices;
17227
17359
  }, [markPrices]);
@@ -17290,7 +17422,8 @@ var usePositionClose = (options) => {
17290
17422
  if (Object.keys(errors2).length > 0) {
17291
17423
  throw errors2;
17292
17424
  }
17293
- return doCreateOrder(closeOrderData).then((res) => {
17425
+ const body = appendOrderMetadata(closeOrderData, orderMetadata);
17426
+ return doCreateOrder(body).then((res) => {
17294
17427
  if (res.success) {
17295
17428
  return res;
17296
17429
  }
@@ -17298,7 +17431,7 @@ var usePositionClose = (options) => {
17298
17431
  }).catch((err) => {
17299
17432
  throw err;
17300
17433
  });
17301
- }, [validate, doCreateOrder, closeOrderData]);
17434
+ }, [validate, doCreateOrder, closeOrderData, orderMetadata]);
17302
17435
  return {
17303
17436
  submit,
17304
17437
  isMutating,
@@ -17309,6 +17442,6 @@ var usePositionClose = (options) => {
17309
17442
  };
17310
17443
  };
17311
17444
 
17312
- export { DefaultLayoutConfig, DistributionId, ENVType2 as ENVType, EpochStatus, ExtendedConfigStore, MaintenanceStatus, MarketsStorageKey, MarketsType, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, StatusProvider, TWType, WalletConnectorContext, WsNetworkStatus, checkNotional, cleanStringStyle, fetcher, findPositionTPSLFromOrders, findTPSLFromOrder, findTPSLOrderPriceFromOrder, getMinNotional, parseJSON, useAccount, useAccountInfo2 as useAccountInfo, useAccountInstance, useAccountRewardsHistory, useAllBrokers, useApiKeyManager, useAssetsHistory, useAudioPlayer, useBalanceSubscription, useBalanceTopic, useBoolean, useChain, useChains, useCheckReferralCode, useCollateral, useCommission, useComputedLTV, useConfig, useConvert, useCurEpochEstimate, useDaily, useDeposit, useDistribution, useDistributionHistory, useEpochInfo, useEventEmitter, useFundingDetails, useFundingFeeHistory, useFundingRate, useFundingRateHistory, useFundingRates, useFundingRatesStore, useGetClaimed, useGetEnv, useGetReferralCode, useHoldingStream, useIndexPrice, useIndexPricesStream, useInfiniteQuery, useInternalTransfer, useKeyStore, useLazyQuery, useLeverage, useLocalStorage, useMaintenanceStatus, useMarginRatio, useMarkPrice, useMarkPriceBySymbol, useMarkPricesStream, useMarket, useMarketList, useMarketMap, useMarketTradeStream, useMarkets, useMarketsStore, useMarketsStream, useMaxQty, useMediaQuery, useMemoizedFn, useMutation, useNetworkInfo, useOdosQuote, useOrderEntity, useOrderEntry2 as useOrderEntry, useOrderEntry as useOrderEntry_deprecated, useOrderStore2 as useOrderStore, useOrderStream, useOrderbookStream, useOrderlyContext, usePositionActions, usePositionClose, usePositionStream, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, useRefereeHistory, useRefereeInfo, useRefereeRebateSummary, useReferralInfo, useReferralRebateSummary, useRestrictedInfo, useSessionStorage, useSettleSubscription, useSimpleDI, useStatisticsDaily, useStorageChain, useStorageLedgerAddress, useSubAccountDataObserver, useSubAccountMaxWithdrawal, useSubAccountMutation, useSubAccountQuery, useSubAccountWS, useSymbolLeverage, useSymbolPriceRange, useSymbolsInfo, useSymbolsInfoStore, useTPSLOrder, useTickerStream, useTokenInfo, useTokensInfo, useTrack, useTrackingInstance, useTradingRewardsStatus, useTransfer, useTransferHistory, useUpdatedRef, useVaultsHistory, useWS, useWalletConnector, useWalletRewardsHistory, useWalletSubscription, useWalletTopic, useWithdraw, useWsStatus, utils_exports as utils, version_default as version };
17445
+ export { DefaultLayoutConfig, DistributionId, ENVType2 as ENVType, EpochStatus, ExtendedConfigStore, MaintenanceStatus, MarketsStorageKey, MarketsType, ORDERLY_ORDERBOOK_DEPTH_KEY, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, StatusProvider, TWType, WalletConnectorContext, WsNetworkStatus, checkNotional, cleanStringStyle, fetcher, findPositionTPSLFromOrders, findTPSLFromOrder, findTPSLOrderPriceFromOrder, getMinNotional, getPriceKey, parseJSON, useAccount, useAccountInfo2 as useAccountInfo, useAccountInstance, useAccountRewardsHistory, useAllBrokers, useApiKeyManager, useAssetsHistory, useAudioPlayer, useBalanceSubscription, useBalanceTopic, useBoolean, useChain, useChains, useCheckReferralCode, useCollateral, useCommission, useComputedLTV, useConfig, useConvert, useCurEpochEstimate, useDaily, useDeposit, useDistribution, useDistributionHistory, useEpochInfo, useEventEmitter, useFundingDetails, useFundingFeeHistory, useFundingRate, useFundingRateHistory, useFundingRates, useFundingRatesStore, useGetClaimed, useGetEnv, useGetReferralCode, useHoldingStream, useIndexPrice, useIndexPricesStream, useInfiniteQuery, useInternalTransfer, useKeyStore, useLazyQuery, useLeverage, useLocalStorage, useMaintenanceStatus, useMarginRatio, useMarkPrice, useMarkPriceBySymbol, useMarkPricesStream, useMarket, useMarketList, useMarketMap, useMarketTradeStream, useMarkets, useMarketsStore, useMarketsStream, useMaxQty, useMediaQuery, useMemoizedFn, useMutation, useNetworkInfo, useOdosQuote, useOrderEntity, useOrderEntry2 as useOrderEntry, useOrderEntry as useOrderEntry_deprecated, useOrderStore2 as useOrderStore, useOrderStream, useOrderbookStream, useOrderlyContext, usePositionActions, usePositionClose, usePositionStream, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, useRefereeHistory, useRefereeInfo, useRefereeRebateSummary, useReferralInfo, useReferralRebateSummary, useRestrictedInfo, useSessionStorage, useSettleSubscription, useSimpleDI, useStatisticsDaily, useStorageChain, useStorageLedgerAddress, useSubAccountDataObserver, useSubAccountMaxWithdrawal, useSubAccountMutation, useSubAccountQuery, useSubAccountWS, useSymbolLeverage, useSymbolPriceRange, useSymbolsInfo, useSymbolsInfoStore, useTPSLOrder, useTickerStream, useTokenInfo, useTokensInfo, useTrack, useTrackingInstance, useTradingRewardsStatus, useTransfer, useTransferHistory, useUpdatedRef, useVaultsHistory, useWS, useWalletConnector, useWalletRewardsHistory, useWalletSubscription, useWalletTopic, useWithdraw, useWsStatus, utils_exports as utils, version_default as version };
17313
17446
  //# sourceMappingURL=out.js.map
17314
17447
  //# sourceMappingURL=index.mjs.map