@orderly.network/hooks 2.0.7 → 2.1.0

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
@@ -1,14 +1,16 @@
1
1
  import useSWR, { mutate } from 'swr';
2
2
  export { unstable_serialize, default as useSWR, useSWRConfig } from 'swr';
3
3
  import { get, WS, mutate as mutate$1 } from '@orderly.network/net';
4
- import React, { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef, useId, useLayoutEffect } from 'react';
4
+ import React, { createContext, useContext, useCallback, useState, useEffect, useMemo, useRef, useId, useLayoutEffect } from 'react';
5
+ import { OrderType, OrderSide, SDKError, EnumTrackerKeys, AccountStatusEnum, AlgoOrderRootType, OrderStatus, TesntTokenFallback, ArbitrumSepoliaTokenInfo, SolanaDevnetTokenInfo, ArbitrumSepoliaChainInfo, SolanaDevnetChainInfo, MONAD_TESTNET_CHAINID, nativeTokenAddress, ChainKey, chainsInfoMap, ARBITRUM_TESTNET_CHAINID, ARBITRUM_MAINNET_CHAINID, isNativeTokenChecker, ChainNamespace, MaxUint256, DEPOSIT_FEE_RATE, LedgerWalletKey, SolanaChains, TrackerListenerKeyMap, AlgoOrderType, TriggerPriceType } from '@orderly.network/types';
5
6
  import useSWRMutation from 'swr/mutation';
6
7
  import useConstant from 'use-constant';
7
8
  export { default as useConstant } from 'use-constant';
8
9
  import { SimpleDI, Account, EventEmitter, EVENT_NAMES, DefaultConfigStore, LocalStorageStore } from '@orderly.network/core';
9
10
  import { zero, getGlobalObject, getTimestamp, Decimal, timeConvertString, isTestnet, getPrecisionByNumber, camelCaseToUnderscoreCase, windowGuard, removeTrailingZeros, commify, todpIfNeed } from '@orderly.network/utils';
10
- import { OrderType, OrderSide, EnumTrackerKeys, AccountStatusEnum, SDKError, AlgoOrderRootType, OrderStatus, MONAD_TESTNET_CHAINID, nativeTokenAddress, chainsInfoMap, ARBITRUM_TESTNET_CHAINID, ARBITRUM_MAINNET_CHAINID, isNativeTokenChecker, ChainNamespace, MaxUint256, DEPOSIT_FEE_RATE, LedgerWalletKey, TrackerListenerKeyMap, AlgoOrderType, TriggerPriceType } from '@orderly.network/types';
11
+ import { debounce } from 'lodash';
11
12
  import useSWRInfinite, { unstable_serialize } from 'swr/infinite';
13
+ import * as amplitude from '@amplitude/analytics-browser';
12
14
  import { jsx } from 'react/jsx-runtime';
13
15
  import { pathOr, prop, omit, pick, compose, head, mergeDeepRight, min, max, isNil, propOr, path, lensIndex, over } from 'ramda';
14
16
  import { create } from 'zustand';
@@ -21,7 +23,6 @@ import { produce } from 'immer';
21
23
  import { DefaultEVMWalletAdapter } from '@orderly.network/default-evm-adapter';
22
24
  import { DefaultSolanaWalletAdapter } from '@orderly.network/default-solana-adapter';
23
25
  import { EthersProvider } from '@orderly.network/web3-provider-ethers';
24
- import * as amplitude from '@amplitude/analytics-browser';
25
26
  import { qrcode } from '@akamfoad/qr';
26
27
 
27
28
  var __defProp = Object.defineProperty;
@@ -33,20 +34,18 @@ var __export = (target, all) => {
33
34
  // src/version.ts
34
35
  if (typeof window !== "undefined") {
35
36
  window.__ORDERLY_VERSION__ = window.__ORDERLY_VERSION__ || {};
36
- window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.0.7";
37
+ window.__ORDERLY_VERSION__["@orderly.network/hooks"] = "2.1.0";
37
38
  }
38
- var version_default = "2.0.7";
39
+ var version_default = "2.1.0";
39
40
  var fetcher = (url, init2 = {}, queryOptions) => get(url, init2, queryOptions?.formatter);
40
41
  var OrderlyContext = createContext({
41
42
  // configStore: new MemoryConfigStore(),
42
43
  });
43
44
  var OrderlyProvider = OrderlyContext.Provider;
44
-
45
- // src/useConfig.ts
46
45
  function useConfig(key, defaultValue) {
47
46
  const { configStore } = useContext(OrderlyContext);
48
47
  if (!configStore) {
49
- throw new Error(
48
+ throw new SDKError(
50
49
  "useConfig must be used within OrderlyConfigProvider or OrderlyAppProvider"
51
50
  );
52
51
  }
@@ -58,13 +57,11 @@ function useConfig(key, defaultValue) {
58
57
  }
59
58
  return configStore;
60
59
  }
61
-
62
- // src/useQuery.ts
63
60
  var useQuery = (query, options) => {
64
61
  const apiBaseUrl = useConfig("apiBaseUrl");
65
62
  const { formatter, ...swrOptions } = options || {};
66
63
  if (typeof apiBaseUrl === "undefined") {
67
- throw new Error("please add OrderlyConfigProvider to your app");
64
+ throw new SDKError("please add OrderlyConfigProvider to your app");
68
65
  }
69
66
  return useSWR(
70
67
  query,
@@ -78,7 +75,7 @@ var useLazyQuery = (query, options) => {
78
75
  const apiBaseUrl = useConfig("apiBaseUrl");
79
76
  const { formatter, init: init2, ...swrOptions } = options || {};
80
77
  if (typeof apiBaseUrl === "undefined") {
81
- throw new Error("please add OrderlyConfigProvider to your app");
78
+ throw new SDKError("please add OrderlyConfigProvider to your app");
82
79
  }
83
80
  return useSWRMutation(
84
81
  query,
@@ -100,9 +97,11 @@ var useLazyQuery = (query, options) => {
100
97
  var useAccountInstance = () => {
101
98
  const { configStore, keyStore, walletAdapters } = useContext(OrderlyContext);
102
99
  if (!configStore)
103
- throw new Error("configStore is not defined, please use OrderlyProvider");
100
+ throw new SDKError(
101
+ "configStore is not defined, please use OrderlyProvider"
102
+ );
104
103
  if (!keyStore) {
105
- throw new Error(
104
+ throw new SDKError(
106
105
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
107
106
  );
108
107
  }
@@ -223,6 +222,26 @@ var useEventEmitter = () => {
223
222
  return ee;
224
223
  });
225
224
  };
225
+
226
+ // src/useTrack.ts
227
+ var useTrack = () => {
228
+ const ee = useEventEmitter();
229
+ const debouncedTrackFn = useCallback(
230
+ debounce((eventName, params) => {
231
+ ee.emit(eventName, params);
232
+ }, 500),
233
+ []
234
+ );
235
+ const track2 = useCallback((eventName, params) => {
236
+ debouncedTrackFn(eventName, params);
237
+ }, [debouncedTrackFn]);
238
+ const setTrackUserId = useCallback((userId) => {
239
+ ee.emit(EnumTrackerKeys.trackIdentifyUserId, userId);
240
+ }, []);
241
+ return { track: track2, setTrackUserId };
242
+ };
243
+
244
+ // src/useAccount.ts
226
245
  var useAccount = () => {
227
246
  const {
228
247
  configStore,
@@ -232,21 +251,18 @@ var useAccount = () => {
232
251
  // onSetChain,
233
252
  } = useContext(OrderlyContext);
234
253
  if (!configStore)
235
- throw new Error("configStore is not defined, please use OrderlyProvider");
254
+ throw new SDKError(
255
+ "configStore is not defined, please use OrderlyProvider"
256
+ );
236
257
  if (!keyStore) {
237
- throw new Error(
258
+ throw new SDKError(
238
259
  "keyStore is not defined, please use OrderlyProvider and provide keyStore"
239
260
  );
240
261
  }
241
262
  const account5 = useAccountInstance();
242
263
  const [state, setState] = useState(account5.stateValue);
243
- const ee = useEventEmitter();
264
+ const { track: track2 } = useTrack();
244
265
  const statusChangeHandler = (nextState) => {
245
- if (AccountStatusEnum.Connected === nextState.status) {
246
- ee.emit(EnumTrackerKeys.WALLET_CONNECT, {
247
- ...nextState
248
- });
249
- }
250
266
  setState(() => nextState);
251
267
  };
252
268
  useEffect(() => {
@@ -257,9 +273,9 @@ var useAccount = () => {
257
273
  }, []);
258
274
  const createOrderlyKey = useCallback(
259
275
  async (remember) => {
260
- ee.emit(EnumTrackerKeys.SIGNIN_SUCCESS, {
261
- ...state,
262
- ...account5
276
+ track2(EnumTrackerKeys.signinSuccess, {
277
+ network: account5.chainId,
278
+ wallet: state.connectWallet?.name
263
279
  });
264
280
  return account5.createOrderlyKey(remember ? 365 : 30);
265
281
  },
@@ -484,6 +500,77 @@ var useNetworkInfo = (networkId) => {
484
500
  };
485
501
  };
486
502
  };
503
+ var apiKeyMap = {
504
+ dev: "4d6b7db0fdd6e9de2b6a270414fd51e0",
505
+ qa: "96476b00bc2701360f9b480629ae5263",
506
+ staging: "dffc00e003479b86d410c448e00f2304",
507
+ prod: "3ab9ae56ed16cc57bc2ac97ffc1098c2"
508
+ };
509
+ var AmplitudeTracker = class {
510
+ constructor(env, sdkInfo) {
511
+ this._ee = SimpleDI.get("EE");
512
+ amplitude.init(apiKeyMap[env], { serverZone: "EU" });
513
+ this.setSdkInfo(sdkInfo);
514
+ this._bindEvents();
515
+ }
516
+ setUserId(userId) {
517
+ if (userId === this._userId) {
518
+ return;
519
+ }
520
+ amplitude.setUserId(userId);
521
+ this._userId = userId;
522
+ }
523
+ setSdkInfo(sdkInfo) {
524
+ if (this._sdkInfoTag && sdkInfo.address === this._sdkInfoTag)
525
+ return;
526
+ const identify2 = new amplitude.Identify();
527
+ Object.entries(sdkInfo).forEach(([key, value]) => {
528
+ identify2.set(key, value);
529
+ });
530
+ amplitude.identify(identify2);
531
+ this._sdkInfoTag = sdkInfo.address;
532
+ }
533
+ identify(identifyEvent) {
534
+ amplitude.identify(identifyEvent);
535
+ }
536
+ track(eventName, properties) {
537
+ amplitude.track(TrackerListenerKeyMap[eventName], properties);
538
+ }
539
+ _bindEvents() {
540
+ const listenKeys = Object.keys(TrackerListenerKeyMap);
541
+ listenKeys.forEach((key) => {
542
+ this._ee.addListener(key, (params = {}) => {
543
+ if (key === EnumTrackerKeys.trackIdentifyUserId) {
544
+ this.setUserId(params);
545
+ } else {
546
+ this.track(key, params);
547
+ }
548
+ });
549
+ });
550
+ }
551
+ };
552
+ AmplitudeTracker.instanceName = "amplitudeTracker";
553
+
554
+ // src/useTrackInstance.ts
555
+ var useTrackingInstance = () => {
556
+ const { configStore } = useContext(OrderlyContext);
557
+ if (!configStore)
558
+ throw new Error("configStore is not defined, please use OrderlyProvider");
559
+ const env = configStore.get("env");
560
+ const brokerId = configStore.get("brokerId");
561
+ const trackInstace = useConstant(() => {
562
+ let instance = SimpleDI.get("amplitudeTracker");
563
+ if (!instance) {
564
+ instance = new AmplitudeTracker(env, {
565
+ brokerId,
566
+ sdk_version: window?.__ORDERLY_VERSION__?.["@orderly.network/net"] ?? ""
567
+ });
568
+ SimpleDI.registerByName("instance", instance);
569
+ }
570
+ return instance;
571
+ });
572
+ return trackInstace;
573
+ };
487
574
  var WS_NAME = "nativeWebsocketClient";
488
575
  var useWS = () => {
489
576
  const { configStore } = useContext(OrderlyContext);
@@ -767,7 +854,7 @@ var AlgoOrderMergeHandler = class _AlgoOrderMergeHandler extends BaseMergeHandle
767
854
  (order) => order.parentAlgoOrderId === 0 && order.algoOrderId === order.rootAlgoOrderId
768
855
  );
769
856
  if (rootOrderIndex === -1) {
770
- throw new Error("Root order not found");
857
+ throw new SDKError("Root order not found");
771
858
  }
772
859
  const rootOrder_ = object2underscore(
773
860
  orders[rootOrderIndex]
@@ -789,7 +876,7 @@ var AlgoOrderMergeHandler = class _AlgoOrderMergeHandler extends BaseMergeHandle
789
876
  (order) => order.algoType !== AlgoOrderType.STOP_LOSS && order.algoType !== AlgoOrderType.TAKE_PROFIT
790
877
  );
791
878
  if (rootOrderIndex === -1) {
792
- throw new Error("Root order not found");
879
+ throw new SDKError("Root order not found");
793
880
  }
794
881
  const rootOrder = innerOrders.splice(
795
882
  rootOrderIndex,
@@ -1859,7 +1946,7 @@ var useFutures = () => {
1859
1946
  // src/orderly/useTickerStream.ts
1860
1947
  var useTickerStream = (symbol) => {
1861
1948
  if (!symbol) {
1862
- throw new Error("useFuturesForSymbol requires a symbol");
1949
+ throw new SDKError("Symbol is required");
1863
1950
  }
1864
1951
  const { data: info } = useQuery(
1865
1952
  `/v1/public/futures/${symbol}`,
@@ -2158,10 +2245,12 @@ var reduceOrderbook = (depth, level, padding, data) => {
2158
2245
  var INIT_DATA = { asks: [], bids: [] };
2159
2246
  var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
2160
2247
  if (!symbol) {
2161
- throw new SDKError("useOrderbookStream requires a symbol");
2248
+ throw new SDKError("Symbol is required");
2162
2249
  }
2163
2250
  const level = options?.level ?? 10;
2164
2251
  const padding = options?.padding ?? true;
2252
+ const symbolRef = useRef(symbol);
2253
+ symbolRef.current = symbol;
2165
2254
  const [requestData, setRequestData] = useState(null);
2166
2255
  const [data, setData] = useState(initial);
2167
2256
  const [isLoading, setIsLoading] = useState(true);
@@ -2204,13 +2293,17 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
2204
2293
  formatter: (message) => message,
2205
2294
  onMessage: (message) => {
2206
2295
  const { data: wsData, ts } = message;
2207
- const { asks, bids, prevTs } = wsData;
2296
+ const { symbol: symbol2, asks, bids, prevTs } = wsData;
2297
+ if (symbolRef.current !== symbol2) {
2298
+ orderBookUpdateSub?.();
2299
+ return;
2300
+ }
2208
2301
  orderbook_service_default.updateOrderbook(
2209
- symbol,
2302
+ symbol2,
2210
2303
  { asks, bids, ts, prevTs },
2211
2304
  () => needRequestFullOrderbook = true
2212
2305
  );
2213
- const data2 = orderbook_service_default.getRawOrderbook(symbol);
2306
+ const data2 = orderbook_service_default.getRawOrderbook(symbol2);
2214
2307
  setData({ bids: data2.bids, asks: data2.asks });
2215
2308
  }
2216
2309
  }
@@ -2230,6 +2323,9 @@ var useOrderbookStream = (symbol, initial = INIT_DATA, options) => {
2230
2323
  formatter: (message) => message,
2231
2324
  onMessage: (message) => {
2232
2325
  const { symbol: symbol2, asks, bids, ts } = message.data;
2326
+ if (symbolRef.current !== symbol2) {
2327
+ return;
2328
+ }
2233
2329
  orderbook_service_default.setFullOrderbook(symbol2, { asks, bids, ts });
2234
2330
  const data2 = orderbook_service_default.getRawOrderbook(symbol2);
2235
2331
  setData({ bids: data2.bids, asks: data2.asks });
@@ -2999,7 +3095,7 @@ var useLeverage = () => {
2999
3095
  };
3000
3096
  var useFundingRate = (symbol) => {
3001
3097
  if (!symbol) {
3002
- throw new Error("useFuturesForSymbol requires a symbol");
3098
+ throw new SDKError("Symbol is required");
3003
3099
  }
3004
3100
  const [countDown, setCountDown] = useState("00:00:00");
3005
3101
  const { data } = useQuery(
@@ -3363,10 +3459,10 @@ var useOrderStream = (params, options) => {
3363
3459
  }, [orders?.length]);
3364
3460
  const cancelAlgoOrdersByTypes = (types) => {
3365
3461
  if (!types) {
3366
- throw new SDKError("types is required");
3462
+ throw new SDKError("Types is required");
3367
3463
  }
3368
3464
  if (!Array.isArray(types)) {
3369
- throw new SDKError("types should be an array");
3465
+ throw new SDKError("Types should be an array");
3370
3466
  }
3371
3467
  return Promise.all(
3372
3468
  types.map((type) => {
@@ -3467,7 +3563,7 @@ var useOrderStream = (params, options) => {
3467
3563
  const updateTPSLOrder = useCallback(
3468
3564
  (orderId, childOrders) => {
3469
3565
  if (!Array.isArray(childOrders)) {
3470
- throw new SDKError("children orders is required");
3566
+ throw new SDKError("Children orders is required");
3471
3567
  }
3472
3568
  return doUpdateAlgoOrder({
3473
3569
  order_id: orderId,
@@ -3513,7 +3609,7 @@ var useOrderStream = (params, options) => {
3513
3609
  };
3514
3610
  var useMarketTradeStream = (symbol, options = {}) => {
3515
3611
  if (!symbol) {
3516
- throw new Error("useTradeStream: symbol is required");
3612
+ throw new SDKError("Symbol is required");
3517
3613
  }
3518
3614
  const [trades, setTrades] = useState([]);
3519
3615
  const [isLoading, setIsLoading] = useState(false);
@@ -3742,7 +3838,13 @@ function useChains(networkId, options = {}) {
3742
3838
  );
3743
3839
  const { data: testTokenChainsRes } = useQuery(
3744
3840
  "https://testnet-api.orderly.org/v1/public/token",
3745
- { ...commonSwrOpts }
3841
+ {
3842
+ ...commonSwrOpts,
3843
+ fallbackData: TesntTokenFallback([
3844
+ ArbitrumSepoliaTokenInfo,
3845
+ SolanaDevnetTokenInfo
3846
+ ])
3847
+ }
3746
3848
  );
3747
3849
  const brokerId = configStore.get("brokerId");
3748
3850
  const needFetchFromAPI = options.forceAPI || !customChains;
@@ -3750,9 +3852,14 @@ function useChains(networkId, options = {}) {
3750
3852
  needFetchFromAPI ? `https://api.orderly.org/v1/public/chain_info${brokerId !== "orderly" ? `?broker_id=${brokerId}` : ""}` : null,
3751
3853
  { ...commonSwrOpts }
3752
3854
  );
3753
- const { data: testChainInfos } = useQuery(
3855
+ const { data: testChainInfos, error: testChainInfoError } = useQuery(
3754
3856
  needFetchFromAPI ? `https://testnet-api.orderly.org/v1/public/chain_info${brokerId !== "orderly" ? `?broker_id=${brokerId}` : ""}` : null,
3755
- { ...commonSwrOpts }
3857
+ {
3858
+ ...commonSwrOpts,
3859
+ fallbackData: [ArbitrumSepoliaChainInfo, SolanaDevnetChainInfo],
3860
+ onError: (error) => {
3861
+ }
3862
+ }
3756
3863
  );
3757
3864
  const chains = useMemo(() => {
3758
3865
  const tokenChains = fillChainsInfo(
@@ -3929,6 +4036,23 @@ function filterByAllowedChains(chains, allowedChains) {
3929
4036
  )
3930
4037
  );
3931
4038
  }
4039
+ function useStorageChain() {
4040
+ const [chain, setChain] = useLocalStorage(ChainKey, null);
4041
+ const setStorageChain = (chainId) => {
4042
+ let namespace = ChainNamespace.evm;
4043
+ if (SolanaChains.has(chainId)) {
4044
+ namespace = ChainNamespace.solana;
4045
+ }
4046
+ setChain({
4047
+ chainId,
4048
+ namespace
4049
+ });
4050
+ };
4051
+ return {
4052
+ storageChain: chain,
4053
+ setStorageChain
4054
+ };
4055
+ }
3932
4056
  var useChain = (token) => {
3933
4057
  const { data, isLoading } = useQuery("/v1/public/token");
3934
4058
  const chains = useMemo(() => {
@@ -4004,6 +4128,7 @@ var useWithdraw = (options) => {
4004
4128
  const networkId = useConfig("networkId");
4005
4129
  const [_, { findByChainId }] = useChains(void 0);
4006
4130
  const ee = useEventEmitter();
4131
+ const { track: track2 } = useTrack();
4007
4132
  const { usdc } = useHoldingStream();
4008
4133
  const maxAmount = useMemo(() => {
4009
4134
  return freeCollateral;
@@ -4045,7 +4170,7 @@ var useWithdraw = (options) => {
4045
4170
  (inputs) => {
4046
4171
  return account5.assetsManager.withdraw(inputs).then((res) => {
4047
4172
  if (res.success) {
4048
- ee.emit(EnumTrackerKeys.WITHDRAW_SUCCESS, {
4173
+ ee.emit(EnumTrackerKeys.withdrawSuccess, {
4049
4174
  wallet: state?.connectWallet?.name,
4050
4175
  network: targetChain?.network_infos.name,
4051
4176
  quantity: inputs.amount
@@ -4053,7 +4178,7 @@ var useWithdraw = (options) => {
4053
4178
  }
4054
4179
  return res;
4055
4180
  }).catch((err) => {
4056
- ee.emit(EnumTrackerKeys.WITHDRAW_FAILED, {
4181
+ track2(EnumTrackerKeys.withdrawFailed, {
4057
4182
  wallet: state?.connectWallet?.name,
4058
4183
  network: targetChain?.network_infos.name,
4059
4184
  msg: JSON.stringify(err)
@@ -4077,7 +4202,7 @@ var useDeposit = (options) => {
4077
4202
  const networkId = useConfig("networkId");
4078
4203
  const [balanceRevalidating, setBalanceRevalidating] = useState(false);
4079
4204
  const [allowanceRevalidating, setAllowanceRevalidating] = useState(false);
4080
- const ee = useEventEmitter();
4205
+ useEventEmitter();
4081
4206
  const [_, { findByChainId }] = useChains(void 0);
4082
4207
  const [quantity, setQuantity] = useState("");
4083
4208
  const [depositFee, setDepositFee] = useState(0n);
@@ -4085,6 +4210,7 @@ var useDeposit = (options) => {
4085
4210
  const [balance, setBalance] = useState("0");
4086
4211
  const [allowance, setAllowance] = useState("0");
4087
4212
  const { account: account5, state } = useAccount();
4213
+ const { track: track2 } = useTrack();
4088
4214
  const prevAddress = useRef();
4089
4215
  const getBalanceListener = useRef();
4090
4216
  const targetChain = useMemo(() => {
@@ -4250,7 +4376,7 @@ var useDeposit = (options) => {
4250
4376
  const approve = useCallback(
4251
4377
  async (amount) => {
4252
4378
  if (!options?.address) {
4253
- throw new Error("address is required");
4379
+ throw new SDKError("Address is required");
4254
4380
  }
4255
4381
  return account5.assetsManager.approve({
4256
4382
  address: options.address,
@@ -4264,17 +4390,17 @@ var useDeposit = (options) => {
4264
4390
  );
4265
4391
  const deposit = useCallback(async () => {
4266
4392
  if (!options?.address) {
4267
- throw new Error("address is required");
4393
+ throw new SDKError("Address is required");
4268
4394
  }
4269
4395
  const _allowance = await account5.assetsManager.getAllowance({
4270
4396
  address: options?.address
4271
4397
  });
4272
4398
  setAllowance(() => _allowance);
4273
4399
  if (new Decimal(quantity).greaterThan(_allowance)) {
4274
- throw new Error("Insufficient allowance");
4400
+ throw new SDKError("Insufficient allowance");
4275
4401
  }
4276
4402
  return account5.assetsManager.deposit(quantity, depositFee).then((res) => {
4277
- ee.emit(EnumTrackerKeys.DEPOSIT_SUCCESS, {
4403
+ track2(EnumTrackerKeys.depositSuccess, {
4278
4404
  wallet: state?.connectWallet?.name,
4279
4405
  network: targetChain?.network_infos.name,
4280
4406
  quantity
@@ -4283,7 +4409,7 @@ var useDeposit = (options) => {
4283
4409
  setBalance((value) => new Decimal(value).sub(quantity).toString());
4284
4410
  return res;
4285
4411
  }).catch((e) => {
4286
- ee.emit(EnumTrackerKeys.DEPOSIT_FAILED, {
4412
+ track2(EnumTrackerKeys.depositFailed, {
4287
4413
  wallet: state?.connectWallet?.name,
4288
4414
  network: targetChain?.network_infos?.name,
4289
4415
  msg: JSON.stringify(e)
@@ -4679,6 +4805,26 @@ function tpslCalculateHelper(key, inputs, options = {}) {
4679
4805
  // }),
4680
4806
  };
4681
4807
  }
4808
+ function getMinNotional(props) {
4809
+ const { price, base_tick, qty, min_notional, base_dp, quote_dp, quote_tick } = props;
4810
+ if (price !== void 0 && qty !== void 0 && min_notional !== void 0) {
4811
+ try {
4812
+ const calcNotional = new Decimal(price).mul(new Decimal(qty)).toNumber();
4813
+ const notional = Number.parseFloat(`${min_notional}`);
4814
+ if (calcNotional < notional) {
4815
+ let minQty = new Decimal(notional).div(price).toDecimalPlaces(base_dp, Decimal.ROUND_DOWN).add(base_tick ?? 0);
4816
+ if (base_tick && base_tick > 0) {
4817
+ minQty = new Decimal(
4818
+ getRoundedDownDivision(minQty.toNumber(), base_tick)
4819
+ );
4820
+ }
4821
+ const newMinNotional = minQty.mul(price).add(quote_tick ?? 0).toFixed(quote_dp);
4822
+ return newMinNotional;
4823
+ }
4824
+ } catch (e) {
4825
+ }
4826
+ }
4827
+ }
4682
4828
  function checkNotional(props) {
4683
4829
  const { price, base_tick, qty, min_notional, base_dp, quote_dp, quote_tick } = props;
4684
4830
  if (price !== void 0 && qty !== void 0 && min_notional !== void 0) {
@@ -4709,6 +4855,47 @@ function getRoundedDownDivision(value, tick) {
4709
4855
  return quotient.mul(decimalTick).toNumber();
4710
4856
  }
4711
4857
 
4858
+ // src/services/orderCreator/orderValidation.ts
4859
+ var OrderValidation = class {
4860
+ static getLabel(key) {
4861
+ switch (key) {
4862
+ case "quantity":
4863
+ case "order_quantity":
4864
+ return "Quantity";
4865
+ case "order_price":
4866
+ return "Price";
4867
+ case "trigger_price":
4868
+ return "Trigger price";
4869
+ case "tp_trigger_price":
4870
+ return "TP price";
4871
+ case "sl_trigger_price":
4872
+ return "SL price";
4873
+ default:
4874
+ return key;
4875
+ }
4876
+ }
4877
+ static required(key) {
4878
+ return {
4879
+ type: "required",
4880
+ message: `${this.getLabel(key)} is required`
4881
+ };
4882
+ }
4883
+ static min(key, value) {
4884
+ return {
4885
+ type: "min",
4886
+ message: `${this.getLabel(key)} must be greater than ${value}`,
4887
+ value
4888
+ };
4889
+ }
4890
+ static max(key, value) {
4891
+ return {
4892
+ type: "max",
4893
+ message: `${this.getLabel(key)} must be less than ${value}`,
4894
+ value
4895
+ };
4896
+ }
4897
+ };
4898
+
4712
4899
  // src/services/orderCreator/baseCreator.ts
4713
4900
  var BaseOrderCreator = class {
4714
4901
  baseOrder(data) {
@@ -4747,31 +4934,24 @@ var BaseOrderCreator = class {
4747
4934
  }
4748
4935
  }
4749
4936
  if (!order_quantity) {
4750
- errors.order_quantity = {
4751
- type: "required",
4752
- message: "Quantity is required"
4753
- };
4937
+ errors.order_quantity = OrderValidation.required("order_quantity");
4754
4938
  } else {
4755
4939
  const { base_min, quote_dp: quote_dp2, base_dp: base_dp2 } = configs.symbol;
4756
4940
  const qty = new Decimal(order_quantity);
4757
4941
  if (qty.lt(base_min)) {
4758
- errors.order_quantity = {
4759
- type: "min",
4760
- message: `Quantity must be greater than ${new Decimal(base_min).todp(
4761
- base_dp2
4762
- )}`
4763
- };
4942
+ errors.order_quantity = OrderValidation.min(
4943
+ "order_quantity",
4944
+ new Decimal(base_min).todp(base_dp2).toString()
4945
+ );
4764
4946
  } else if (qty.gt(maxQty)) {
4765
- errors.order_quantity = {
4766
- type: "max",
4767
- message: `Quantity must be less than ${new Decimal(maxQty).todp(
4768
- base_dp2
4769
- )}`
4770
- };
4947
+ errors.order_quantity = OrderValidation.max(
4948
+ "order_quantity",
4949
+ new Decimal(maxQty).todp(base_dp2).toString()
4950
+ );
4771
4951
  }
4772
4952
  }
4773
4953
  const price = `${order_type}`.includes("MARKET") ? markPrice : order_price;
4774
- const notionalHintStr = checkNotional({
4954
+ const minNotional = getMinNotional({
4775
4955
  base_tick,
4776
4956
  quote_tick,
4777
4957
  price,
@@ -4780,10 +4960,11 @@ var BaseOrderCreator = class {
4780
4960
  quote_dp,
4781
4961
  base_dp
4782
4962
  });
4783
- if (notionalHintStr !== void 0 && !reduce_only) {
4963
+ if (minNotional !== void 0 && !reduce_only) {
4784
4964
  errors.total = {
4785
4965
  type: "min",
4786
- message: notionalHintStr
4966
+ message: `The order value should be greater or equal to ${minNotional} USDC`,
4967
+ value: minNotional
4787
4968
  };
4788
4969
  }
4789
4970
  this.validateBracketOrder(values2, configs, errors);
@@ -4848,62 +5029,62 @@ var BaseOrderCreator = class {
4848
5029
  if (hasTPPrice) {
4849
5030
  const tpPrice = new Decimal(tp_trigger_price);
4850
5031
  if (tpPrice.gt(quote_max)) {
4851
- errors.tp_trigger_price = {
4852
- type: "max",
4853
- message: `TP price must be less than ${quote_max}`
4854
- };
5032
+ errors.tp_trigger_price = OrderValidation.max(
5033
+ "tp_trigger_price",
5034
+ quote_max
5035
+ );
4855
5036
  }
4856
5037
  if (tpPrice.lt(quote_min)) {
4857
- errors.tp_trigger_price = {
4858
- type: "min",
4859
- message: `TP price must be greater than ${quote_min}`
4860
- };
5038
+ errors.tp_trigger_price = OrderValidation.min(
5039
+ "tp_trigger_price",
5040
+ quote_min
5041
+ );
4861
5042
  }
4862
5043
  if (side === OrderSide.BUY) {
4863
5044
  if (tpPrice.lte(_orderPrice)) {
4864
- errors.tp_trigger_price = {
4865
- type: "tpPrice < order_price",
4866
- message: `TP must be greater than ${_orderPrice}`
4867
- };
5045
+ errors.tp_trigger_price = OrderValidation.min(
5046
+ "tp_trigger_price",
5047
+ _orderPrice
5048
+ );
4868
5049
  }
4869
5050
  }
4870
5051
  if (side === OrderSide.SELL) {
4871
5052
  if (tpPrice.gte(_orderPrice)) {
4872
- errors.tp_trigger_price = {
4873
- type: "tpPrice > order_price",
4874
- message: `TP price must be less than ${_orderPrice}`
4875
- };
5053
+ errors.tp_trigger_price = OrderValidation.max(
5054
+ "tp_trigger_price",
5055
+ _orderPrice
5056
+ );
4876
5057
  }
4877
5058
  }
4878
5059
  }
4879
5060
  if (hasSLPrice) {
4880
5061
  const slPrice = new Decimal(sl_trigger_price);
4881
5062
  if (slPrice.gt(quote_max)) {
4882
- errors.sl_trigger_price = {
4883
- type: "max",
4884
- message: `SL price must be less than ${quote_max}`
4885
- };
5063
+ errors.sl_trigger_price = OrderValidation.max(
5064
+ "sl_trigger_price",
5065
+ quote_max
5066
+ );
4886
5067
  }
4887
5068
  if (slPrice.lt(quote_min)) {
4888
- errors.sl_trigger_price = {
4889
- type: "min",
4890
- message: `SL price must be greater than ${quote_min}`
4891
- };
5069
+ errors.sl_trigger_price = OrderValidation.min(
5070
+ "sl_trigger_price",
5071
+ quote_min
5072
+ );
4892
5073
  }
4893
5074
  if (side === OrderSide.BUY) {
4894
5075
  if (slPrice.gte(_orderPrice)) {
4895
- errors.sl_trigger_price = {
4896
- type: "slPrice > order_price",
4897
- message: `SL price must be less than ${_orderPrice}`
4898
- };
5076
+ errors.sl_trigger_price = OrderValidation.max(
5077
+ "sl_trigger_price",
5078
+ _orderPrice
5079
+ );
4899
5080
  }
4900
5081
  }
4901
5082
  if (side === OrderSide.SELL) {
4902
5083
  if (slPrice.lte(_orderPrice)) {
4903
- errors.sl_trigger_price = {
4904
- type: "slPrice < order_price",
4905
- message: `SL price must be greater than ${_orderPrice}`
4906
- };
5084
+ errors.sl_trigger_price = OrderValidation.min(
5085
+ "sl_trigger_price",
5086
+ _orderPrice
5087
+ );
4907
5088
  }
4908
5089
  }
4909
5090
  }
@@ -4958,10 +5139,7 @@ var LimitOrderCreator = class extends BaseOrderCreator {
4958
5139
  return this.baseValidate(values2, config).then((errors) => {
4959
5140
  const { order_price, side } = values2;
4960
5141
  if (!order_price) {
4961
- errors.order_price = {
4962
- type: "required",
4963
- message: "Price is required"
4964
- };
5142
+ errors.order_price = OrderValidation.required("order_price");
4965
5143
  } else {
4966
5144
  const price = new Decimal(order_price);
4967
5145
  const { symbol } = config;
@@ -4981,33 +5159,23 @@ var LimitOrderCreator = class extends BaseOrderCreator {
4981
5159
  max: scopePriceNumber
4982
5160
  };
4983
5161
  if (price.gt(quote_max)) {
4984
- errors.order_price = {
4985
- type: "max",
4986
- message: `Price must be less than ${quote_max}`
4987
- };
5162
+ errors.order_price = OrderValidation.max("order_price", quote_max);
4988
5163
  } else {
4989
5164
  if (price.gt(priceRange?.max)) {
4990
- errors.order_price = {
4991
- type: "max",
4992
- message: `Price must be less than ${new Decimal(
4993
- priceRange.max
4994
- ).todp(symbol.quote_dp)}`
4995
- };
5165
+ errors.order_price = OrderValidation.max(
5166
+ "order_price",
5167
+ new Decimal(priceRange.max).todp(symbol.quote_dp).toString()
5168
+ );
4996
5169
  }
4997
5170
  }
4998
5171
  if (price.lt(quote_min)) {
4999
- errors.order_price = {
5000
- type: "min",
5001
- message: `Price must be greater than ${quote_min}`
5002
- };
5172
+ errors.order_price = OrderValidation.min("order_price", quote_min);
5003
5173
  } else {
5004
5174
  if (price.lt(priceRange?.min)) {
5005
- errors.order_price = {
5006
- type: "min",
5007
- message: `Price must be greater than ${new Decimal(
5008
- priceRange.min
5009
- ).todp(symbol.quote_dp)}`
5010
- };
5175
+ errors.order_price = OrderValidation.min(
5176
+ "order_price",
5177
+ new Decimal(priceRange.min).todp(symbol.quote_dp).toString()
5178
+ );
5011
5179
  }
5012
5180
  }
5013
5181
  }
@@ -5054,27 +5222,15 @@ var StopLimitOrderCreator = class extends BaseOrderCreator {
5054
5222
  const { symbol } = config;
5055
5223
  const { price_range, price_scope, quote_max, quote_min } = symbol;
5056
5224
  if (!trigger_price) {
5057
- errors.trigger_price = {
5058
- type: "required",
5059
- message: "Trigger price is required"
5060
- };
5225
+ errors.trigger_price = OrderValidation.required("trigger_price");
5061
5226
  }
5062
5227
  if (!order_price) {
5063
- errors.order_price = {
5064
- type: "required",
5065
- message: "Price is required"
5066
- };
5228
+ errors.order_price = OrderValidation.required("order_price");
5067
5229
  }
5068
5230
  if (trigger_price > quote_max) {
5069
- errors.trigger_price = {
5070
- type: "max",
5071
- message: `Trigger price must be less than ${quote_max}`
5072
- };
5231
+ errors.trigger_price = OrderValidation.max("trigger_price", quote_max);
5073
5232
  } else if (trigger_price < quote_min) {
5074
- errors.trigger_price = {
5075
- type: "min",
5076
- message: `Trigger price must be greater than ${quote_min}`
5077
- };
5233
+ errors.trigger_price = OrderValidation.min("trigger_price", quote_min);
5078
5234
  } else {
5079
5235
  if (trigger_price && order_price) {
5080
5236
  const price = new Decimal(order_price);
@@ -5093,33 +5249,23 @@ var StopLimitOrderCreator = class extends BaseOrderCreator {
5093
5249
  max: scropePriceNumbere
5094
5250
  };
5095
5251
  if (price.gt(quote_max)) {
5096
- errors.order_price = {
5097
- type: "max",
5098
- message: `Price must be less than ${quote_max}`
5099
- };
5252
+ errors.order_price = OrderValidation.max("order_price", quote_max);
5100
5253
  } else {
5101
5254
  if (price.gt(priceRange?.max)) {
5102
- errors.order_price = {
5103
- type: "max",
5104
- message: `Price must be less than ${new Decimal(
5105
- priceRange.max
5106
- ).todp(symbol.quote_dp)}`
5107
- };
5255
+ errors.order_price = OrderValidation.max(
5256
+ "order_price",
5257
+ new Decimal(priceRange.max).todp(symbol.quote_dp).toString()
5258
+ );
5108
5259
  }
5109
5260
  }
5110
5261
  if (price.lt(quote_min)) {
5111
- errors.order_price = {
5112
- type: "min",
5113
- message: `Price must be greater than ${quote_min}`
5114
- };
5262
+ errors.order_price = OrderValidation.min("order_price", quote_min);
5115
5263
  } else {
5116
5264
  if (price.lt(priceRange?.min)) {
5117
- errors.order_price = {
5118
- type: "min",
5119
- message: `Price must be greater than ${new Decimal(
5120
- priceRange.min
5121
- ).todp(symbol.quote_dp)}`
5122
- };
5265
+ errors.order_price = OrderValidation.min(
5266
+ "order_price",
5267
+ new Decimal(priceRange.min).todp(symbol.quote_dp).toString()
5268
+ );
5123
5269
  }
5124
5270
  }
5125
5271
  }
@@ -5176,21 +5322,12 @@ var StopMarketOrderCreator = class extends BaseOrderCreator {
5176
5322
  const { symbol } = config;
5177
5323
  const { quote_max, quote_min } = symbol;
5178
5324
  if (!trigger_price) {
5179
- errors.trigger_price = {
5180
- type: "required",
5181
- message: "Trigger price is required"
5182
- };
5325
+ errors.trigger_price = OrderValidation.required("trigger_price");
5183
5326
  }
5184
5327
  if (trigger_price > quote_max) {
5185
- errors.trigger_price = {
5186
- type: "max",
5187
- message: `Trigger price must be less than ${quote_max}`
5188
- };
5328
+ errors.trigger_price = OrderValidation.max("trigger_price", quote_max);
5189
5329
  } else if (trigger_price < quote_min) {
5190
- errors.trigger_price = {
5191
- type: "min",
5192
- message: `Trigger price must be greater than ${quote_min}`
5193
- };
5330
+ errors.trigger_price = OrderValidation.min("trigger_price", quote_min);
5194
5331
  }
5195
5332
  return errors;
5196
5333
  });
@@ -5219,82 +5356,91 @@ var BaseAlgoOrderCreator = class {
5219
5356
  const qty = Number(values2.quantity);
5220
5357
  const maxQty = config.maxQty;
5221
5358
  const orderType = values2.order_type;
5222
- const { quote_max, quote_min, price_scope, quote_dp, base_min, min_notional } = config.symbol ?? {};
5359
+ const {
5360
+ quote_max,
5361
+ quote_min,
5362
+ price_scope,
5363
+ quote_dp,
5364
+ base_min,
5365
+ min_notional
5366
+ } = config.symbol ?? {};
5223
5367
  if (!isNaN(qty) && qty > maxQty) {
5224
- result.quantity = {
5225
- message: `Quantity must be less than ${config.maxQty}`
5226
- };
5368
+ result.quantity = OrderValidation.max("quantity", config.maxQty);
5227
5369
  }
5228
5370
  if (!isNaN(qty) && qty < base_min) {
5229
- result.quantity = {
5230
- message: `Quantity must be greater than ${base_min}`
5231
- };
5371
+ result.quantity = OrderValidation.min("quantity", base_min);
5232
5372
  }
5233
5373
  if (Number(tp_trigger_price) < 0) {
5234
- result.tp_trigger_price = {
5235
- message: `TP Price must be greater than 0`
5236
- };
5374
+ result.tp_trigger_price = OrderValidation.min("tp_trigger_price", 0);
5237
5375
  }
5238
5376
  if (Number(sl_trigger_price) < 0) {
5239
- result.sl_trigger_price = {
5240
- message: `SL Price must be greater than 0`
5241
- };
5377
+ result.sl_trigger_price = OrderValidation.min("sl_trigger_price", 0);
5242
5378
  }
5243
5379
  const mark_price = orderType === OrderType.MARKET || orderType == null ? config.markPrice : values2.order_price ? Number(values2.order_price) : void 0;
5244
5380
  if (side === OrderSide.BUY && mark_price) {
5245
5381
  const slTriggerPriceScope = new Decimal(mark_price * (1 - price_scope)).toDecimalPlaces(quote_dp, Decimal.ROUND_DOWN).toNumber();
5246
5382
  if (!!sl_trigger_price && Number(sl_trigger_price) < slTriggerPriceScope) {
5247
- result.sl_trigger_price = {
5248
- message: `SL price must be greater than ${slTriggerPriceScope}`
5249
- };
5383
+ result.sl_trigger_price = OrderValidation.min(
5384
+ "sl_trigger_price",
5385
+ slTriggerPriceScope
5386
+ );
5250
5387
  }
5251
5388
  if (!!sl_trigger_price && Number(sl_trigger_price) > config.markPrice) {
5252
- result.sl_trigger_price = {
5253
- message: `SL price must be less than ${config.markPrice}`
5254
- };
5389
+ result.sl_trigger_price = OrderValidation.max(
5390
+ "sl_trigger_price",
5391
+ config.markPrice
5392
+ );
5255
5393
  }
5256
5394
  if (!!tp_trigger_price && Number(tp_trigger_price) <= config.markPrice) {
5257
- result.tp_trigger_price = {
5258
- message: `TP price must be greater than ${config.markPrice}`
5259
- };
5395
+ result.tp_trigger_price = OrderValidation.min(
5396
+ "tp_trigger_price",
5397
+ config.markPrice
5398
+ );
5260
5399
  }
5261
5400
  if (!!tp_trigger_price && Number(tp_trigger_price) > quote_max) {
5262
- result.tp_trigger_price = {
5263
- message: `TP price must be less than ${quote_max}`
5264
- };
5401
+ result.tp_trigger_price = OrderValidation.max(
5402
+ "tp_trigger_price",
5403
+ quote_max
5404
+ );
5265
5405
  }
5266
5406
  if (!!sl_trigger_price && Number(sl_trigger_price) < quote_min) {
5267
- result.sl_trigger_price = {
5268
- message: `TP price must be greater than ${quote_min}`
5269
- };
5407
+ result.sl_trigger_price = OrderValidation.min(
5408
+ "sl_trigger_price",
5409
+ quote_min
5410
+ );
5270
5411
  }
5271
5412
  }
5272
5413
  if (side === OrderSide.SELL && mark_price) {
5273
5414
  const slTriggerPriceScope = new Decimal(mark_price * (1 + price_scope)).toDecimalPlaces(quote_dp, Decimal.ROUND_DOWN).toNumber();
5274
5415
  if (!!sl_trigger_price && Number(sl_trigger_price) > slTriggerPriceScope) {
5275
- result.sl_trigger_price = {
5276
- message: `SL price must be less than ${slTriggerPriceScope}`
5277
- };
5416
+ result.sl_trigger_price = OrderValidation.max(
5417
+ "sl_trigger_price",
5418
+ slTriggerPriceScope
5419
+ );
5278
5420
  }
5279
5421
  if (!!sl_trigger_price && Number(sl_trigger_price) < config.markPrice) {
5280
- result.sl_trigger_price = {
5281
- message: `SL price must be greater than ${config.markPrice}`
5282
- };
5422
+ result.sl_trigger_price = OrderValidation.min(
5423
+ "sl_trigger_price",
5424
+ config.markPrice
5425
+ );
5283
5426
  }
5284
5427
  if (!!tp_trigger_price && Number(tp_trigger_price) >= config.markPrice) {
5285
- result.tp_trigger_price = {
5286
- message: `TP price must be less than ${config.markPrice}`
5287
- };
5428
+ result.tp_trigger_price = OrderValidation.max(
5429
+ "tp_trigger_price",
5430
+ config.markPrice
5431
+ );
5288
5432
  }
5289
5433
  if (!!tp_trigger_price && Number(tp_trigger_price) > quote_max) {
5290
- result.tp_trigger_price = {
5291
- message: `TP price must be less than ${quote_max}`
5292
- };
5434
+ result.tp_trigger_price = OrderValidation.max(
5435
+ "tp_trigger_price",
5436
+ quote_max
5437
+ );
5293
5438
  }
5294
5439
  if (!!sl_trigger_price && Number(sl_trigger_price) < quote_min) {
5295
- result.sl_trigger_price = {
5296
- message: `TP price must be greater than ${quote_min}`
5297
- };
5440
+ result.sl_trigger_price = OrderValidation.min(
5441
+ "sl_trigger_price",
5442
+ quote_min
5443
+ );
5298
5444
  }
5299
5445
  }
5300
5446
  return Object.keys(result).length > 0 ? result : null;
@@ -5466,64 +5612,66 @@ async function bracketOrderValidator(values2, config) {
5466
5612
  const { quote_max, quote_min, price_scope, quote_dp } = config.symbol ?? {};
5467
5613
  const mark_price = type === OrderType.MARKET ? config.markPrice : values2.order_price ? Number(values2.order_price) : void 0;
5468
5614
  if (!isNaN(qty) && qty > maxQty) {
5469
- result.quantity = {
5470
- message: `Quantity must be less than ${config.maxQty}`
5471
- };
5615
+ result.quantity = OrderValidation.max("quantity", config.maxQty);
5472
5616
  }
5473
5617
  if (Number(tp_trigger_price) < 0) {
5474
- result.tp_trigger_price = {
5475
- message: `TP Price must be greater than 0`
5476
- };
5618
+ result.tp_trigger_price = OrderValidation.min("tp_trigger_price", 0);
5477
5619
  }
5478
5620
  if (Number(sl_trigger_price) < 0) {
5479
- result.sl_trigger_price = {
5480
- message: `SL Price must be greater than 0`
5481
- };
5621
+ result.sl_trigger_price = OrderValidation.min("sl_trigger_price", 0);
5482
5622
  }
5483
5623
  if (side === OrderSide.BUY && mark_price) {
5484
5624
  const slTriggerPriceScope = new Decimal(mark_price * (1 - price_scope)).toDecimalPlaces(quote_dp, Decimal.ROUND_DOWN).toNumber();
5485
5625
  if (!!sl_trigger_price && Number(sl_trigger_price) < slTriggerPriceScope) {
5486
- result.sl_trigger_price = {
5487
- message: `SL price must be greater than ${slTriggerPriceScope}`
5488
- };
5626
+ result.sl_trigger_price = OrderValidation.min(
5627
+ "sl_trigger_price",
5628
+ slTriggerPriceScope
5629
+ );
5489
5630
  }
5490
5631
  if (!!tp_trigger_price && Number(tp_trigger_price) <= mark_price) {
5491
- result.tp_trigger_price = {
5492
- message: `TP price must be greater than ${mark_price}`
5493
- };
5632
+ result.tp_trigger_price = OrderValidation.min(
5633
+ "tp_trigger_price",
5634
+ mark_price
5635
+ );
5494
5636
  }
5495
5637
  if (!!tp_trigger_price && Number(tp_trigger_price) > quote_max) {
5496
- result.tp_trigger_price = {
5497
- message: `TP price must be less than ${quote_max}`
5498
- };
5638
+ result.tp_trigger_price = OrderValidation.max(
5639
+ "tp_trigger_price",
5640
+ quote_max
5641
+ );
5499
5642
  }
5500
5643
  if (!!sl_trigger_price && Number(sl_trigger_price) < quote_min) {
5501
- result.sl_trigger_price = {
5502
- message: `TP price must be greater than ${quote_min}`
5503
- };
5644
+ result.sl_trigger_price = OrderValidation.min(
5645
+ "sl_trigger_price",
5646
+ quote_min
5647
+ );
5504
5648
  }
5505
5649
  }
5506
5650
  if (side === OrderSide.SELL && mark_price) {
5507
5651
  const slTriggerPriceScope = new Decimal(mark_price * (1 + price_scope)).toDecimalPlaces(quote_dp, Decimal.ROUND_DOWN).toNumber();
5508
5652
  if (!!sl_trigger_price && Number(sl_trigger_price) > slTriggerPriceScope) {
5509
- result.sl_trigger_price = {
5510
- message: `SL price must be less than ${slTriggerPriceScope}`
5511
- };
5653
+ result.sl_trigger_price = OrderValidation.max(
5654
+ "sl_trigger_price",
5655
+ slTriggerPriceScope
5656
+ );
5512
5657
  }
5513
5658
  if (!!tp_trigger_price && Number(tp_trigger_price) >= mark_price) {
5514
- result.tp_trigger_price = {
5515
- message: `TP price must be less than ${mark_price}`
5516
- };
5659
+ result.tp_trigger_price = OrderValidation.max(
5660
+ "tp_trigger_price",
5661
+ mark_price
5662
+ );
5517
5663
  }
5518
5664
  if (!!tp_trigger_price && Number(tp_trigger_price) > quote_max) {
5519
- result.tp_trigger_price = {
5520
- message: `TP price must be less than ${quote_max}`
5521
- };
5665
+ result.tp_trigger_price = OrderValidation.max(
5666
+ "tp_trigger_price",
5667
+ quote_max
5668
+ );
5522
5669
  }
5523
5670
  if (!!sl_trigger_price && Number(sl_trigger_price) < quote_min) {
5524
- result.sl_trigger_price = {
5525
- message: `TP price must be greater than ${quote_min}`
5526
- };
5671
+ result.sl_trigger_price = OrderValidation.min(
5672
+ "sl_trigger_price",
5673
+ quote_min
5674
+ );
5527
5675
  }
5528
5676
  }
5529
5677
  return Object.keys(result).length > 0 ? result : null;
@@ -5592,7 +5740,7 @@ var BBOOrderCreator = class extends BaseOrderCreator {
5592
5740
  let { order_quantity, order_price, reduce_only, level } = values2;
5593
5741
  const { symbol } = configs;
5594
5742
  const { min_notional, base_tick, quote_dp, quote_tick, base_dp } = symbol || {};
5595
- const notionalHintStr = checkNotional({
5743
+ const minNotional = getMinNotional({
5596
5744
  base_tick,
5597
5745
  quote_tick,
5598
5746
  price: order_price,
@@ -5601,10 +5749,11 @@ var BBOOrderCreator = class extends BaseOrderCreator {
5601
5749
  quote_dp,
5602
5750
  base_dp
5603
5751
  });
5604
- if (notionalHintStr !== void 0 && !reduce_only) {
5752
+ if (minNotional !== void 0 && !reduce_only) {
5605
5753
  errors.total = {
5606
5754
  type: "min",
5607
- message: notionalHintStr
5755
+ message: `The order value should be greater or equal to ${minNotional} USDC`,
5756
+ value: minNotional
5608
5757
  };
5609
5758
  }
5610
5759
  return errors;
@@ -5895,12 +6044,12 @@ var useSymbolLeverage = (symbol) => {
5895
6044
  return maxLeverage;
5896
6045
  };
5897
6046
  var AssetHistoryStatusEnum = /* @__PURE__ */ ((AssetHistoryStatusEnum2) => {
5898
- AssetHistoryStatusEnum2["NEW"] = "new";
5899
- AssetHistoryStatusEnum2["CONFIRM"] = "confirm";
5900
- AssetHistoryStatusEnum2["PROCESSING"] = "processing";
5901
- AssetHistoryStatusEnum2["COMPLETED"] = "completed";
5902
- AssetHistoryStatusEnum2["PENDDING"] = "pendding";
5903
- AssetHistoryStatusEnum2["PENDING_REBALANCE"] = "pending_rebalance";
6047
+ AssetHistoryStatusEnum2["NEW"] = "NEW";
6048
+ AssetHistoryStatusEnum2["CONFIRM"] = "CONFIRM";
6049
+ AssetHistoryStatusEnum2["PROCESSING"] = "PROCESSING";
6050
+ AssetHistoryStatusEnum2["COMPLETED"] = "COMPLETED";
6051
+ AssetHistoryStatusEnum2["FAILED"] = "FAILED";
6052
+ AssetHistoryStatusEnum2["PENDING_REBALANCE"] = "PENDING_REBALANCE";
5904
6053
  return AssetHistoryStatusEnum2;
5905
6054
  })(AssetHistoryStatusEnum || {});
5906
6055
  var useAssetsHistory = (options) => {
@@ -5951,7 +6100,7 @@ var useStatisticsDaily = (params, options) => {
5951
6100
  const { startDate, endDate, page = 1 } = params;
5952
6101
  const { ignoreAggregation = false } = options || {};
5953
6102
  if (!startDate || !endDate) {
5954
- throw new SDKError("startDate and endDate are required");
6103
+ throw new SDKError("Start date and end date are required");
5955
6104
  }
5956
6105
  const getPeriod = (startDate2, endDate2) => {
5957
6106
  if (startDate2 === endDate2) {
@@ -6097,11 +6246,14 @@ function useMaintenanceStatus() {
6097
6246
  const [startTime, setStartTime] = useState();
6098
6247
  const [endTime, setEndTime] = useState();
6099
6248
  const [brokerName, setBrokerName] = useState("Orderly network");
6100
- const { data: systemInfo, mutate: mutate3 } = useQuery(`/v1/public/system_info?source=maintenance`, {
6101
- revalidateOnFocus: false,
6102
- errorRetryCount: 2,
6103
- errorRetryInterval: 200
6104
- });
6249
+ const { data: systemInfo, mutate: mutate3 } = useQuery(
6250
+ `/v1/public/system_info?source=maintenance`,
6251
+ {
6252
+ revalidateOnFocus: false,
6253
+ errorRetryCount: 2,
6254
+ errorRetryInterval: 200
6255
+ }
6256
+ );
6105
6257
  const ws = useWS();
6106
6258
  const config = useConfig();
6107
6259
  useEffect(() => {
@@ -6540,7 +6692,7 @@ var ProxyConfigStore = class {
6540
6692
  (this._proxyConfigStore ?? this._originConfigStore).set(key, value);
6541
6693
  }
6542
6694
  clear() {
6543
- throw new Error("Method not implemented.");
6695
+ throw new SDKError("Method not implemented.");
6544
6696
  }
6545
6697
  getFromOrigin(key) {
6546
6698
  return this._originConfigStore.get(key);
@@ -6661,91 +6813,6 @@ var OrderlyConfigProvider = (props) => {
6661
6813
  }
6662
6814
  );
6663
6815
  };
6664
- var apiKeyMap = {
6665
- dev: "4d6b7db0fdd6e9de2b6a270414fd51e0",
6666
- qa: "96476b00bc2701360f9b480629ae5263",
6667
- staging: "dffc00e003479b86d410c448e00f2304",
6668
- prod: "3ab9ae56ed16cc57bc2ac97ffc1098c2"
6669
- };
6670
- var TrackerContext = createContext({});
6671
- var OrderlyTrackerProvider = ({ children }) => {
6672
- const listenKeys = Object.keys(TrackerListenerKeyMap);
6673
- const ee = useEventEmitter();
6674
- const env = useGetEnv();
6675
- const walletConnectRef = useRef(false);
6676
- const { account: account5, state } = useAccount();
6677
- const networkId = useConfig("networkId");
6678
- const brokerId = useConfig("brokerId");
6679
- const getChainInfo = useNetworkInfo(networkId);
6680
- const handleEvent = useCallback(
6681
- (key, params) => {
6682
- account5?.accountId && amplitude.setUserId(account5?.accountId);
6683
- if (key === EnumTrackerKeys.WALLET_CONNECT) {
6684
- if (walletConnectRef.current)
6685
- return;
6686
- const info = getChainInfo(
6687
- params?.connectWallet?.chainId
6688
- ).info;
6689
- const { address = "", connectWallet } = params;
6690
- const identify2 = {
6691
- address,
6692
- broker_id: brokerId,
6693
- sdk_version: window?.__ORDERLY_VERSION__?.["@orderly.network/net"] ?? ""
6694
- };
6695
- const identifyEvent = new amplitude.Identify();
6696
- Object.keys(identify2).map((subKey) => {
6697
- identifyEvent.set(subKey, identify2[subKey]);
6698
- });
6699
- amplitude.identify(identifyEvent);
6700
- const eventProperties = {
6701
- wallet: connectWallet?.name,
6702
- network: info?.network_infos?.name
6703
- };
6704
- amplitude.track(TrackerListenerKeyMap[key], eventProperties);
6705
- walletConnectRef.current = true;
6706
- return;
6707
- }
6708
- if (key === EnumTrackerKeys.SIGNIN_SUCCESS) {
6709
- const info = getChainInfo(
6710
- params?.connectWallet?.chainId
6711
- ).info;
6712
- amplitude.track(TrackerListenerKeyMap[key], {
6713
- wallet: params?.connectWallet?.name,
6714
- network: info?.network_infos?.name
6715
- });
6716
- return;
6717
- }
6718
- amplitude.track(TrackerListenerKeyMap[key], params);
6719
- },
6720
- [account5?.accountId, brokerId, state?.connectWallet?.name]
6721
- );
6722
- useEffect(() => {
6723
- amplitude.init(apiKeyMap[env], { serverZone: "EU" });
6724
- listenKeys.forEach((key) => {
6725
- ee.on(key, (params = {}) => {
6726
- setTimeout(() => {
6727
- handleEvent(key, params);
6728
- }, 2e3);
6729
- });
6730
- });
6731
- return () => {
6732
- listenKeys.forEach((key) => {
6733
- ee.off(key);
6734
- });
6735
- };
6736
- }, [env]);
6737
- return /* @__PURE__ */ jsx(
6738
- TrackerContext.Provider,
6739
- {
6740
- value: {
6741
- track: (key, params) => {
6742
- amplitude.track(key, params);
6743
- }
6744
- },
6745
- children
6746
- }
6747
- );
6748
- };
6749
6816
  var WalletConnectorContext = createContext({});
6750
6817
  var useWalletConnector = () => {
6751
6818
  return useContext(WalletConnectorContext);
@@ -6992,13 +7059,13 @@ function useOrderEntry(symbolOrOrder, sideOrOptions, reduceOnly, options) {
6992
7059
  if (typeof symbolOrOrder === "object") {
6993
7060
  isNewVersion = true;
6994
7061
  if (!symbolOrOrder.symbol) {
6995
- throw new SDKError("symbol is required");
7062
+ throw new SDKError("Symbol is required");
6996
7063
  }
6997
7064
  if (!symbolOrOrder.side) {
6998
7065
  throw new SDKError("Order side is required");
6999
7066
  }
7000
7067
  if (!symbolOrOrder.order_type) {
7001
- throw new SDKError("order_type is required");
7068
+ throw new SDKError("Order type is required");
7002
7069
  }
7003
7070
  }
7004
7071
  const prevOrderData = useRef(null);
@@ -7159,20 +7226,20 @@ function useOrderEntry(symbolOrOrder, sideOrOptions, reduceOnly, options) {
7159
7226
  );
7160
7227
  const createOrder = (values2) => {
7161
7228
  if (!values2.symbol) {
7162
- throw new SDKError("symbol is error");
7229
+ throw new SDKError("Symbol is error");
7163
7230
  }
7164
7231
  if (!values2.side) {
7165
- throw new SDKError("side is error");
7232
+ throw new SDKError("Order side is error");
7166
7233
  }
7167
7234
  if (!values2 || typeof values2.order_type === "undefined") {
7168
- throw new SDKError("order_type is error");
7235
+ throw new SDKError("Order type is error");
7169
7236
  }
7170
7237
  const orderCreator = OrderFactory.create(
7171
7238
  // @ts-ignore
7172
7239
  values2.order_type_ext ? values2.order_type_ext : values2.order_type
7173
7240
  );
7174
7241
  if (!orderCreator) {
7175
- return Promise.reject(new SDKError("orderCreator is null"));
7242
+ return Promise.reject(new SDKError("Order creator is null"));
7176
7243
  }
7177
7244
  return new Promise((resolve, reject) => {
7178
7245
  return orderCreator.validate(values2, {
@@ -14060,9 +14127,10 @@ var useOrderEntryNextInternal = (symbol, options = {}) => {
14060
14127
  };
14061
14128
  var useOrderEntry2 = (symbol, options = {}) => {
14062
14129
  if (!symbol) {
14063
- throw new SDKError("symbol is required and must be a string");
14130
+ throw new SDKError("Symbol is required");
14064
14131
  }
14065
14132
  const ee = useEventEmitter();
14133
+ const { track: track2 } = useTrack();
14066
14134
  const [meta, setMeta] = useState({
14067
14135
  dirty: {},
14068
14136
  submitted: false,
@@ -14214,28 +14282,30 @@ var useOrderEntry2 = (symbol, options = {}) => {
14214
14282
  return validate(order, creator, prepareData());
14215
14283
  }
14216
14284
  const validateOrder = () => {
14217
- return new Promise(async (resolve, reject) => {
14218
- const creator = getOrderCreator(formattedOrder);
14219
- const errors = await validate(formattedOrder, creator, prepareData());
14220
- const keys = Object.keys(errors);
14221
- if (keys.length > 0) {
14222
- setMeta(
14223
- produce((draft) => {
14224
- draft.errors = errors;
14225
- })
14226
- );
14227
- if (!meta.validated) {
14285
+ return new Promise(
14286
+ async (resolve, reject) => {
14287
+ const creator = getOrderCreator(formattedOrder);
14288
+ const errors = await validate(formattedOrder, creator, prepareData());
14289
+ const keys = Object.keys(errors);
14290
+ if (keys.length > 0) {
14228
14291
  setMeta(
14229
14292
  produce((draft) => {
14230
- draft.validated = true;
14293
+ draft.errors = errors;
14231
14294
  })
14232
14295
  );
14296
+ if (!meta.validated) {
14297
+ setMeta(
14298
+ produce((draft) => {
14299
+ draft.validated = true;
14300
+ })
14301
+ );
14302
+ }
14303
+ reject(errors);
14233
14304
  }
14234
- reject(errors);
14305
+ const order = generateOrder(creator, prepareData());
14306
+ resolve(order);
14235
14307
  }
14236
- const order = generateOrder(creator, prepareData());
14237
- resolve(order);
14238
- });
14308
+ );
14239
14309
  };
14240
14310
  const { freeCollateral, totalCollateral } = useCollateral();
14241
14311
  const estLiqPrice = useMemo(() => {
@@ -14302,12 +14372,12 @@ var useOrderEntry2 = (symbol, options = {}) => {
14302
14372
  draft.errors = errors;
14303
14373
  })
14304
14374
  );
14305
- throw new Error("Order validation failed");
14375
+ throw new SDKError("Order validation failed");
14306
14376
  }
14307
14377
  const order = generateOrder(creator, prepareData());
14308
14378
  const result = await doCreateOrder(order);
14309
14379
  if (result.success) {
14310
- ee.emit(EnumTrackerKeys.PLACEORDER_SUCCESS, {
14380
+ track2(EnumTrackerKeys.placeorderSuccess, {
14311
14381
  side: order.side,
14312
14382
  order_type: order.order_type,
14313
14383
  tp_sl: hasTPSL(formattedOrder),
@@ -14435,7 +14505,7 @@ var useOrderStore2 = create()(
14435
14505
  );
14436
14506
  var useOrderEntity = (order, options) => {
14437
14507
  if (!order.symbol) {
14438
- throw new SDKError("symbol is required");
14508
+ throw new SDKError("Symbol is required");
14439
14509
  }
14440
14510
  const [errors, setErrors] = useState();
14441
14511
  const maxQty = useMaxQty(order.symbol, order.side, order.reduce_only);
@@ -14450,27 +14520,29 @@ var useOrderEntity = (order, options) => {
14450
14520
  }, [finalMaxQty, order.symbol, order]);
14451
14521
  const symbolInfo = useSymbolsInfo();
14452
14522
  const validate = () => {
14453
- return new Promise(async (resolve, reject) => {
14454
- const creator = getOrderCreator(order);
14455
- const _symbol = symbolInfo[order.symbol]();
14456
- const errors2 = await creator?.validate(order, {
14457
- symbol: _symbol,
14458
- maxQty: finalMaxQty,
14459
- markPrice
14460
- });
14461
- const keys = Object.keys(errors2);
14462
- if (keys.length > 0) {
14463
- setErrors(errors2);
14464
- reject(errors2);
14465
- } else {
14466
- setErrors({});
14523
+ return new Promise(
14524
+ async (resolve, reject) => {
14525
+ const creator = getOrderCreator(order);
14526
+ const _symbol = symbolInfo[order.symbol]();
14527
+ const errors2 = await creator?.validate(order, {
14528
+ symbol: _symbol,
14529
+ maxQty: finalMaxQty,
14530
+ markPrice
14531
+ });
14532
+ const keys = Object.keys(errors2);
14533
+ if (keys.length > 0) {
14534
+ setErrors(errors2);
14535
+ reject(errors2);
14536
+ } else {
14537
+ setErrors({});
14538
+ }
14539
+ const orderEntity = creator.create(order, {
14540
+ ...prepareData(),
14541
+ symbol: _symbol
14542
+ });
14543
+ resolve(orderEntity);
14467
14544
  }
14468
- const orderEntity = creator.create(order, {
14469
- ...prepareData(),
14470
- symbol: _symbol
14471
- });
14472
- resolve(orderEntity);
14473
- });
14545
+ );
14474
14546
  };
14475
14547
  const autoCheck = useThrottledCallback(
14476
14548
  () => {
@@ -14559,6 +14631,6 @@ var useRestrictedInfo = (options) => {
14559
14631
  };
14560
14632
  };
14561
14633
 
14562
- export { AssetHistoryStatusEnum, DefaultLayoutConfig, DistributionId, ENVType2 as ENVType, ExtendedConfigStore, MarketsStorageKey, MarketsType, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, OrderlyTrackerProvider, StatusContext, StatusProvider, TWType, WalletConnectorContext, WsNetworkStatus, checkNotional, cleanStringStyle, parseJSON, useAccount, useAccountInfo2 as useAccountInfo, useAccountInstance, useAccountRewardsHistory, useAllBrokers, useApiKeyManager, useAssetsHistory, useBoolean, useChain, useChains, useCheckReferralCode, useCollateral, useCommission, useConfig, useCurEpochEstimate, useDaily, useDeposit, useDistribution, useDistributionHistory, useEpochInfo, useEventEmitter, useFundingFeeHistory, useFundingRate, useFundingRateHistory, useFundingRates, useGetClaimed, useGetEnv, useGetReferralCode, useHoldingStream, useIndexPrice, useKeyStore, useLazyQuery, useLeverage, useLocalStorage, useMaintenanceStatus, useMarginRatio, useMarkPrice, useMarkPriceBySymbol, useMarkPricesStream, useMarket, useMarketTradeStream, useMarkets, useMarketsStore, useMarketsStream, useMaxQty, useMediaQuery, useMutation, useNetworkInfo, useOrderEntity, useOrderEntry2 as useOrderEntry, useOrderEntry as useOrderEntry_deprecated, useOrderStore2 as useOrderStore, useOrderStream, useOrderbookStream, usePositionActions, usePositionStream, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, useRefereeHistory, useRefereeInfo, useRefereeRebateSummary, useReferralInfo, useReferralRebateSummary, useRestrictedInfo, useSessionStorage, useSettleSubscription, useSimpleDI, useStatisticsDaily, useStorageLedgerAddress, useSymbolLeverage, useSymbolPriceRange, useSymbolsInfo, useTPSLOrder, useTickerStream, useWS, useWalletConnector, useWalletRewardsHistory, useWalletSubscription, useWithdraw, useWsStatus, utils_exports as utils, version_default as version };
14634
+ export { AssetHistoryStatusEnum, DefaultLayoutConfig, DistributionId, ENVType2 as ENVType, ExtendedConfigStore, MarketsStorageKey, MarketsType, OrderlyConfigProvider, OrderlyContext, OrderlyProvider, StatusContext, StatusProvider, TWType, WalletConnectorContext, WsNetworkStatus, checkNotional, cleanStringStyle, getMinNotional, parseJSON, useAccount, useAccountInfo2 as useAccountInfo, useAccountInstance, useAccountRewardsHistory, useAllBrokers, useApiKeyManager, useAssetsHistory, useBoolean, useChain, useChains, useCheckReferralCode, useCollateral, useCommission, useConfig, useCurEpochEstimate, useDaily, useDeposit, useDistribution, useDistributionHistory, useEpochInfo, useEventEmitter, useFundingFeeHistory, useFundingRate, useFundingRateHistory, useFundingRates, useGetClaimed, useGetEnv, useGetReferralCode, useHoldingStream, useIndexPrice, useKeyStore, useLazyQuery, useLeverage, useLocalStorage, useMaintenanceStatus, useMarginRatio, useMarkPrice, useMarkPriceBySymbol, useMarkPricesStream, useMarket, useMarketTradeStream, useMarkets, useMarketsStore, useMarketsStream, useMaxQty, useMediaQuery, useMutation, useNetworkInfo, useOrderEntity, useOrderEntry2 as useOrderEntry, useOrderEntry as useOrderEntry_deprecated, useOrderStore2 as useOrderStore, useOrderStream, useOrderbookStream, usePositionActions, usePositionStream, usePoster, usePreLoadData, usePrivateDataObserver, usePrivateInfiniteQuery, usePrivateQuery, useQuery, useRefereeHistory, useRefereeInfo, useRefereeRebateSummary, useReferralInfo, useReferralRebateSummary, useRestrictedInfo, useSessionStorage, useSettleSubscription, useSimpleDI, useStatisticsDaily, useStorageChain, useStorageLedgerAddress, useSymbolLeverage, useSymbolPriceRange, useSymbolsInfo, useTPSLOrder, useTickerStream, useTrack, useTrackingInstance, useWS, useWalletConnector, useWalletRewardsHistory, useWalletSubscription, useWithdraw, useWsStatus, utils_exports as utils, version_default as version };
14563
14635
  //# sourceMappingURL=out.js.map
14564
14636
  //# sourceMappingURL=index.mjs.map