@kodiak-finance/orderly-react-app 2.7.4
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.d.mts +95 -0
- package/dist/index.d.ts +95 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +14 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +44 -0
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import react, { ReactNode, ComponentType, PropsWithChildren } from 'react';
|
|
2
|
+
import { ExtensionPosition, OrderlyThemeProviderProps } from '@kodiak-finance/orderly-ui';
|
|
3
|
+
import { ConfigProviderProps, ExclusiveConfigProviderProps, Chains, WalletState, RestrictedInfoReturns, RestrictedInfoOptions, OrderValidationResult } from '@kodiak-finance/orderly-hooks';
|
|
4
|
+
import { Chain, NetworkId, AccountStatusEnum } from '@kodiak-finance/orderly-types';
|
|
5
|
+
|
|
6
|
+
type Logo = {
|
|
7
|
+
img?: string;
|
|
8
|
+
component?: ReactNode;
|
|
9
|
+
className?: string;
|
|
10
|
+
};
|
|
11
|
+
type AppLogos = Partial<{
|
|
12
|
+
main: Logo;
|
|
13
|
+
secondary: Logo;
|
|
14
|
+
}>;
|
|
15
|
+
type OrderlyAppConfig = {
|
|
16
|
+
appIcons?: AppLogos;
|
|
17
|
+
dateFormatting?: string;
|
|
18
|
+
components?: {
|
|
19
|
+
[position in ExtensionPosition]: ComponentType;
|
|
20
|
+
};
|
|
21
|
+
} & Partial<Omit<ConfigProviderProps, "brokerId" | "brokerName" | "configStore" | "networkId">> & ExclusiveConfigProviderProps;
|
|
22
|
+
|
|
23
|
+
type ReturnChain = Pick<Chain, "id"> & Partial<Omit<Chain, "id">>;
|
|
24
|
+
type DefaultChain = {
|
|
25
|
+
mainnet?: ReturnChain;
|
|
26
|
+
testnet?: ReturnChain;
|
|
27
|
+
} | ((networkId: NetworkId, chains: Chains) => ReturnChain) | undefined;
|
|
28
|
+
|
|
29
|
+
declare const useWalletStateHandle: (options: {
|
|
30
|
+
currentChainId?: number;
|
|
31
|
+
}) => {
|
|
32
|
+
connectWallet: () => Promise<{
|
|
33
|
+
wallet?: WalletState;
|
|
34
|
+
status?: AccountStatusEnum;
|
|
35
|
+
wrongNetwork?: boolean;
|
|
36
|
+
} | null>;
|
|
37
|
+
wrongNetwork: boolean;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
type RouteOption = {
|
|
41
|
+
href: "/portfolio" | "/portfolio/history";
|
|
42
|
+
name: string;
|
|
43
|
+
};
|
|
44
|
+
type WidgetConfigs = {
|
|
45
|
+
scanQRCode?: {
|
|
46
|
+
onSuccess?: (url: string) => void;
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
type AppContextState = {
|
|
50
|
+
connectWallet: ReturnType<typeof useWalletStateHandle>["connectWallet"];
|
|
51
|
+
/**
|
|
52
|
+
* Whether the current network is not supported
|
|
53
|
+
*/
|
|
54
|
+
wrongNetwork: boolean;
|
|
55
|
+
disabledConnect: boolean;
|
|
56
|
+
currentChainId: number | undefined;
|
|
57
|
+
setCurrentChainId: (chainId: number | undefined) => void;
|
|
58
|
+
onChainChanged?: (chainId: number, state: {
|
|
59
|
+
isTestnet: boolean;
|
|
60
|
+
isWalletConnected: boolean;
|
|
61
|
+
}) => void;
|
|
62
|
+
restrictedInfo: RestrictedInfoReturns;
|
|
63
|
+
showAnnouncement: boolean;
|
|
64
|
+
setShowAnnouncement: (show: boolean) => void;
|
|
65
|
+
onRouteChange?: (option: RouteOption) => void;
|
|
66
|
+
widgetConfigs?: WidgetConfigs;
|
|
67
|
+
};
|
|
68
|
+
declare const useAppContext: () => AppContextState;
|
|
69
|
+
|
|
70
|
+
type AppStateProviderProps = {
|
|
71
|
+
defaultChain?: DefaultChain;
|
|
72
|
+
restrictedInfo?: RestrictedInfoOptions;
|
|
73
|
+
} & Pick<AppContextState, "onChainChanged" | "onRouteChange" | "widgetConfigs">;
|
|
74
|
+
|
|
75
|
+
type OrderlyAppProviderProps = PropsWithChildren<OrderlyAppConfig & AppStateProviderProps & OrderlyThemeProviderProps>;
|
|
76
|
+
declare const OrderlyAppProvider: react.FC<OrderlyAppProviderProps>;
|
|
77
|
+
|
|
78
|
+
type ThemeContextState = {
|
|
79
|
+
appIcons?: AppLogos;
|
|
80
|
+
brokerName: string;
|
|
81
|
+
};
|
|
82
|
+
declare const useAppConfig: () => ThemeContextState;
|
|
83
|
+
|
|
84
|
+
declare const useDataTap: <T = any>(data: T, options?: {
|
|
85
|
+
skip?: false;
|
|
86
|
+
fallbackData?: T;
|
|
87
|
+
accountStatus?: AccountStatusEnum;
|
|
88
|
+
}) => T | null;
|
|
89
|
+
|
|
90
|
+
type Keys = keyof OrderValidationResult;
|
|
91
|
+
declare function useOrderEntryFormErrorMsg(errors: OrderValidationResult | null): {
|
|
92
|
+
getErrorMsg: (key: Keys, customValue?: string) => string;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
export { type AppLogos, type AppStateProviderProps, OrderlyAppProvider, type OrderlyAppProviderProps, useAppConfig, useAppContext, useDataTap, useOrderEntryFormErrorMsg };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import react, { ReactNode, ComponentType, PropsWithChildren } from 'react';
|
|
2
|
+
import { ExtensionPosition, OrderlyThemeProviderProps } from '@kodiak-finance/orderly-ui';
|
|
3
|
+
import { ConfigProviderProps, ExclusiveConfigProviderProps, Chains, WalletState, RestrictedInfoReturns, RestrictedInfoOptions, OrderValidationResult } from '@kodiak-finance/orderly-hooks';
|
|
4
|
+
import { Chain, NetworkId, AccountStatusEnum } from '@kodiak-finance/orderly-types';
|
|
5
|
+
|
|
6
|
+
type Logo = {
|
|
7
|
+
img?: string;
|
|
8
|
+
component?: ReactNode;
|
|
9
|
+
className?: string;
|
|
10
|
+
};
|
|
11
|
+
type AppLogos = Partial<{
|
|
12
|
+
main: Logo;
|
|
13
|
+
secondary: Logo;
|
|
14
|
+
}>;
|
|
15
|
+
type OrderlyAppConfig = {
|
|
16
|
+
appIcons?: AppLogos;
|
|
17
|
+
dateFormatting?: string;
|
|
18
|
+
components?: {
|
|
19
|
+
[position in ExtensionPosition]: ComponentType;
|
|
20
|
+
};
|
|
21
|
+
} & Partial<Omit<ConfigProviderProps, "brokerId" | "brokerName" | "configStore" | "networkId">> & ExclusiveConfigProviderProps;
|
|
22
|
+
|
|
23
|
+
type ReturnChain = Pick<Chain, "id"> & Partial<Omit<Chain, "id">>;
|
|
24
|
+
type DefaultChain = {
|
|
25
|
+
mainnet?: ReturnChain;
|
|
26
|
+
testnet?: ReturnChain;
|
|
27
|
+
} | ((networkId: NetworkId, chains: Chains) => ReturnChain) | undefined;
|
|
28
|
+
|
|
29
|
+
declare const useWalletStateHandle: (options: {
|
|
30
|
+
currentChainId?: number;
|
|
31
|
+
}) => {
|
|
32
|
+
connectWallet: () => Promise<{
|
|
33
|
+
wallet?: WalletState;
|
|
34
|
+
status?: AccountStatusEnum;
|
|
35
|
+
wrongNetwork?: boolean;
|
|
36
|
+
} | null>;
|
|
37
|
+
wrongNetwork: boolean;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
type RouteOption = {
|
|
41
|
+
href: "/portfolio" | "/portfolio/history";
|
|
42
|
+
name: string;
|
|
43
|
+
};
|
|
44
|
+
type WidgetConfigs = {
|
|
45
|
+
scanQRCode?: {
|
|
46
|
+
onSuccess?: (url: string) => void;
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
type AppContextState = {
|
|
50
|
+
connectWallet: ReturnType<typeof useWalletStateHandle>["connectWallet"];
|
|
51
|
+
/**
|
|
52
|
+
* Whether the current network is not supported
|
|
53
|
+
*/
|
|
54
|
+
wrongNetwork: boolean;
|
|
55
|
+
disabledConnect: boolean;
|
|
56
|
+
currentChainId: number | undefined;
|
|
57
|
+
setCurrentChainId: (chainId: number | undefined) => void;
|
|
58
|
+
onChainChanged?: (chainId: number, state: {
|
|
59
|
+
isTestnet: boolean;
|
|
60
|
+
isWalletConnected: boolean;
|
|
61
|
+
}) => void;
|
|
62
|
+
restrictedInfo: RestrictedInfoReturns;
|
|
63
|
+
showAnnouncement: boolean;
|
|
64
|
+
setShowAnnouncement: (show: boolean) => void;
|
|
65
|
+
onRouteChange?: (option: RouteOption) => void;
|
|
66
|
+
widgetConfigs?: WidgetConfigs;
|
|
67
|
+
};
|
|
68
|
+
declare const useAppContext: () => AppContextState;
|
|
69
|
+
|
|
70
|
+
type AppStateProviderProps = {
|
|
71
|
+
defaultChain?: DefaultChain;
|
|
72
|
+
restrictedInfo?: RestrictedInfoOptions;
|
|
73
|
+
} & Pick<AppContextState, "onChainChanged" | "onRouteChange" | "widgetConfigs">;
|
|
74
|
+
|
|
75
|
+
type OrderlyAppProviderProps = PropsWithChildren<OrderlyAppConfig & AppStateProviderProps & OrderlyThemeProviderProps>;
|
|
76
|
+
declare const OrderlyAppProvider: react.FC<OrderlyAppProviderProps>;
|
|
77
|
+
|
|
78
|
+
type ThemeContextState = {
|
|
79
|
+
appIcons?: AppLogos;
|
|
80
|
+
brokerName: string;
|
|
81
|
+
};
|
|
82
|
+
declare const useAppConfig: () => ThemeContextState;
|
|
83
|
+
|
|
84
|
+
declare const useDataTap: <T = any>(data: T, options?: {
|
|
85
|
+
skip?: false;
|
|
86
|
+
fallbackData?: T;
|
|
87
|
+
accountStatus?: AccountStatusEnum;
|
|
88
|
+
}) => T | null;
|
|
89
|
+
|
|
90
|
+
type Keys = keyof OrderValidationResult;
|
|
91
|
+
declare function useOrderEntryFormErrorMsg(errors: OrderValidationResult | null): {
|
|
92
|
+
getErrorMsg: (key: Keys, customValue?: string) => string;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
export { type AppLogos, type AppStateProviderProps, OrderlyAppProvider, type OrderlyAppProviderProps, useAppConfig, useAppContext, useDataTap, useOrderEntryFormErrorMsg };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var orderlyHooks = require('@kodiak-finance/orderly-hooks');
|
|
4
|
+
var orderlyUi = require('@kodiak-finance/orderly-ui');
|
|
5
|
+
var react = require('react');
|
|
6
|
+
var orderlyTypes = require('@kodiak-finance/orderly-types');
|
|
7
|
+
var orderlyI18n = require('@kodiak-finance/orderly-i18n');
|
|
8
|
+
var orderlyUtils = require('@kodiak-finance/orderly-utils');
|
|
9
|
+
var jsxRuntime = require('react/jsx-runtime');
|
|
10
|
+
var locale = require('date-fns/locale');
|
|
11
|
+
|
|
12
|
+
var q=()=>{react.useEffect(()=>{let e=new URLSearchParams(window.location.search).get("ref");e&&localStorage.setItem("referral_code",e);},[]);};function ye(r){return r==="BUY"?orderlyI18n.i18n.t("common.buy"):r==="SELL"?orderlyI18n.i18n.t("common.sell"):orderlyUtils.capitalizeString(r)}function F(r,e){let {symbol:i,side:o,quantity:a,client_order_id:c,fieldChanges:d}=r,t="total_executed_quantity"in r?r.total_executed_quantity:0,l="status"in r?r.status:r.algo_status,s=e[i],n=s("base_dp");s("quote_dp");let u=ye(o),f=orderlyUtils.transSymbolformString(i),p="algo_type"in r&&r.algo_type===orderlyTypes.AlgoOrderRootType.POSITIONAL_TP_SL?orderlyI18n.i18n.t("tpsl.entirePosition"):n===void 0?a:orderlyUi.parseNumber(a,{dp:n}),m="",g="";switch(l){case orderlyTypes.OrderStatus.NEW:c?.startsWith("scaled_")?(m=orderlyI18n.i18n.t("orders.status.scaledSubOrderOpened.toast.title"),g=`${u} ${f} ${p}`):(m=orderlyI18n.i18n.t("orders.status.opened.toast.title"),g=`${u} ${f} ${p}`);break;case orderlyTypes.OrderStatus.FILLED:case orderlyTypes.OrderStatus.PARTIAL_FILLED:let w=n===void 0?t:orderlyUi.parseNumber(t,{dp:n});m=orderlyI18n.i18n.t("orders.status.filled.toast.title"),g=`${u} ${f} ${w} / ${p}`;break;case orderlyTypes.OrderStatus.CANCELLED:m=orderlyI18n.i18n.t("orders.status.canceled.toast.title"),g=`${u} ${f} ${p}`;break;case orderlyTypes.OrderStatus.REJECTED:m=orderlyI18n.i18n.t("orders.status.rejected.toast.title"),g=`${u} ${f} ${p}`;break;case orderlyTypes.OrderStatus.REPLACED:let{algo_type:I,activated_price:E}=r;if(I===orderlyTypes.AlgoOrderRootType.TRAILING_STOP){let b=d?.[orderlyTypes.AlgoOrderRootType.TRAILING_STOP]||{};b.is_activated&&b.extreme_price&&E?(m=orderlyI18n.i18n.t("orders.trailingStop.activated"),g=`${f} @${E}`):b.extreme_price&&(m="",g="");}else m=orderlyI18n.i18n.t("orders.status.replaced.toast.title"),g=`${o} ${f} ${t} / ${p}`;break;}return {title:m,msg:g,status:l}}var be="orderly_order_sound_alert",V=()=>{let r=orderlyHooks.useEventEmitter(),e=orderlyHooks.useSymbolsInfo(),i=react.useRef({}),{notification:o}=orderlyHooks.useOrderlyContext();react.useEffect(()=>{i.current=e;},[e]);let a=o?.orderFilled?.media??"",[c]=orderlyHooks.useLocalStorage(be,o?.orderFilled?.defaultOpen??false),[d]=orderlyHooks.useAudioPlayer(a,{autoPlay:c,volume:1}),t=orderlyHooks.useDebouncedCallback(l=>{(n=>{let{title:h,msg:u,status:f}=F(n,i.current),p=f===orderlyTypes.OrderStatus.FILLED||f===orderlyTypes.OrderStatus.PARTIAL_FILLED,m=n.algo_type||n.type;h&&u&&orderlyUi.toast.success(jsxRuntime.jsxs("div",{children:[h,jsxRuntime.jsx("br",{}),jsxRuntime.jsx("div",{className:"orderly-text-white/[0.54] orderly-text-xs",children:u}),p&&d]}),{id:m});})(l);},100);react.useEffect(()=>(r.on("orders:changed",t),()=>{r.off("orders:changed",t),t.cancel();}),[r,t]);};function Q(){let{t:r}=orderlyI18n.useTranslation(),e=orderlyI18n.useLocaleCode();return react.useMemo(()=>{let i={[orderlyI18n.LocaleEnum.en]:locale.enUS,[orderlyI18n.LocaleEnum.zh]:locale.zhCN};return {locale:e,dialog:{ok:r("common.ok"),cancel:r("common.cancel")},modal:{confirm:r("common.confirm"),cancel:r("common.cancel")},pagination:{morePages:r("ui.pagination.morePages"),rowsPerPage:r("ui.pagination.rowsPerPage")},picker:{selectDate:r("ui.picker.selectDate"),dayPicker:i[e]},empty:{description:r("ui.empty.description")}}},[r,e])}var _=react.createContext({}),De=()=>react.useContext(_);var z=r=>jsxRuntime.jsx(_.Provider,{value:r,children:r.children});var B=()=>{let r=orderlyHooks.useWS(),{t:e}=orderlyI18n.useTranslation();react.useEffect(()=>{let i=r.privateSubscribe({id:"assetconvert",event:"subscribe",topic:"assetconvert",ts:orderlyUtils.getTimestamp()},{onMessage(o){o.convertId&&orderlyUi.toast.success(e("transfer.convert.completed"));}});return ()=>i()},[]);};function J(r){let{storageChain:e,setStorageChain:i}=orderlyHooks.useStorageChain(),[o,a]=react.useState(),[c]=orderlyHooks.useChains(),d=orderlyHooks.useConfig("networkId"),{connectedChain:t}=orderlyHooks.useWalletConnector();return react.useEffect(()=>{if(t)a?.(typeof t.id=="number"?t.id:parseInt(t.id));else {if(o)return;let l,s=d==="mainnet"?c.mainnet?.[0]:c.testnet?.[0];typeof r=="function"?l=r(d,c):typeof r=="object"&&(l=d==="mainnet"?r?.mainnet:r?.testnet);let n=l?.id||s?.network_infos?.chain_id;if(!n)return;e?a?.(e.chainId):(i(n),a?.(n));}},[t,c,o,d,a,r]),[o,a]}var Y="orderly:wallet-info";function G(){let{connectedChain:r,disconnect:e}=orderlyHooks.useWalletConnector(),[i,o]=orderlyHooks.useLocalStorage("orderly_link_device",{}),{account:a}=orderlyHooks.useAccount(),{isMobile:c}=orderlyUi.useScreen(),d=orderlyHooks.useConfig(),t=async n=>{localStorage.removeItem(Y),await a.disconnect(),await e({label:n});};react.useEffect(()=>{let n=k(),h=JSON.parse(localStorage.getItem(Y)??"{}");n&&h&&t(h.label);},[]);let l=async()=>{let n=k();if(!n)return;let{address:h,secretKey:u,chainId:f,chainNamespace:p}=n;if(!await a.importOrderlyKey({address:h,secretKey:u,chainNamespace:p}))return;o({chainId:f,chainNamespace:p});let g=new URL(window.location.href);g.searchParams.delete("link"),g.searchParams.set("utm_medium","qrcode");let x=decodeURIComponent(g.toString());history.replaceState(null,"",x);};react.useEffect(()=>{c&&!r&&l();},[a,r,c]);let s=async()=>{let{chainId:n,chainNamespace:h}=Ze()||{};if(c&&!r&&n&&h){let u=a.keyStore.getAddress(),f=a.keyStore.getOrderlyKey(),p=a.keyStore.getAccountId(u);await a.checkOrderlyKey(u,f,p)&&d.set("chainNamespace",h);}};return react.useEffect(()=>{s();},[a,c,r]),{linkDevice:l}}function Ze(){try{let r=localStorage.getItem("orderly_link_device");return r?orderlyHooks.parseJSON(r):null}catch{}}function k(){let e=new URL(window.location.href).searchParams.get("link");if(!e)return;let{a:i,k:o,i:a,n:c}=er(e)||{};if(i&&o&&a&&c)return {address:i,secretKey:o,chainId:a,chainNamespace:c}}function er(r){try{let e=JSON.parse(window.atob(r)),i=Math.floor(Date.now()/1e3),o=e.t;return !o||i>o?void 0:e}catch{}}function X(){let{t:r}=orderlyI18n.useTranslation();orderlyHooks.useSettleSubscription({onMessage:e=>{let{status:i}=e;switch(i){case "COMPLETED":orderlyUi.toast.success(r("settle.settlement.completed"));break;case "FAILED":orderlyUi.toast.error(r("settle.settlement.failed"));break;}}});}function ee(){let{t:r}=orderlyI18n.useTranslation(),e=orderlyHooks.useEventEmitter(),{setLedgerAddress:i}=orderlyHooks.useStorageLedgerAddress();return react.useEffect(()=>{e.on("wallet:connect-error",o=>{orderlyUi.toast.error(o.message);}),e.on("wallet:sign-message-with-ledger-error",o=>{window.setTimeout(()=>{orderlyUi.modal.confirm({title:r("connector.ledger.signMessageFailed"),content:r("connector.ledger.signMessageFailed.description"),size:"sm",onOk:async()=>(i(o.userAddress),Promise.resolve()),okLabel:r("common.ok"),onCancel:async()=>(orderlyUi.toast.error(o.message),Promise.resolve()),cancelLabel:r("common.no")}).then(a=>{});});});},[e,r]),{}}function oe(){let{t:r}=orderlyI18n.useTranslation(),e=orderlyHooks.useEventEmitter(),i=react.useRef({}),[o,a]=orderlyHooks.useSessionStorage("orderly_wallet_change_id",{});i.current=o,orderlyHooks.useWalletSubscription({onMessage:c=>{let{id:d,side:t,transStatus:l}=c,s=true;if(["DEPOSIT","WITHDRAW"].includes(t)&&["COMPLETED","FAILED"].includes(l)){let n=!!i.current[d];n||(i.current[d]=true,a(h=>({...h,[d]:true}))),s=!n;}if(l==="COMPLETED"&&s){let n=`${orderlyUtils.capitalizeString(t)} completed`;t==="DEPOSIT"?n=r("transfer.deposit.completed"):t==="WITHDRAW"&&(n=r("transfer.withdraw.completed")),orderlyUi.toast.success(n);}else if(l==="FAILED"&&s){let n=`${orderlyUtils.capitalizeString(t)} failed`;t==="DEPOSIT"?n=r("transfer.deposit.failed"):t==="WITHDRAW"&&(n=r("transfer.withdraw.failed")),orderlyUi.toast.error(n);}e.emit("wallet:changed",c);}});}var ce="orderly:wallet-info";var de=r=>{let{wallet:e,connect:i,connectedChain:o,disconnect:a,namespace:c}=orderlyHooks.useWalletConnector();if(typeof i!="function")throw new orderlyTypes.SDKError("Please provide a wallet connector provider");orderlyHooks.useEventEmitter();let t=react.useRef(false);orderlyHooks.useConfig("brokerId");let {account:s,state:n}=orderlyHooks.useAccount(),h=orderlyHooks.useKeyStore(),u=orderlyHooks.useConfig("networkId"),[f,{checkChainSupport:p}]=orderlyHooks.useChains(),[m,g]=react.useState(false),{track:x,setTrackUserId:w}=orderlyHooks.useTrack(),I=react.useMemo(()=>e?.accounts?.[0]?.address,[e]),E=react.useMemo(()=>{let y=e?.chains?.[0]?.id,C=e?.chains?.[0]?.namespace;if(!(typeof y>"u"))return {id:orderlyUtils.parseChainIdToNumber(y),namespace:C}},[e]);return react.useEffect(()=>{n.status>=orderlyTypes.AccountStatusEnum.EnableTrading&&s.accountId&&w(s.accountId);},[s,n]),react.useEffect(()=>{if(!o){g(false);return}let y=p(o.id,u);orderlyTypes.ABSTRACT_CHAIN_ID_MAP.has(parseInt(o.id))&&e?.label!=="AGW"&&(y=false),g(!y);},[o,f,p,u,e]),react.useEffect(()=>{orderlyUtils.windowGuard(()=>{let y=h.getAddress(),C=JSON.parse(localStorage.getItem(ce)??"{}");o?.namespace!==orderlyTypes.ChainNamespace.solana&&y&&s.address!==y&&C.label&&i({autoSelect:{label:C.label,disableModals:true}}).then(T=>{},T=>{});});},[e,s.address]),react.useEffect(()=>{if(e===null&&n.status>orderlyTypes.AccountStatusEnum.NotConnected&&!n.validating){s.disconnect();return}if(m||!o||t.current)return;let y=k();I&&I!==s.address&&!y&&(s.setAddress(I,{provider:e?.provider,chain:{id:orderlyUtils.praseChainIdToNumber(E.id),namespace:E.namespace.toUpperCase()},wallet:{name:e?.label??""},additionalInfo:e?.additionalInfo??{}}),x(orderlyTypes.TrackerEventName.walletConnect,{wallet:e?.label??"",network:E.namespace.toUpperCase()}),orderlyUtils.windowGuard(()=>{localStorage.setItem(ce,JSON.stringify({label:e?.label??""}));})),E?.id!==s.chainId&&s.switchChainId(E?.id);},[e,o,I,E,s.address,n,s.chainId,m]),{connectWallet:async()=>(t.current=true,i({chainId:r.currentChainId}).then(async y=>{if(Array.isArray(y)&&y.length>0&&y[0]&&y[0].accounts.length>0){let C=y[0],T=orderlyUtils.praseChainIdToNumber(C.chains[0].id);if(!p(T,u))return {wrongNetwork:true};if(!s)throw new Error("account is not initialized");n.status===orderlyTypes.AccountStatusEnum.EnableTradingWithoutConnected&&(localStorage.removeItem("orderly_link_device"),await s.disconnect());let pe=await s.setAddress(C.accounts[0].address,{provider:C.provider,chain:{id:orderlyUtils.praseChainIdToNumber(C.chains[0].id),namespace:C.chains[0].namespace.toUpperCase()},wallet:{name:C.label}});return x(orderlyTypes.TrackerEventName.walletConnect,{wallet:C.label,network:C.chains[0].namespace.toUpperCase()}),{wallet:C,status:pe,wrongNetwork:false}}return null}).finally(()=>{t.current=false;})),wrongNetwork:m}};var N=react.createContext({setCurrentChainId:r=>{},restrictedInfo:{},setShowAnnouncement:r=>{}}),W=()=>react.useContext(N);var le=r=>{let[e,i]=react.useState(false),[o,a]=J(r.defaultChain);G(),orderlyHooks.useTrackingInstance();let{connectWallet:c,wrongNetwork:d}=de({currentChainId:o});oe(),X(),B(),ee();let t=orderlyHooks.useRestrictedInfo(r.restrictedInfo),l=t.restrictedOpen,s=react.useMemo(()=>({connectWallet:c,wrongNetwork:d,currentChainId:o,setCurrentChainId:a,onChainChanged:r.onChainChanged,disabledConnect:l,restrictedInfo:t,showAnnouncement:e,setShowAnnouncement:i,onRouteChange:r.onRouteChange,widgetConfigs:r.widgetConfigs}),[c,o,l,r.onChainChanged,t,a,e,d,r.onRouteChange,r.widgetConfigs]);return jsxRuntime.jsx(N.Provider,{value:s,children:r.children})};var Fr=()=>(V(),null),ue=r=>{let{components:e,appIcons:i,onChainChanged:o,defaultChain:a,widgetConfigs:c,...d}=r;orderlyHooks.useTrack(),q();let t=Q();return jsxRuntime.jsx(z,{appIcons:i,brokerName:r.brokerName,children:jsxRuntime.jsx(orderlyUi.OrderlyThemeProvider,{components:e,overrides:r.overrides,children:jsxRuntime.jsxs(orderlyHooks.OrderlyConfigProvider,{...d,children:[jsxRuntime.jsx(Fr,{}),jsxRuntime.jsx(le,{onChainChanged:o,defaultChain:a,restrictedInfo:r.restrictedInfo,onRouteChange:r.onRouteChange,widgetConfigs:c,children:jsxRuntime.jsx(orderlyUi.LocaleProvider,{locale:t,children:jsxRuntime.jsx(orderlyUi.TooltipProvider,{delayDuration:300,children:jsxRuntime.jsx(orderlyUi.ModalProvider,{children:r.children})})})}),jsxRuntime.jsx(orderlyUi.Toaster,{})]})})})};process.env.NODE_ENV!=="production"&&(ue.displayName="OrderlyAppProvider");var Kr=(r,e)=>{let{wrongNetwork:i,disabledConnect:o}=W(),{state:a}=orderlyHooks.useAccount();return e?.skip?r:i||o||typeof e?.accountStatus<"u"&&a.status<e.accountStatus?typeof e?.fallbackData<"u"?e.fallbackData:null:r};function Qr(r){let{t:e}=orderlyI18n.useTranslation(),i=(a,c,d)=>{let{value:t,min:l,max:s}=d||{};return {quantity:{required:e("orderEntry.orderQuantity.error.required"),min:e("orderEntry.orderQuantity.error.min",{value:t}),max:e("orderEntry.orderQuantity.error.max",{value:t})},order_quantity:{required:e("orderEntry.orderQuantity.error.required"),min:e("orderEntry.orderQuantity.error.min",{value:t}),max:e("orderEntry.orderQuantity.error.max",{value:t})},order_price:{required:e("orderEntry.orderPrice.error.required"),min:e("orderEntry.orderPrice.error.min",{value:t}),max:e("orderEntry.orderPrice.error.max",{value:t})},trigger_price:{required:e("orderEntry.triggerPrice.error.required"),min:e("orderEntry.triggerPrice.error.min",{value:t}),max:e("orderEntry.triggerPrice.error.max",{value:t})},tp_trigger_price:{required:e("tpsl.validate.tpTriggerPrice.error.required"),min:e("orderEntry.tpTriggerPrice.error.min",{value:t}),max:e("orderEntry.tpTriggerPrice.error.max",{value:t}),priceErrorMin:e("tpsl.validate.tpTriggerPrice.error.priceErrorMin"),priceErrorMax:e("tpsl.validate.tpTriggerPrice.error.priceErrorMax")},sl_trigger_price:{required:e("tpsl.validate.slTriggerPrice.error.required"),min:e("orderEntry.slTriggerPrice.error.min",{value:t}),max:e("orderEntry.slTriggerPrice.error.max",{value:t}),priceErrorMin:e("tpsl.validate.slTriggerPrice.error.priceErrorMin"),priceErrorMax:e("tpsl.validate.slTriggerPrice.error.priceErrorMax")},tp_order_price:{required:e("tpsl.validate.tpOrderPrice.error.required"),min:e("tpsl.validate.tpOrderPrice.error.min",{value:t}),max:e("tpsl.validate.tpOrderPrice.error.max",{value:t})},sl_order_price:{required:e("tpsl.validate.slOrderPrice.error.required"),min:e("tpsl.validate.slOrderPrice.error.min",{value:t}),max:e("tpsl.validate.slOrderPrice.error.max",{value:t})},total:{min:e("orderEntry.total.error.min",{value:t})},start_price:{required:e("orderEntry.startPrice.error.required"),min:e("orderEntry.startPrice.error.min",{value:t}),max:e("orderEntry.startPrice.error.max",{value:t})},end_price:{required:e("orderEntry.endPrice.error.required"),min:e("orderEntry.endPrice.error.min",{value:t}),max:e("orderEntry.endPrice.error.max",{value:t})},total_orders:{required:e("orderEntry.totalOrders.error.required"),range:e("orderEntry.totalOrders.error.range")},skew:{required:e("orderEntry.skew.error.required"),min:e("orderEntry.skew.error.min",{value:t}),max:e("orderEntry.skew.error.max",{value:t})},activated_price:{min:e("orderEntry.triggerPrice.error.min",{value:t}),max:e("orderEntry.triggerPrice.error.max",{value:t})},callback_value:{required:e("orderEntry.callbackValue.error.required"),min:e("orderEntry.callbackValue.error.min",{value:t}),range:e("orderEntry.callbackValue.error.range",{min:l,max:s})},callback_rate:{required:e("orderEntry.callbackRate.error.required"),range:e("orderEntry.callbackRate.error.range",{min:l,max:s})}}[a]?.[c]||""};return {getErrorMsg:react.useCallback((a,c)=>{let{type:d,value:t,min:l,max:s}=r?.[a]||{};return d?i(a,d,{value:c||t,min:l,max:s}):""},[r])}}
|
|
13
|
+
|
|
14
|
+
exports.OrderlyAppProvider = ue;
|
|
15
|
+
exports.useAppConfig = De;
|
|
16
|
+
exports.useAppContext = W;
|
|
17
|
+
exports.useDataTap = Kr;
|
|
18
|
+
exports.useOrderEntryFormErrorMsg = Qr;
|
|
19
|
+
//# sourceMappingURL=out.js.map
|
|
20
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider/orderlyAppProvider.tsx","../src/hooks/useBootstrap.ts","../src/hooks/useExecutionReport.tsx","../src/hooks/getOrderExecutionReportMsg.ts","../src/hooks/useUILocale.ts","../src/provider/appConfigContext.tsx","../src/provider/appConfigProvider.tsx","../src/provider/appStateProvider.tsx","../src/hooks/useAssetconvertEvent.ts","../src/hooks/useCurrentChainId.ts","../src/hooks/useLinkDevice.ts","../src/hooks/useSettleEvent.ts","../src/hooks/useWalletConnectError.ts","../src/hooks/useWalletEvent.ts","../src/hooks/useWalletStateHandle.ts","../src/provider/appStateContext.tsx","../src/hooks/useDataTap.ts","../src/common/useOrderEntryFormErrorMsg.ts"],"names":["OrderlyConfigProvider","useTrack","UILocaleProvider","ModalProvider","OrderlyThemeProvider","Toaster","TooltipProvider","useEffect","useBootstrap","refCode","useRef","useSymbolsInfo","useEventEmitter","useDebouncedCallback","useAudioPlayer","useLocalStorage","useOrderlyContext","OrderStatus","toast","i18n","AlgoOrderRootType","parseNumber","capitalizeString","transSymbolformString","getDisplaySide","side","getOrderExecutionReportMsg","data","symbolsInfo","symbol","quantity","client_order_id","fieldChanges","total_executed_quantity","status","getSymbolInfo","base_dp","quote_dp","displaySide","displaySymbol","displayQuantity","title","msg","displayTotalExecutedQuantity","algo_type","activated_price","fieldChange","jsx","jsxs","ORDERLY_ORDER_SOUND_ALERT_KEY","useExecutionReport","ee","symbolsInfoRef","notification","src","soundAutoPlay","audioElement","handler","isFilled","orderType","useMemo","useTranslation","useLocaleCode","LocaleEnum","enUS","zhCN","useUILocale","t","localeCode","calendarLocale","createContext","useContext","AppConfigContext","useAppConfig","AppConfigProvider","props","useState","useRestrictedInfo","useTrackingInstance","useWS","getTimestamp","useAssetconvertEvent","ws","unsubscribe","useChains","useConfig","useStorageChain","useWalletConnector","useCurrentChainId","defaultChain","storageChain","setStorageChain","currentChainId","setCurrentChainId","chains","networkId","connectedChain","fallbackChain","firstChain","chainId","parseJSON","useAccount","useScreen","WALLET_KEY","useLinkDevice","disconnect","_","setLinkDeviceStorage","account","isMobile","configStore","onDisconnect","label","linkData","getLinkDeviceData","walletInfo","linkDevice","address","secretKey","chainNamespace","url","decodedUrl","autoLinkDevice","getLinkDeviceStorage","orderlyKey","accountId","linkDeviceStorage","link","decodeBase64","base64","currentTime","expiredTime","useSettleSubscription","useSettleEvent","modal","useStorageLedgerAddress","useWalletConnectError","setLedgerAddress","res","useSessionStorage","useWalletSubscription","useWalletEvent","recordRef","record","setRecord","id","transStatus","showToast","isPushed","prev","useKeyStore","AccountStatusEnum","SDKError","ChainNamespace","TrackerEventName","ABSTRACT_CHAIN_ID_MAP","parseChainIdToNumber","praseChainIdToNumber","windowGuard","useWalletStateHandle","options","connectedWallet","connect","namespace","isManualConnect","brokerId","accountState","keyStore","checkChainSupport","unsupported","setUnsupported","track","setTrackUserId","currentWalletAddress","currentChain","isSupported","localAddress","error","walletState","wallet","AppStateContext","show","useAppContext","AppStateProvider","showAnnouncement","setShowAnnouncement","connectWallet","wrongNetwork","restrictedInfo","disabledConnect","memoizedValue","ExecutionReportListener","OrderlyAppProvider","components","appIcons","onChainChanged","widgetConfigs","configProps","uiLocale","useDataTap","state","useCallback","useOrderEntryFormErrorMsg","errors","getMessage","key","type","params","value","min","max","customValue"],"mappings":"AACA,OAAS,yBAAAA,GAAuB,YAAAC,OAAgB,gCAChD,OACE,kBAAkBC,GAClB,iBAAAC,GACA,wBAAAC,GACA,WAAAC,GACA,mBAAAC,OACK,6BCRP,OAAS,aAAAC,OAAiB,QAEnB,IAAMC,EAAe,IAAM,CAChCD,GAAU,IAAM,CAEd,IAAME,EADe,IAAI,gBAAgB,OAAO,SAAS,MAAM,EAClC,IAAI,KAAK,EAClCA,GACF,aAAa,QAAQ,gBAAiBA,CAAO,CAEjD,EAAG,CAAC,CAAC,CACP,ECTA,OAAS,aAAAF,EAAW,UAAAG,OAAc,QAClC,OACE,kBAAAC,GACA,mBAAAC,GACA,wBAAAC,GACA,kBAAAC,GACA,mBAAAC,GACA,qBAAAC,OACK,gCACP,OAAS,eAAAC,MAAmB,gCAC5B,OAAS,SAAAC,OAAa,6BCXtB,OAAS,QAAAC,MAAY,+BACrB,OAAc,eAAAF,MAA8B,gCAC5C,OAAS,qBAAAG,MAAyB,gCAClC,OAAS,eAAAC,MAAmB,6BAC5B,OACE,oBAAAC,GACA,yBAAAC,OACK,gCAEP,SAASC,GAAeC,EAAc,CACpC,OAAIA,IAAS,MACJN,EAAK,EAAE,YAAY,EACjBM,IAAS,OACXN,EAAK,EAAE,aAAa,EAEtBG,GAAiBG,CAAI,CAC9B,CAMO,SAASC,EACdC,EAGAC,EACA,CACA,GAAM,CAAE,OAAAC,EAAQ,KAAAJ,E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,EAAE,gCAAgC,EAC5C,IAAKA,EAAE,4BAA6B,CAAE,MAAA6I,CAAM,CAAC,EAC7C,IAAK7I,EAAE,4BAA6B,CAAE,MAAA6I,CAAM,CAAC,CAC/C,EACA,gBAAiB,CACf,IAAK7I,EAAE,oCAAqC,CAAE,MAAA6I,CAAM,CAAC,EACrD,IAAK7I,EAAE,oCAAqC,CAAE,MAAA6I,CAAM,CAAC,CACvD,EACA,eAAgB,CACd,SAAU7I,EAAE,yCAAyC,EACrD,IAAKA,EAAE,qCAAsC,CAAE,MAAA6I,CAAM,CAAC,EACtD,MAAO7I,EAAE,uCAAwC,CAC/C,IAAA8I,EACA,IAAAC,CACF,CAAC,CACH,EACA,cAAe,CACb,SAAU/I,EAAE,wCAAwC,EACpD,MAAOA,EAAE,sCAAuC,CAC9C,IAAA8I,EACA,IAAAC,CACF,CAAC,CACH,CACF,EAEWL,CAAG,IAAIC,CAAI,GAAK,EAC7B,EAaA,MAAO,CACL,YAZkBL,GAClB,CAACI,EAAWM,IAAyB,CACnC,GAAM,CAAE,KAAAL,EAAM,MAAAE,EAAO,IAAAC,EAAK,IAAAC,CAAI,EAAIP,IAASE,CAAG,GAAM,CAAC,EACrD,OAAIC,EACKF,EAAWC,EAAKC,EAAM,CAAE,MAAOK,GAAeH,EAAO,IAAAC,EAAK,IAAAC,CAAI,CAAC,EAEjE,EACT,EACA,CAACP,CAAM,CACT,CAIA,CACF","sourcesContent":["import React, { PropsWithChildren } from \"react\";\nimport { OrderlyConfigProvider, useTrack } from \"@kodiak-finance/orderly-hooks\";\nimport {\n LocaleProvider as UILocaleProvider,\n ModalProvider,\n OrderlyThemeProvider,\n Toaster,\n TooltipProvider,\n} from \"@kodiak-finance/orderly-ui\";\nimport { OrderlyThemeProviderProps } from \"@kodiak-finance/orderly-ui\";\nimport { useBootstrap } from \"../hooks/useBootstrap\";\nimport { useExecutionReport } from \"../hooks/useExecutionReport\";\nimport { useUILocale } from \"../hooks/useUILocale\";\nimport { OrderlyAppConfig } from \"../types\";\nimport { AppConfigProvider } from \"./appConfigProvider\";\nimport { AppStateProvider, AppStateProviderProps } from \"./appStateProvider\";\n\nexport type OrderlyAppProviderProps = PropsWithChildren<\n OrderlyAppConfig & AppStateProviderProps & OrderlyThemeProviderProps\n>;\n\n// Cannot be called outside of Provider because useExecutionReport requires useOrderlyContext.\nconst ExecutionReportListener: React.FC = () => {\n useExecutionReport();\n return null;\n};\n\nconst OrderlyAppProvider: React.FC<OrderlyAppProviderProps> = (props) => {\n const {\n // dateFormatting,\n components,\n appIcons,\n onChainChanged,\n defaultChain,\n widgetConfigs,\n ...configProps\n } = props;\n\n useTrack();\n useBootstrap();\n\n const uiLocale = useUILocale();\n\n return (\n <AppConfigProvider appIcons={appIcons} brokerName={props.brokerName!}>\n <OrderlyThemeProvider\n // dateFormatting={dateFormatting}\n components={components}\n overrides={props.overrides}\n >\n <OrderlyConfigProvider {...configProps}>\n <ExecutionReportListener />\n <AppStateProvider\n onChainChanged={onChainChanged}\n defaultChain={defaultChain}\n restrictedInfo={props.restrictedInfo}\n onRouteChange={props.onRouteChange}\n widgetConfigs={widgetConfigs}\n >\n <UILocaleProvider locale={uiLocale}>\n <TooltipProvider delayDuration={300}>\n <ModalProvider>{props.children}</ModalProvider>\n </TooltipProvider>\n </UILocaleProvider>\n </AppStateProvider>\n <Toaster />\n </OrderlyConfigProvider>\n </OrderlyThemeProvider>\n </AppConfigProvider>\n );\n};\n\nif (process.env.NODE_ENV !== \"production\") {\n OrderlyAppProvider.displayName = \"OrderlyAppProvider\";\n}\n\nexport { OrderlyAppProvider };\n","import { useEffect } from \"react\";\n\nexport const useBootstrap = () => {\n useEffect(() => {\n const searchParams = new URLSearchParams(window.location.search);\n const refCode = searchParams.get(\"ref\");\n if (refCode) {\n localStorage.setItem(\"referral_code\", refCode);\n }\n }, []);\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { useEffect, useRef } from \"react\";\nimport {\n useSymbolsInfo,\n useEventEmitter,\n useDebouncedCallback,\n useAudioPlayer,\n useLocalStorage,\n useOrderlyContext,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { OrderStatus } from \"@kodiak-finance/orderly-types\";\nimport { toast } from \"@kodiak-finance/orderly-ui\";\nimport { getOrderExecutionReportMsg } from \"./getOrderExecutionReportMsg\";\n\nexport const ORDERLY_ORDER_SOUND_ALERT_KEY = \"orderly_order_sound_alert\";\n\nexport const useExecutionReport = () => {\n const ee = useEventEmitter();\n\n const symbolsInfo = useSymbolsInfo();\n const symbolsInfoRef = useRef({});\n\n const { notification } = useOrderlyContext();\n\n useEffect(() => {\n symbolsInfoRef.current = symbolsInfo;\n }, [symbolsInfo]);\n\n const src = notification?.orderFilled?.media ?? \"\";\n\n const [soundAutoPlay] = useLocalStorage<boolean>(\n ORDERLY_ORDER_SOUND_ALERT_KEY,\n notification?.orderFilled?.defaultOpen ?? false,\n );\n\n const [audioElement] = useAudioPlayer(src, {\n autoPlay: soundAutoPlay,\n volume: 1,\n });\n\n const handler = useDebouncedCallback((data: any) => {\n const showToast = (data: any) => {\n const { title, msg, status } = getOrderExecutionReportMsg(\n data,\n symbolsInfoRef.current,\n );\n const isFilled =\n status === OrderStatus.FILLED || status === OrderStatus.PARTIAL_FILLED;\n // only show latest msg for same order type\n const orderType = data.algo_type || data.type;\n if (title && msg) {\n toast.success(\n <div>\n {title}\n <br />\n <div className=\"orderly-text-white/[0.54] orderly-text-xs\">\n {msg}\n </div>\n {isFilled && audioElement}\n </div>,\n { id: orderType },\n );\n }\n };\n showToast(data);\n }, 100);\n\n useEffect(() => {\n ee.on(\"orders:changed\", handler);\n return () => {\n ee.off(\"orders:changed\", handler);\n handler.cancel();\n };\n }, [ee, handler]);\n};\n","import { i18n } from \"@kodiak-finance/orderly-i18n\";\nimport { API, OrderStatus, OrderType } from \"@kodiak-finance/orderly-types\";\nimport { AlgoOrderRootType } from \"@kodiak-finance/orderly-types\";\nimport { parseNumber } from \"@kodiak-finance/orderly-ui\";\nimport {\n capitalizeString,\n transSymbolformString,\n} from \"@kodiak-finance/orderly-utils\";\n\nfunction getDisplaySide(side: string) {\n if (side === \"BUY\") {\n return i18n.t(\"common.buy\");\n } else if (side === \"SELL\") {\n return i18n.t(\"common.sell\");\n }\n return capitalizeString(side);\n}\n\ntype AlgoOrderFieldChanges = Partial<\n Record<OrderType, Partial<Record<keyof API.AlgoOrder, boolean>>>\n>;\n\nexport function getOrderExecutionReportMsg(\n data: (API.AlgoOrder | API.Order) & {\n fieldChanges?: AlgoOrderFieldChanges;\n },\n symbolsInfo: any,\n) {\n const { symbol, side, quantity, client_order_id, fieldChanges } = data;\n const total_executed_quantity =\n \"total_executed_quantity\" in data ? data.total_executed_quantity : 0;\n const status = \"status\" in data ? data.status : data.algo_status;\n const getSymbolInfo = symbolsInfo[symbol];\n const base_dp = getSymbolInfo(\"base_dp\");\n const quote_dp = getSymbolInfo(\"quote_dp\");\n const displaySide = getDisplaySide(side);\n const displaySymbol = transSymbolformString(symbol);\n const displayQuantity =\n \"algo_type\" in data && data.algo_type === AlgoOrderRootType.POSITIONAL_TP_SL\n ? i18n.t(\"tpsl.entirePosition\")\n : base_dp === undefined\n ? quantity\n : parseNumber(quantity, { dp: base_dp });\n\n let title = \"\";\n let msg = \"\";\n switch (status) {\n case OrderStatus.NEW:\n const isScaledOrder = client_order_id?.startsWith(\"scaled_\");\n // if client_order_id is scaled order, show the scaled order message\n if (isScaledOrder) {\n title = i18n.t(\"orders.status.scaledSubOrderOpened.toast.title\");\n msg = `${displaySide} ${displaySymbol} ${displayQuantity}`;\n } else {\n title = i18n.t(\"orders.status.opened.toast.title\");\n msg = `${displaySide} ${displaySymbol} ${displayQuantity}`;\n }\n\n break;\n case OrderStatus.FILLED:\n case OrderStatus.PARTIAL_FILLED:\n const displayTotalExecutedQuantity =\n base_dp === undefined\n ? total_executed_quantity\n : parseNumber(total_executed_quantity, { dp: base_dp });\n title = i18n.t(\"orders.status.filled.toast.title\");\n msg = `${displaySide} ${displaySymbol} ${displayTotalExecutedQuantity} / ${displayQuantity}`;\n break;\n case OrderStatus.CANCELLED:\n title = i18n.t(\"orders.status.canceled.toast.title\");\n msg = `${displaySide} ${displaySymbol} ${displayQuantity}`;\n break;\n case OrderStatus.REJECTED:\n title = i18n.t(\"orders.status.rejected.toast.title\");\n msg = `${displaySide} ${displaySymbol} ${displayQuantity}`;\n break;\n case OrderStatus.REPLACED:\n const { algo_type, activated_price } = data as API.AlgoOrder;\n if (algo_type === AlgoOrderRootType.TRAILING_STOP) {\n const fieldChange =\n fieldChanges?.[AlgoOrderRootType.TRAILING_STOP] || {};\n // when trailing stop order is activated, and extreme_price will also changed\n if (\n fieldChange.is_activated &&\n fieldChange.extreme_price &&\n activated_price\n ) {\n title = i18n.t(\"orders.trailingStop.activated\");\n msg = `${displaySymbol} @${activated_price}`;\n } else if (fieldChange.extreme_price) {\n // if extreme_price is changed, skip show the message\n title = \"\";\n msg = \"\";\n }\n } else {\n title = i18n.t(\"orders.status.replaced.toast.title\");\n msg = `${side} ${displaySymbol} ${total_executed_quantity} / ${displayQuantity}`;\n }\n\n break;\n default:\n break;\n }\n\n return {\n title,\n msg,\n status,\n };\n}\n","import { useMemo } from \"react\";\nimport {\n useTranslation,\n useLocaleCode,\n LocaleEnum,\n} from \"@kodiak-finance/orderly-i18n\";\nimport { Locale } from \"@kodiak-finance/orderly-ui\";\nimport { enUS, zhCN, ja, es, ko, vi, de, fr, nl } from \"date-fns/locale\";\n\nexport function useUILocale() {\n const { t } = useTranslation();\n const localeCode = useLocaleCode();\n\n return useMemo<Locale>(() => {\n const calendarLocale = {\n [LocaleEnum.en]: enUS,\n [LocaleEnum.zh]: zhCN,\n // [LocaleEnum.ja]: ja,\n // [LocaleEnum.es]: es,\n // [LocaleEnum.ko]: ko,\n // [LocaleEnum.vi]: vi,\n // [LocaleEnum.de]: de,\n // [LocaleEnum.fr]: fr,\n // [LocaleEnum.nl]: nl,\n };\n return {\n locale: localeCode,\n dialog: {\n ok: t(\"common.ok\"),\n cancel: t(\"common.cancel\"),\n },\n modal: {\n confirm: t(\"common.confirm\"),\n cancel: t(\"common.cancel\"),\n },\n pagination: {\n morePages: t(\"ui.pagination.morePages\"),\n rowsPerPage: t(\"ui.pagination.rowsPerPage\"),\n },\n picker: {\n selectDate: t(\"ui.picker.selectDate\"),\n dayPicker: calendarLocale[localeCode as keyof typeof calendarLocale],\n },\n empty: {\n description: t(\"ui.empty.description\"),\n },\n } as const;\n }, [t, localeCode]);\n}\n","import { createContext, useContext } from \"react\";\nimport { AppLogos } from \"../types\";\n\nexport type ThemeContextState = {\n appIcons?: AppLogos;\n brokerName: string;\n};\n\nexport const AppConfigContext = createContext({} as ThemeContextState);\n\nexport const useAppConfig = () => {\n return useContext(AppConfigContext);\n};\n","import { FC, PropsWithChildren } from \"react\";\nimport { AppLogos } from \"../types\";\nimport { AppConfigContext } from \"./appConfigContext\";\n\nexport type ThemeContextState = {\n appIcons?: AppLogos;\n brokerName: string;\n};\n\nexport const AppConfigProvider: FC<\n PropsWithChildren<{ appIcons?: AppLogos; brokerName: string }>\n> = (props) => {\n return (\n <AppConfigContext.Provider value={props}>\n {props.children}\n </AppConfigContext.Provider>\n );\n};\n","import { FC, PropsWithChildren, useState, useMemo } from \"react\";\nimport {\n RestrictedInfoOptions,\n useRestrictedInfo,\n useTrackingInstance,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { useAssetconvertEvent } from \"../hooks/useAssetconvertEvent\";\nimport { DefaultChain, useCurrentChainId } from \"../hooks/useCurrentChainId\";\nimport { useLinkDevice } from \"../hooks/useLinkDevice\";\nimport { useSettleEvent } from \"../hooks/useSettleEvent\";\nimport { useWalletConnectError } from \"../hooks/useWalletConnectError\";\nimport { useWalletEvent } from \"../hooks/useWalletEvent\";\nimport { useWalletStateHandle } from \"../hooks/useWalletStateHandle\";\nimport { AppContextState, AppStateContext } from \"./appStateContext\";\n\nexport type RouteOption = {\n href: \"/portfolio\" | \"/portfolio/history\";\n name: string;\n};\n\nexport type AppStateProviderProps = {\n defaultChain?: DefaultChain;\n restrictedInfo?: RestrictedInfoOptions;\n} & Pick<AppContextState, \"onChainChanged\" | \"onRouteChange\" | \"widgetConfigs\">;\n\nexport const AppStateProvider: FC<PropsWithChildren<AppStateProviderProps>> = (\n props,\n) => {\n const [showAnnouncement, setShowAnnouncement] = useState(false);\n const [currentChainId, setCurrentChainId] = useCurrentChainId(\n props.defaultChain,\n );\n useLinkDevice();\n useTrackingInstance();\n\n const { connectWallet, wrongNetwork } = useWalletStateHandle({\n // onChainChanged: props.onChainChanged,\n currentChainId,\n });\n\n useWalletEvent();\n useSettleEvent();\n useAssetconvertEvent();\n useWalletConnectError();\n\n const restrictedInfo = useRestrictedInfo(props.restrictedInfo);\n\n const disabledConnect = restrictedInfo.restrictedOpen;\n\n const memoizedValue = useMemo<AppContextState>(\n () => ({\n connectWallet,\n wrongNetwork,\n currentChainId,\n setCurrentChainId,\n onChainChanged: props.onChainChanged,\n disabledConnect,\n restrictedInfo,\n showAnnouncement,\n setShowAnnouncement,\n onRouteChange: props.onRouteChange,\n widgetConfigs: props.widgetConfigs,\n }),\n [\n connectWallet,\n currentChainId,\n disabledConnect,\n props.onChainChanged,\n restrictedInfo,\n setCurrentChainId,\n showAnnouncement,\n wrongNetwork,\n props.onRouteChange,\n props.widgetConfigs,\n ],\n );\n\n return (\n <AppStateContext.Provider value={memoizedValue}>\n {props.children}\n </AppStateContext.Provider>\n );\n};\n","import { useEffect } from \"react\";\nimport { useWS } from \"@kodiak-finance/orderly-hooks\";\nimport { useTranslation } from \"@kodiak-finance/orderly-i18n\";\nimport { toast } from \"@kodiak-finance/orderly-ui\";\nimport { getTimestamp } from \"@kodiak-finance/orderly-utils\";\n\nexport const useAssetconvertEvent = () => {\n const ws = useWS();\n const { t } = useTranslation();\n useEffect(() => {\n const unsubscribe = ws.privateSubscribe(\n {\n id: \"assetconvert\",\n event: \"subscribe\",\n topic: \"assetconvert\",\n ts: getTimestamp(),\n },\n {\n onMessage(data) {\n if (data.convertId) {\n toast.success(t(\"transfer.convert.completed\"));\n }\n },\n },\n );\n return () => unsubscribe();\n }, []);\n};\n","import { useEffect, useState } from \"react\";\nimport {\n Chains,\n useChains,\n useConfig,\n useStorageChain,\n useWalletConnector,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { Chain, NetworkId } from \"@kodiak-finance/orderly-types\";\ntype ReturnChain = Pick<Chain, \"id\"> & Partial<Omit<Chain, \"id\">>;\n\nexport type DefaultChain =\n | {\n mainnet?: ReturnChain;\n testnet?: ReturnChain;\n }\n | ((networkId: NetworkId, chains: Chains) => ReturnChain)\n | undefined;\n\nexport function useCurrentChainId(defaultChain?: DefaultChain) {\n const { storageChain, setStorageChain } = useStorageChain();\n const [currentChainId, setCurrentChainId] = useState<number | undefined>();\n\n const [chains] = useChains();\n const networkId = useConfig(\"networkId\") as NetworkId;\n\n const { connectedChain } = useWalletConnector();\n\n useEffect(() => {\n if (connectedChain) {\n setCurrentChainId?.(\n typeof connectedChain.id === \"number\"\n ? connectedChain.id\n : parseInt(connectedChain.id)\n );\n } else {\n if (!!currentChainId) return;\n let fallbackChain: Partial<Chain> | undefined;\n\n const firstChain =\n networkId === \"mainnet\" ? chains.mainnet?.[0] : chains.testnet?.[0];\n\n if (typeof defaultChain === \"function\") {\n fallbackChain = defaultChain(networkId, chains);\n } else if (typeof defaultChain === \"object\") {\n fallbackChain =\n networkId === \"mainnet\"\n ? defaultChain?.mainnet\n : defaultChain?.testnet;\n }\n\n const chainId = fallbackChain?.id || firstChain?.network_infos?.chain_id;\n if (!chainId) return;\n\n if (storageChain) {\n setCurrentChainId?.(storageChain.chainId);\n } else {\n setStorageChain(chainId);\n setCurrentChainId?.(chainId);\n \n }\n }\n }, [\n connectedChain,\n chains,\n currentChainId,\n networkId,\n setCurrentChainId,\n defaultChain,\n ]);\n\n return [currentChainId, setCurrentChainId] as const;\n}\n","import { useCallback, useEffect } from \"react\";\nimport {\n parseJSON,\n useAccount,\n useConfig,\n useLocalStorage,\n useWalletConnector,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { ChainNamespace } from \"@kodiak-finance/orderly-types\";\nimport { useScreen } from \"@kodiak-finance/orderly-ui\";\n\ntype DecodedData = {\n /** secret key */\n k: string;\n /* timestamp */\n t: number;\n /** address */\n a: string;\n /** chain id */\n i: number;\n /** chain namespace */\n n: ChainNamespace;\n};\n\ntype LinkDeviceStorage = { chainId: number; chainNamespace: ChainNamespace };\n\nconst WALLET_KEY = \"orderly:wallet-info\";\n\nexport function useLinkDevice() {\n const { connectedChain, disconnect } = useWalletConnector();\n const [_, setLinkDeviceStorage] = useLocalStorage(\n \"orderly_link_device\",\n {} as LinkDeviceStorage,\n );\n\n const { account } = useAccount();\n const { isMobile } = useScreen();\n const configStore = useConfig();\n\n const onDisconnect = async (label: string) => {\n // The cache must be cleared first, otherwise it will be auto connect wallet\n localStorage.removeItem(WALLET_KEY);\n await account.disconnect();\n await disconnect({ label });\n };\n\n useEffect(() => {\n const linkData = getLinkDeviceData();\n const walletInfo = JSON.parse(localStorage.getItem(WALLET_KEY) ?? \"{}\");\n if (linkData && walletInfo) {\n // clear connect data when link device\n onDisconnect(walletInfo.label);\n }\n }, []);\n\n const linkDevice = async () => {\n const linkData = getLinkDeviceData();\n if (!linkData) return;\n\n const { address, secretKey, chainId, chainNamespace } = linkData;\n const isSuccess = await account.importOrderlyKey({\n address,\n secretKey,\n chainNamespace,\n });\n if (!isSuccess) return;\n setLinkDeviceStorage({\n chainId,\n chainNamespace,\n });\n\n const url = new URL(window.location.href);\n url.searchParams.delete(\"link\");\n // use set instead of append, because the param possibly in the url\n url.searchParams.set(\"utm_medium\", \"qrcode\");\n const decodedUrl = decodeURIComponent(url.toString());\n history.replaceState(null, \"\", decodedUrl);\n };\n\n useEffect(() => {\n if (isMobile && !connectedChain) {\n linkDevice();\n }\n }, [account, connectedChain, isMobile]);\n\n const autoLinkDevice = async () => {\n // this can't use the value returned by useLocalStorage here, because it will trigger extra state change\n const { chainId, chainNamespace } = getLinkDeviceStorage() || {};\n if (isMobile && !connectedChain && chainId && chainNamespace) {\n const address = account.keyStore.getAddress();\n const orderlyKey = account.keyStore.getOrderlyKey();\n const accountId = account.keyStore.getAccountId(address!);\n const res = await account.checkOrderlyKey(\n address!,\n orderlyKey!,\n accountId!,\n );\n if (res) {\n configStore.set(\"chainNamespace\", chainNamespace);\n }\n }\n };\n\n // persist status when refresh page\n useEffect(() => {\n autoLinkDevice();\n }, [account, isMobile, connectedChain]);\n\n return { linkDevice };\n}\n\nfunction getLinkDeviceStorage() {\n try {\n const linkDeviceStorage = localStorage.getItem(\"orderly_link_device\");\n const json = linkDeviceStorage ? parseJSON(linkDeviceStorage) : null;\n return json as LinkDeviceStorage;\n } catch (err) {\n console.error(\"getLinkDeviceStorage\", err);\n }\n}\n\nexport function getLinkDeviceData() {\n const url = new URL(window.location.href);\n const link = url.searchParams.get(\"link\");\n\n if (!link) return;\n\n const {\n a: address,\n k: secretKey,\n i: chainId,\n n: chainNamespace,\n } = decodeBase64(link) || {};\n\n if (address && secretKey && chainId && chainNamespace) {\n return {\n address,\n secretKey,\n chainId,\n chainNamespace,\n };\n }\n}\n\nfunction decodeBase64(base64: string) {\n try {\n const data = JSON.parse(window.atob(base64)) as DecodedData;\n console.log(\"decodeBase64\", data);\n const currentTime = Math.floor(Date.now() / 1000);\n const expiredTime = data.t;\n\n if (!expiredTime || currentTime > expiredTime) {\n console.error(\"Orderly key has expired.\");\n return;\n }\n\n return data;\n } catch (error) {\n console.error(\"Invalid or expired orderly key.\");\n }\n}\n","import { useSettleSubscription } from \"@kodiak-finance/orderly-hooks\";\nimport { toast } from \"@kodiak-finance/orderly-ui\";\nimport { useTranslation } from \"@kodiak-finance/orderly-i18n\";\n\nexport function useSettleEvent() {\n const { t } = useTranslation();\n\n useSettleSubscription({\n onMessage: (data: any) => {\n const { status } = data;\n\n // console.log(\"settle ws: \", data);\n\n switch (status) {\n case \"COMPLETED\":\n toast.success(t(\"settle.settlement.completed\"));\n break;\n case \"FAILED\":\n toast.error(t(\"settle.settlement.failed\"));\n break;\n default:\n break;\n }\n },\n });\n}\n","import { useEventEmitter } from \"@kodiak-finance/orderly-hooks\";\nimport { useEffect } from \"react\";\nimport { modal, toast } from \"@kodiak-finance/orderly-ui\";\nimport { LedgerWalletKey } from \"@kodiak-finance/orderly-types\";\nimport { useStorageLedgerAddress } from \"@kodiak-finance/orderly-hooks\";\nimport { useTranslation } from \"@kodiak-finance/orderly-i18n\";\n\nexport function useWalletConnectError() {\n const { t } = useTranslation();\n const ee = useEventEmitter();\n const { setLedgerAddress } = useStorageLedgerAddress();\n\n useEffect(() => {\n ee.on(\"wallet:connect-error\", (data) => {\n toast.error(data.message);\n });\n ee.on(\n \"wallet:sign-message-with-ledger-error\",\n (data: { userAddress: string; message: string }) => {\n window.setTimeout(() => {\n modal\n .confirm({\n title: t(\"connector.ledger.signMessageFailed\"),\n content: t(\"connector.ledger.signMessageFailed.description\"),\n size: \"sm\",\n onOk: async () => {\n console.log(\"-- use ledger\", true);\n setLedgerAddress(data.userAddress);\n\n return Promise.resolve();\n },\n okLabel: t(\"common.ok\"),\n onCancel: async () => {\n toast.error(data.message);\n return Promise.resolve();\n },\n cancelLabel: t(\"common.no\"),\n })\n .then((res) => {\n console.log(\"-- dialog res\", res);\n });\n });\n }\n );\n }, [ee, t]);\n\n return {};\n}\n","import { useRef } from \"react\";\nimport {\n useEventEmitter,\n useSessionStorage,\n useWalletSubscription,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { useTranslation } from \"@kodiak-finance/orderly-i18n\";\nimport { toast } from \"@kodiak-finance/orderly-ui\";\nimport { capitalizeString } from \"@kodiak-finance/orderly-utils\";\n\nexport function useWalletEvent() {\n const { t } = useTranslation();\n const ee = useEventEmitter();\n\n const recordRef = useRef<Record<number, boolean>>({});\n\n const [record, setRecord] = useSessionStorage(\n \"orderly_wallet_change_id\",\n {} as Record<number, boolean>,\n );\n\n recordRef.current = record;\n\n useWalletSubscription({\n onMessage: (data: any) => {\n console.log(\"wallet:changed\", data);\n const { id, side, transStatus } = data;\n let showToast = true;\n\n // DEPOSIT and WITHDRAW will push twice COMPLETED and FAILED event\n if (\n [\"DEPOSIT\", \"WITHDRAW\"].includes(side) &&\n [\"COMPLETED\", \"FAILED\"].includes(transStatus)\n ) {\n const isPushed = !!recordRef.current[id];\n if (!isPushed) {\n recordRef.current[id] = true;\n setRecord((prev: Record<number, boolean>) => ({\n ...prev,\n [id]: true,\n }));\n }\n showToast = !isPushed;\n }\n\n if (transStatus === \"COMPLETED\" && showToast) {\n let msg = `${capitalizeString(side)} completed`;\n\n if (side === \"DEPOSIT\") {\n msg = t(\"transfer.deposit.completed\");\n } else if (side === \"WITHDRAW\") {\n msg = t(\"transfer.withdraw.completed\");\n }\n\n toast.success(msg);\n } else if (transStatus === \"FAILED\" && showToast) {\n let msg = `${capitalizeString(side)} failed`;\n\n if (side === \"DEPOSIT\") {\n msg = t(\"transfer.deposit.failed\");\n } else if (side === \"WITHDRAW\") {\n msg = t(\"transfer.withdraw.failed\");\n }\n toast.error(msg);\n }\n\n ee.emit(\"wallet:changed\", data);\n },\n });\n}\n","import { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n useConfig,\n useEventEmitter,\n useTrack,\n WalletState,\n} from \"@kodiak-finance/orderly-hooks\";\nimport {\n useAccount,\n useChains,\n useKeyStore,\n useWalletConnector,\n} from \"@kodiak-finance/orderly-hooks\";\nimport {\n AccountStatusEnum,\n SDKError,\n ChainNamespace,\n NetworkId,\n TrackerEventName,\n ABSTRACT_CHAIN_ID_MAP,\n} from \"@kodiak-finance/orderly-types\";\nimport {\n parseChainIdToNumber,\n praseChainIdToNumber,\n windowGuard,\n} from \"@kodiak-finance/orderly-utils\";\nimport { getLinkDeviceData } from \"./useLinkDevice\";\n\nconst WALLET_KEY = \"orderly:wallet-info\";\nconst CHAIN_NAMESPACE = \"orderly:chain-namespace\";\n\nexport const useWalletStateHandle = (options: {\n // onChainChanged?: (chainId: number, isTestnet: boolean) => void;\n currentChainId?: number;\n}) => {\n const {\n wallet: connectedWallet,\n connect,\n connectedChain,\n disconnect,\n namespace,\n } = useWalletConnector();\n //\n // console.log(\"🔗 wallet state handle\", {\n // connectedWallet,\n // connectedChain,\n // namespace,\n // });\n\n if (typeof connect !== \"function\") {\n throw new SDKError(\"Please provide a wallet connector provider\");\n }\n\n const ee = useEventEmitter();\n const isManualConnect = useRef<boolean>(false);\n const brokerId = useConfig(\"brokerId\");\n const { account, state: accountState } = useAccount();\n const keyStore = useKeyStore();\n const networkId = useConfig(\"networkId\") as NetworkId;\n const [chains, { checkChainSupport }] = useChains();\n\n const [unsupported, setUnsupported] = useState(false);\n const { track, setTrackUserId } = useTrack();\n\n // current connected wallet address\n const currentWalletAddress = useMemo<string | undefined>(() => {\n return connectedWallet?.accounts?.[0]?.address;\n }, [connectedWallet]);\n\n // current connected chain id\n const currentChain = useMemo<\n { id: number; namespace: string } | undefined\n >(() => {\n const id = connectedWallet?.chains?.[0]?.id;\n const namespace = connectedWallet?.chains?.[0]?.namespace as string;\n if (typeof id === \"undefined\") return undefined;\n return {\n id: parseChainIdToNumber(id),\n namespace,\n };\n }, [connectedWallet]);\n\n useEffect(() => {\n if (\n accountState.status >= AccountStatusEnum.EnableTrading &&\n account.accountId\n ) {\n setTrackUserId(account.accountId!);\n }\n }, [account, accountState]);\n\n useEffect(() => {\n if (!connectedChain) {\n setUnsupported(false);\n return;\n }\n\n let isSupported = checkChainSupport(\n connectedChain.id,\n networkId,\n // networkId === \"testnet\" ? chains.testnet : chains.mainnet\n );\n if (\n ABSTRACT_CHAIN_ID_MAP.has(parseInt(connectedChain.id as string)) &&\n connectedWallet?.label !== \"AGW\"\n ) {\n isSupported = false;\n }\n\n setUnsupported(!isSupported);\n }, [connectedChain, chains, checkChainSupport, networkId, connectedWallet]);\n\n useEffect(() => {\n // if (unsupported) return;\n\n windowGuard(() => {\n const localAddress = keyStore.getAddress();\n const walletInfo = JSON.parse(localStorage.getItem(WALLET_KEY) ?? \"{}\");\n\n /**\n * if locale address is exist, restore account state\n */\n if (connectedChain?.namespace === ChainNamespace.solana) {\n return;\n }\n if (\n localAddress &&\n account.address !== localAddress &&\n walletInfo.label\n ) {\n connect({\n autoSelect: {\n label: walletInfo.label,\n disableModals: true,\n },\n }).then(\n (res) => {\n console.log(\"silent connect wallet successes\", res);\n },\n (error) => console.log(\"connect error\", error),\n );\n }\n });\n }, [connectedWallet, account.address]);\n\n /**\n * handle wallet connection\n */\n useEffect(() => {\n if (\n connectedWallet === null &&\n accountState.status > AccountStatusEnum.NotConnected &&\n !accountState.validating\n ) {\n account.disconnect();\n return;\n }\n\n if (unsupported || !connectedChain) return;\n if (isManualConnect.current) return;\n\n const linkData = getLinkDeviceData();\n\n // updateAccount(currentWalletAddress!, connectedWallet!, currentChainId!);\n /**\n * switch account\n */\n if (\n !!currentWalletAddress &&\n currentWalletAddress !== account.address &&\n !linkData\n ) {\n account.setAddress(currentWalletAddress, {\n provider: connectedWallet?.provider,\n chain: {\n id: praseChainIdToNumber(currentChain!.id),\n namespace: currentChain!.namespace.toUpperCase() as ChainNamespace,\n },\n wallet: {\n name: connectedWallet?.label ?? \"\",\n },\n additionalInfo: connectedWallet?.additionalInfo ?? {},\n });\n track(TrackerEventName.walletConnect, {\n wallet: connectedWallet?.label ?? \"\",\n network: currentChain!.namespace.toUpperCase() as ChainNamespace,\n });\n\n // save wallet connector info to local storage\n windowGuard(() => {\n localStorage.setItem(\n WALLET_KEY,\n JSON.stringify({\n label: connectedWallet?.label ?? \"\",\n }),\n );\n });\n }\n\n /**\n * switch chainId\n */\n if (currentChain?.id !== account.chainId) {\n account.switchChainId(currentChain?.id!);\n\n // emit chain changed event\n // options.onChainChanged?.(currentChainId!, isTestnet(networkId));\n }\n }, [\n connectedWallet,\n connectedChain,\n currentWalletAddress,\n currentChain,\n account.address,\n accountState,\n account.chainId,\n unsupported,\n ]);\n\n /**\n * User manually connects to wallet\n */\n const connectWallet = async (): Promise<{\n wallet?: WalletState;\n status?: AccountStatusEnum;\n wrongNetwork?: boolean;\n } | null> => {\n isManualConnect.current = true;\n // const walletState = await connect();\n\n return connect({ chainId: options.currentChainId })\n .then(async (walletState) => {\n if (\n Array.isArray(walletState) &&\n walletState.length > 0 &&\n walletState[0] &&\n walletState[0].accounts.length > 0\n ) {\n const wallet = walletState[0];\n const chainId = praseChainIdToNumber(wallet.chains[0].id);\n\n if (!checkChainSupport(chainId, networkId)) {\n return {\n wrongNetwork: true,\n };\n }\n //\n if (!account) {\n throw new Error(\"account is not initialized\");\n }\n // clear link device data when connect wallt\n if (\n accountState.status ===\n AccountStatusEnum.EnableTradingWithoutConnected\n ) {\n localStorage.removeItem(\"orderly_link_device\");\n await account.disconnect();\n }\n\n const status = await account.setAddress(wallet.accounts[0].address, {\n provider: wallet.provider,\n chain: {\n id: praseChainIdToNumber(wallet.chains[0].id),\n namespace:\n wallet.chains[0].namespace.toUpperCase() as ChainNamespace,\n },\n wallet: {\n name: wallet.label,\n },\n // label: ,\n });\n track(TrackerEventName.walletConnect, {\n wallet: wallet.label,\n network: wallet.chains[0].namespace.toUpperCase() as ChainNamespace,\n });\n console.log(\"-- xxxxxx status\", status);\n\n return { wallet, status, wrongNetwork: false };\n }\n\n return null;\n })\n .finally(() => {\n isManualConnect.current = false;\n });\n };\n\n return {\n connectWallet,\n wrongNetwork: unsupported,\n };\n};\n","import React, { createContext, useContext } from \"react\";\nimport { RestrictedInfoReturns } from \"@kodiak-finance/orderly-hooks\";\nimport { useWalletStateHandle } from \"../hooks/useWalletStateHandle\";\n\nexport type RouteOption = {\n href: \"/portfolio\" | \"/portfolio/history\";\n name: string;\n};\n\nexport type WidgetConfigs = {\n scanQRCode?: {\n onSuccess?: (url: string) => void;\n };\n};\n\nexport type AppContextState = {\n connectWallet: ReturnType<typeof useWalletStateHandle>[\"connectWallet\"];\n /**\n * Whether the current network is not supported\n */\n wrongNetwork: boolean;\n disabledConnect: boolean;\n currentChainId: number | undefined;\n setCurrentChainId: (chainId: number | undefined) => void;\n onChainChanged?: (\n chainId: number,\n state: { isTestnet: boolean; isWalletConnected: boolean },\n ) => void;\n // networkStatus: ReturnType<typeof useAppState>[\"networkStatus\"];\n restrictedInfo: RestrictedInfoReturns;\n showAnnouncement: boolean;\n setShowAnnouncement: (show: boolean) => void;\n onRouteChange?: (option: RouteOption) => void;\n widgetConfigs?: WidgetConfigs;\n};\n\nexport const AppStateContext = createContext<AppContextState>({\n setCurrentChainId: (chainId?: number) => {},\n restrictedInfo: {},\n setShowAnnouncement: (show: boolean) => {},\n} as AppContextState);\n\nexport const useAppContext = () => {\n return useContext(AppStateContext);\n};\n","import { useAccount } from \"@kodiak-finance/orderly-hooks\";\nimport { AccountStatusEnum } from \"@kodiak-finance/orderly-types\";\nimport { useAppContext } from \"../provider/appStateContext\";\n\nexport const useDataTap = <T = any>(\n data: T,\n options?: {\n skip?: false;\n fallbackData?: T;\n accountStatus?: AccountStatusEnum;\n },\n): T | null => {\n const { wrongNetwork, disabledConnect } = useAppContext();\n const { state } = useAccount();\n /**\n * ignore\n */\n if (options?.skip) {\n return data;\n }\n\n if (wrongNetwork || disabledConnect) {\n return typeof options?.fallbackData !== \"undefined\"\n ? options.fallbackData\n : null;\n }\n\n if (typeof options?.accountStatus !== \"undefined\") {\n if (state.status < options.accountStatus) {\n return typeof options?.fallbackData !== \"undefined\"\n ? options.fallbackData\n : null;\n }\n }\n\n // return wrongNetwork\n // ? typeof options?.fallbackData !== \"undefined\"\n // ? options.fallbackData\n // : null\n // : data;\n //\n return data;\n};\n","import { useCallback } from \"react\";\nimport {\n OrderValidationItem,\n OrderValidationResult,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { useTranslation } from \"@kodiak-finance/orderly-i18n\";\n\ntype Keys = keyof OrderValidationResult;\ntype ErrorType = Partial<OrderValidationItem[\"type\"]>;\n\nexport function useOrderEntryFormErrorMsg(\n errors: OrderValidationResult | null,\n) {\n const { t } = useTranslation();\n\n const getMessage = (\n key: Keys,\n type: ErrorType,\n params: {\n value?: string | number;\n min?: string | number;\n max?: string | number;\n },\n ) => {\n const { value, min, max } = params || {};\n const map: Partial<Record<Keys, Partial<Record<ErrorType, string>>>> = {\n quantity: {\n required: t(\"orderEntry.orderQuantity.error.required\"),\n min: t(\"orderEntry.orderQuantity.error.min\", { value }),\n max: t(\"orderEntry.orderQuantity.error.max\", { value }),\n },\n order_quantity: {\n required: t(\"orderEntry.orderQuantity.error.required\"),\n min: t(\"orderEntry.orderQuantity.error.min\", { value }),\n max: t(\"orderEntry.orderQuantity.error.max\", { value }),\n },\n order_price: {\n required: t(\"orderEntry.orderPrice.error.required\"),\n min: t(\"orderEntry.orderPrice.error.min\", { value }),\n max: t(\"orderEntry.orderPrice.error.max\", { value }),\n },\n trigger_price: {\n required: t(\"orderEntry.triggerPrice.error.required\"),\n min: t(\"orderEntry.triggerPrice.error.min\", { value }),\n max: t(\"orderEntry.triggerPrice.error.max\", { value }),\n },\n tp_trigger_price: {\n required: t(\"tpsl.validate.tpTriggerPrice.error.required\"),\n min: t(\"orderEntry.tpTriggerPrice.error.min\", { value }),\n max: t(\"orderEntry.tpTriggerPrice.error.max\", { value }),\n priceErrorMin: t(\"tpsl.validate.tpTriggerPrice.error.priceErrorMin\"),\n priceErrorMax: t(\"tpsl.validate.tpTriggerPrice.error.priceErrorMax\"),\n },\n sl_trigger_price: {\n required: t(\"tpsl.validate.slTriggerPrice.error.required\"),\n min: t(\"orderEntry.slTriggerPrice.error.min\", { value }),\n max: t(\"orderEntry.slTriggerPrice.error.max\", { value }),\n priceErrorMin: t(\"tpsl.validate.slTriggerPrice.error.priceErrorMin\"),\n priceErrorMax: t(\"tpsl.validate.slTriggerPrice.error.priceErrorMax\"),\n },\n tp_order_price: {\n required: t(\"tpsl.validate.tpOrderPrice.error.required\"),\n min: t(\"tpsl.validate.tpOrderPrice.error.min\", { value }),\n max: t(\"tpsl.validate.tpOrderPrice.error.max\", { value }),\n },\n sl_order_price: {\n required: t(\"tpsl.validate.slOrderPrice.error.required\"),\n min: t(\"tpsl.validate.slOrderPrice.error.min\", { value }),\n max: t(\"tpsl.validate.slOrderPrice.error.max\", { value }),\n },\n total: {\n min: t(\"orderEntry.total.error.min\", { value }),\n },\n // not show form input tooltip\n // slippage: {\n // max: t(\"orderEntry.slippage.error.max\"),\n // },\n start_price: {\n required: t(\"orderEntry.startPrice.error.required\"),\n min: t(\"orderEntry.startPrice.error.min\", { value }),\n max: t(\"orderEntry.startPrice.error.max\", { value }),\n },\n end_price: {\n required: t(\"orderEntry.endPrice.error.required\"),\n min: t(\"orderEntry.endPrice.error.min\", { value }),\n max: t(\"orderEntry.endPrice.error.max\", { value }),\n },\n total_orders: {\n required: t(\"orderEntry.totalOrders.error.required\"),\n range: t(\"orderEntry.totalOrders.error.range\"),\n },\n skew: {\n required: t(\"orderEntry.skew.error.required\"),\n min: t(\"orderEntry.skew.error.min\", { value }),\n max: t(\"orderEntry.skew.error.max\", { value }),\n },\n activated_price: {\n min: t(\"orderEntry.triggerPrice.error.min\", { value }),\n max: t(\"orderEntry.triggerPrice.error.max\", { value }),\n },\n callback_value: {\n required: t(\"orderEntry.callbackValue.error.required\"),\n min: t(\"orderEntry.callbackValue.error.min\", { value }),\n range: t(\"orderEntry.callbackValue.error.range\", {\n min,\n max,\n }),\n },\n callback_rate: {\n required: t(\"orderEntry.callbackRate.error.required\"),\n range: t(\"orderEntry.callbackRate.error.range\", {\n min,\n max,\n }),\n },\n };\n\n return map[key]?.[type] || \"\";\n };\n\n const getErrorMsg = useCallback(\n (key: Keys, customValue?: string) => {\n const { type, value, min, max } = errors?.[key] || ({} as any);\n if (type) {\n return getMessage(key, type, { value: customValue || value, min, max });\n }\n return \"\";\n },\n [errors],\n );\n\n return {\n getErrorMsg,\n };\n}\n"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { useTrack, OrderlyConfigProvider, useAccount, useTrackingInstance, useRestrictedInfo, useEventEmitter, useSymbolsInfo, useOrderlyContext, useLocalStorage, useAudioPlayer, useDebouncedCallback, useStorageChain, useChains, useConfig, useWalletConnector, useKeyStore, useSessionStorage, useWalletSubscription, useSettleSubscription, useWS, useStorageLedgerAddress, parseJSON } from '@kodiak-finance/orderly-hooks';
|
|
2
|
+
import { OrderlyThemeProvider, LocaleProvider, TooltipProvider, ModalProvider, Toaster, toast, useScreen, modal, parseNumber } from '@kodiak-finance/orderly-ui';
|
|
3
|
+
import { createContext, useContext, useCallback, useEffect, useMemo, useState, useRef } from 'react';
|
|
4
|
+
import { OrderStatus, SDKError, AccountStatusEnum, ABSTRACT_CHAIN_ID_MAP, ChainNamespace, TrackerEventName, AlgoOrderRootType } from '@kodiak-finance/orderly-types';
|
|
5
|
+
import { useTranslation, useLocaleCode, LocaleEnum, i18n } from '@kodiak-finance/orderly-i18n';
|
|
6
|
+
import { parseChainIdToNumber, windowGuard, praseChainIdToNumber, capitalizeString, getTimestamp, transSymbolformString } from '@kodiak-finance/orderly-utils';
|
|
7
|
+
import { jsx, jsxs } from 'react/jsx-runtime';
|
|
8
|
+
import { zhCN, enUS } from 'date-fns/locale';
|
|
9
|
+
|
|
10
|
+
var q=()=>{useEffect(()=>{let e=new URLSearchParams(window.location.search).get("ref");e&&localStorage.setItem("referral_code",e);},[]);};function ye(r){return r==="BUY"?i18n.t("common.buy"):r==="SELL"?i18n.t("common.sell"):capitalizeString(r)}function F(r,e){let {symbol:i,side:o,quantity:a,client_order_id:c,fieldChanges:d}=r,t="total_executed_quantity"in r?r.total_executed_quantity:0,l="status"in r?r.status:r.algo_status,s=e[i],n=s("base_dp");s("quote_dp");let u=ye(o),f=transSymbolformString(i),p="algo_type"in r&&r.algo_type===AlgoOrderRootType.POSITIONAL_TP_SL?i18n.t("tpsl.entirePosition"):n===void 0?a:parseNumber(a,{dp:n}),m="",g="";switch(l){case OrderStatus.NEW:c?.startsWith("scaled_")?(m=i18n.t("orders.status.scaledSubOrderOpened.toast.title"),g=`${u} ${f} ${p}`):(m=i18n.t("orders.status.opened.toast.title"),g=`${u} ${f} ${p}`);break;case OrderStatus.FILLED:case OrderStatus.PARTIAL_FILLED:let w=n===void 0?t:parseNumber(t,{dp:n});m=i18n.t("orders.status.filled.toast.title"),g=`${u} ${f} ${w} / ${p}`;break;case OrderStatus.CANCELLED:m=i18n.t("orders.status.canceled.toast.title"),g=`${u} ${f} ${p}`;break;case OrderStatus.REJECTED:m=i18n.t("orders.status.rejected.toast.title"),g=`${u} ${f} ${p}`;break;case OrderStatus.REPLACED:let{algo_type:I,activated_price:E}=r;if(I===AlgoOrderRootType.TRAILING_STOP){let b=d?.[AlgoOrderRootType.TRAILING_STOP]||{};b.is_activated&&b.extreme_price&&E?(m=i18n.t("orders.trailingStop.activated"),g=`${f} @${E}`):b.extreme_price&&(m="",g="");}else m=i18n.t("orders.status.replaced.toast.title"),g=`${o} ${f} ${t} / ${p}`;break;}return {title:m,msg:g,status:l}}var be="orderly_order_sound_alert",V=()=>{let r=useEventEmitter(),e=useSymbolsInfo(),i=useRef({}),{notification:o}=useOrderlyContext();useEffect(()=>{i.current=e;},[e]);let a=o?.orderFilled?.media??"",[c]=useLocalStorage(be,o?.orderFilled?.defaultOpen??false),[d]=useAudioPlayer(a,{autoPlay:c,volume:1}),t=useDebouncedCallback(l=>{(n=>{let{title:h,msg:u,status:f}=F(n,i.current),p=f===OrderStatus.FILLED||f===OrderStatus.PARTIAL_FILLED,m=n.algo_type||n.type;h&&u&&toast.success(jsxs("div",{children:[h,jsx("br",{}),jsx("div",{className:"orderly-text-white/[0.54] orderly-text-xs",children:u}),p&&d]}),{id:m});})(l);},100);useEffect(()=>(r.on("orders:changed",t),()=>{r.off("orders:changed",t),t.cancel();}),[r,t]);};function Q(){let{t:r}=useTranslation(),e=useLocaleCode();return useMemo(()=>{let i={[LocaleEnum.en]:enUS,[LocaleEnum.zh]:zhCN};return {locale:e,dialog:{ok:r("common.ok"),cancel:r("common.cancel")},modal:{confirm:r("common.confirm"),cancel:r("common.cancel")},pagination:{morePages:r("ui.pagination.morePages"),rowsPerPage:r("ui.pagination.rowsPerPage")},picker:{selectDate:r("ui.picker.selectDate"),dayPicker:i[e]},empty:{description:r("ui.empty.description")}}},[r,e])}var _=createContext({}),De=()=>useContext(_);var z=r=>jsx(_.Provider,{value:r,children:r.children});var B=()=>{let r=useWS(),{t:e}=useTranslation();useEffect(()=>{let i=r.privateSubscribe({id:"assetconvert",event:"subscribe",topic:"assetconvert",ts:getTimestamp()},{onMessage(o){o.convertId&&toast.success(e("transfer.convert.completed"));}});return ()=>i()},[]);};function J(r){let{storageChain:e,setStorageChain:i}=useStorageChain(),[o,a]=useState(),[c]=useChains(),d=useConfig("networkId"),{connectedChain:t}=useWalletConnector();return useEffect(()=>{if(t)a?.(typeof t.id=="number"?t.id:parseInt(t.id));else {if(o)return;let l,s=d==="mainnet"?c.mainnet?.[0]:c.testnet?.[0];typeof r=="function"?l=r(d,c):typeof r=="object"&&(l=d==="mainnet"?r?.mainnet:r?.testnet);let n=l?.id||s?.network_infos?.chain_id;if(!n)return;e?a?.(e.chainId):(i(n),a?.(n));}},[t,c,o,d,a,r]),[o,a]}var Y="orderly:wallet-info";function G(){let{connectedChain:r,disconnect:e}=useWalletConnector(),[i,o]=useLocalStorage("orderly_link_device",{}),{account:a}=useAccount(),{isMobile:c}=useScreen(),d=useConfig(),t=async n=>{localStorage.removeItem(Y),await a.disconnect(),await e({label:n});};useEffect(()=>{let n=k(),h=JSON.parse(localStorage.getItem(Y)??"{}");n&&h&&t(h.label);},[]);let l=async()=>{let n=k();if(!n)return;let{address:h,secretKey:u,chainId:f,chainNamespace:p}=n;if(!await a.importOrderlyKey({address:h,secretKey:u,chainNamespace:p}))return;o({chainId:f,chainNamespace:p});let g=new URL(window.location.href);g.searchParams.delete("link"),g.searchParams.set("utm_medium","qrcode");let x=decodeURIComponent(g.toString());history.replaceState(null,"",x);};useEffect(()=>{c&&!r&&l();},[a,r,c]);let s=async()=>{let{chainId:n,chainNamespace:h}=Ze()||{};if(c&&!r&&n&&h){let u=a.keyStore.getAddress(),f=a.keyStore.getOrderlyKey(),p=a.keyStore.getAccountId(u);await a.checkOrderlyKey(u,f,p)&&d.set("chainNamespace",h);}};return useEffect(()=>{s();},[a,c,r]),{linkDevice:l}}function Ze(){try{let r=localStorage.getItem("orderly_link_device");return r?parseJSON(r):null}catch{}}function k(){let e=new URL(window.location.href).searchParams.get("link");if(!e)return;let{a:i,k:o,i:a,n:c}=er(e)||{};if(i&&o&&a&&c)return {address:i,secretKey:o,chainId:a,chainNamespace:c}}function er(r){try{let e=JSON.parse(window.atob(r)),i=Math.floor(Date.now()/1e3),o=e.t;return !o||i>o?void 0:e}catch{}}function X(){let{t:r}=useTranslation();useSettleSubscription({onMessage:e=>{let{status:i}=e;switch(i){case "COMPLETED":toast.success(r("settle.settlement.completed"));break;case "FAILED":toast.error(r("settle.settlement.failed"));break;}}});}function ee(){let{t:r}=useTranslation(),e=useEventEmitter(),{setLedgerAddress:i}=useStorageLedgerAddress();return useEffect(()=>{e.on("wallet:connect-error",o=>{toast.error(o.message);}),e.on("wallet:sign-message-with-ledger-error",o=>{window.setTimeout(()=>{modal.confirm({title:r("connector.ledger.signMessageFailed"),content:r("connector.ledger.signMessageFailed.description"),size:"sm",onOk:async()=>(i(o.userAddress),Promise.resolve()),okLabel:r("common.ok"),onCancel:async()=>(toast.error(o.message),Promise.resolve()),cancelLabel:r("common.no")}).then(a=>{});});});},[e,r]),{}}function oe(){let{t:r}=useTranslation(),e=useEventEmitter(),i=useRef({}),[o,a]=useSessionStorage("orderly_wallet_change_id",{});i.current=o,useWalletSubscription({onMessage:c=>{let{id:d,side:t,transStatus:l}=c,s=true;if(["DEPOSIT","WITHDRAW"].includes(t)&&["COMPLETED","FAILED"].includes(l)){let n=!!i.current[d];n||(i.current[d]=true,a(h=>({...h,[d]:true}))),s=!n;}if(l==="COMPLETED"&&s){let n=`${capitalizeString(t)} completed`;t==="DEPOSIT"?n=r("transfer.deposit.completed"):t==="WITHDRAW"&&(n=r("transfer.withdraw.completed")),toast.success(n);}else if(l==="FAILED"&&s){let n=`${capitalizeString(t)} failed`;t==="DEPOSIT"?n=r("transfer.deposit.failed"):t==="WITHDRAW"&&(n=r("transfer.withdraw.failed")),toast.error(n);}e.emit("wallet:changed",c);}});}var ce="orderly:wallet-info";var de=r=>{let{wallet:e,connect:i,connectedChain:o,disconnect:a,namespace:c}=useWalletConnector();if(typeof i!="function")throw new SDKError("Please provide a wallet connector provider");useEventEmitter();let t=useRef(false);useConfig("brokerId");let {account:s,state:n}=useAccount(),h=useKeyStore(),u=useConfig("networkId"),[f,{checkChainSupport:p}]=useChains(),[m,g]=useState(false),{track:x,setTrackUserId:w}=useTrack(),I=useMemo(()=>e?.accounts?.[0]?.address,[e]),E=useMemo(()=>{let y=e?.chains?.[0]?.id,C=e?.chains?.[0]?.namespace;if(!(typeof y>"u"))return {id:parseChainIdToNumber(y),namespace:C}},[e]);return useEffect(()=>{n.status>=AccountStatusEnum.EnableTrading&&s.accountId&&w(s.accountId);},[s,n]),useEffect(()=>{if(!o){g(false);return}let y=p(o.id,u);ABSTRACT_CHAIN_ID_MAP.has(parseInt(o.id))&&e?.label!=="AGW"&&(y=false),g(!y);},[o,f,p,u,e]),useEffect(()=>{windowGuard(()=>{let y=h.getAddress(),C=JSON.parse(localStorage.getItem(ce)??"{}");o?.namespace!==ChainNamespace.solana&&y&&s.address!==y&&C.label&&i({autoSelect:{label:C.label,disableModals:true}}).then(T=>{},T=>{});});},[e,s.address]),useEffect(()=>{if(e===null&&n.status>AccountStatusEnum.NotConnected&&!n.validating){s.disconnect();return}if(m||!o||t.current)return;let y=k();I&&I!==s.address&&!y&&(s.setAddress(I,{provider:e?.provider,chain:{id:praseChainIdToNumber(E.id),namespace:E.namespace.toUpperCase()},wallet:{name:e?.label??""},additionalInfo:e?.additionalInfo??{}}),x(TrackerEventName.walletConnect,{wallet:e?.label??"",network:E.namespace.toUpperCase()}),windowGuard(()=>{localStorage.setItem(ce,JSON.stringify({label:e?.label??""}));})),E?.id!==s.chainId&&s.switchChainId(E?.id);},[e,o,I,E,s.address,n,s.chainId,m]),{connectWallet:async()=>(t.current=true,i({chainId:r.currentChainId}).then(async y=>{if(Array.isArray(y)&&y.length>0&&y[0]&&y[0].accounts.length>0){let C=y[0],T=praseChainIdToNumber(C.chains[0].id);if(!p(T,u))return {wrongNetwork:true};if(!s)throw new Error("account is not initialized");n.status===AccountStatusEnum.EnableTradingWithoutConnected&&(localStorage.removeItem("orderly_link_device"),await s.disconnect());let pe=await s.setAddress(C.accounts[0].address,{provider:C.provider,chain:{id:praseChainIdToNumber(C.chains[0].id),namespace:C.chains[0].namespace.toUpperCase()},wallet:{name:C.label}});return x(TrackerEventName.walletConnect,{wallet:C.label,network:C.chains[0].namespace.toUpperCase()}),{wallet:C,status:pe,wrongNetwork:false}}return null}).finally(()=>{t.current=false;})),wrongNetwork:m}};var N=createContext({setCurrentChainId:r=>{},restrictedInfo:{},setShowAnnouncement:r=>{}}),W=()=>useContext(N);var le=r=>{let[e,i]=useState(false),[o,a]=J(r.defaultChain);G(),useTrackingInstance();let{connectWallet:c,wrongNetwork:d}=de({currentChainId:o});oe(),X(),B(),ee();let t=useRestrictedInfo(r.restrictedInfo),l=t.restrictedOpen,s=useMemo(()=>({connectWallet:c,wrongNetwork:d,currentChainId:o,setCurrentChainId:a,onChainChanged:r.onChainChanged,disabledConnect:l,restrictedInfo:t,showAnnouncement:e,setShowAnnouncement:i,onRouteChange:r.onRouteChange,widgetConfigs:r.widgetConfigs}),[c,o,l,r.onChainChanged,t,a,e,d,r.onRouteChange,r.widgetConfigs]);return jsx(N.Provider,{value:s,children:r.children})};var Fr=()=>(V(),null),ue=r=>{let{components:e,appIcons:i,onChainChanged:o,defaultChain:a,widgetConfigs:c,...d}=r;useTrack(),q();let t=Q();return jsx(z,{appIcons:i,brokerName:r.brokerName,children:jsx(OrderlyThemeProvider,{components:e,overrides:r.overrides,children:jsxs(OrderlyConfigProvider,{...d,children:[jsx(Fr,{}),jsx(le,{onChainChanged:o,defaultChain:a,restrictedInfo:r.restrictedInfo,onRouteChange:r.onRouteChange,widgetConfigs:c,children:jsx(LocaleProvider,{locale:t,children:jsx(TooltipProvider,{delayDuration:300,children:jsx(ModalProvider,{children:r.children})})})}),jsx(Toaster,{})]})})})};process.env.NODE_ENV!=="production"&&(ue.displayName="OrderlyAppProvider");var Kr=(r,e)=>{let{wrongNetwork:i,disabledConnect:o}=W(),{state:a}=useAccount();return e?.skip?r:i||o||typeof e?.accountStatus<"u"&&a.status<e.accountStatus?typeof e?.fallbackData<"u"?e.fallbackData:null:r};function Qr(r){let{t:e}=useTranslation(),i=(a,c,d)=>{let{value:t,min:l,max:s}=d||{};return {quantity:{required:e("orderEntry.orderQuantity.error.required"),min:e("orderEntry.orderQuantity.error.min",{value:t}),max:e("orderEntry.orderQuantity.error.max",{value:t})},order_quantity:{required:e("orderEntry.orderQuantity.error.required"),min:e("orderEntry.orderQuantity.error.min",{value:t}),max:e("orderEntry.orderQuantity.error.max",{value:t})},order_price:{required:e("orderEntry.orderPrice.error.required"),min:e("orderEntry.orderPrice.error.min",{value:t}),max:e("orderEntry.orderPrice.error.max",{value:t})},trigger_price:{required:e("orderEntry.triggerPrice.error.required"),min:e("orderEntry.triggerPrice.error.min",{value:t}),max:e("orderEntry.triggerPrice.error.max",{value:t})},tp_trigger_price:{required:e("tpsl.validate.tpTriggerPrice.error.required"),min:e("orderEntry.tpTriggerPrice.error.min",{value:t}),max:e("orderEntry.tpTriggerPrice.error.max",{value:t}),priceErrorMin:e("tpsl.validate.tpTriggerPrice.error.priceErrorMin"),priceErrorMax:e("tpsl.validate.tpTriggerPrice.error.priceErrorMax")},sl_trigger_price:{required:e("tpsl.validate.slTriggerPrice.error.required"),min:e("orderEntry.slTriggerPrice.error.min",{value:t}),max:e("orderEntry.slTriggerPrice.error.max",{value:t}),priceErrorMin:e("tpsl.validate.slTriggerPrice.error.priceErrorMin"),priceErrorMax:e("tpsl.validate.slTriggerPrice.error.priceErrorMax")},tp_order_price:{required:e("tpsl.validate.tpOrderPrice.error.required"),min:e("tpsl.validate.tpOrderPrice.error.min",{value:t}),max:e("tpsl.validate.tpOrderPrice.error.max",{value:t})},sl_order_price:{required:e("tpsl.validate.slOrderPrice.error.required"),min:e("tpsl.validate.slOrderPrice.error.min",{value:t}),max:e("tpsl.validate.slOrderPrice.error.max",{value:t})},total:{min:e("orderEntry.total.error.min",{value:t})},start_price:{required:e("orderEntry.startPrice.error.required"),min:e("orderEntry.startPrice.error.min",{value:t}),max:e("orderEntry.startPrice.error.max",{value:t})},end_price:{required:e("orderEntry.endPrice.error.required"),min:e("orderEntry.endPrice.error.min",{value:t}),max:e("orderEntry.endPrice.error.max",{value:t})},total_orders:{required:e("orderEntry.totalOrders.error.required"),range:e("orderEntry.totalOrders.error.range")},skew:{required:e("orderEntry.skew.error.required"),min:e("orderEntry.skew.error.min",{value:t}),max:e("orderEntry.skew.error.max",{value:t})},activated_price:{min:e("orderEntry.triggerPrice.error.min",{value:t}),max:e("orderEntry.triggerPrice.error.max",{value:t})},callback_value:{required:e("orderEntry.callbackValue.error.required"),min:e("orderEntry.callbackValue.error.min",{value:t}),range:e("orderEntry.callbackValue.error.range",{min:l,max:s})},callback_rate:{required:e("orderEntry.callbackRate.error.required"),range:e("orderEntry.callbackRate.error.range",{min:l,max:s})}}[a]?.[c]||""};return {getErrorMsg:useCallback((a,c)=>{let{type:d,value:t,min:l,max:s}=r?.[a]||{};return d?i(a,d,{value:c||t,min:l,max:s}):""},[r])}}
|
|
11
|
+
|
|
12
|
+
export { ue as OrderlyAppProvider, De as useAppConfig, W as useAppContext, Kr as useDataTap, Qr as useOrderEntryFormErrorMsg };
|
|
13
|
+
//# sourceMappingURL=out.js.map
|
|
14
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider/orderlyAppProvider.tsx","../src/hooks/useBootstrap.ts","../src/hooks/useExecutionReport.tsx","../src/hooks/getOrderExecutionReportMsg.ts","../src/hooks/useUILocale.ts","../src/provider/appConfigContext.tsx","../src/provider/appConfigProvider.tsx","../src/provider/appStateProvider.tsx","../src/hooks/useAssetconvertEvent.ts","../src/hooks/useCurrentChainId.ts","../src/hooks/useLinkDevice.ts","../src/hooks/useSettleEvent.ts","../src/hooks/useWalletConnectError.ts","../src/hooks/useWalletEvent.ts","../src/hooks/useWalletStateHandle.ts","../src/provider/appStateContext.tsx","../src/hooks/useDataTap.ts","../src/common/useOrderEntryFormErrorMsg.ts"],"names":["OrderlyConfigProvider","useTrack","UILocaleProvider","ModalProvider","OrderlyThemeProvider","Toaster","TooltipProvider","useEffect","useBootstrap","refCode","useRef","useSymbolsInfo","useEventEmitter","useDebouncedCallback","useAudioPlayer","useLocalStorage","useOrderlyContext","OrderStatus","toast","i18n","AlgoOrderRootType","parseNumber","capitalizeString","transSymbolformString","getDisplaySide","side","getOrderExecutionReportMsg","data","symbolsInfo","symbol","quantity","client_order_id","fieldChanges","total_executed_quantity","status","getSymbolInfo","base_dp","quote_dp","displaySide","displaySymbol","displayQuantity","title","msg","displayTotalExecutedQuantity","algo_type","activated_price","fieldChange","jsx","jsxs","ORDERLY_ORDER_SOUND_ALERT_KEY","useExecutionReport","ee","symbolsInfoRef","notification","src","soundAutoPlay","audioElement","handler","isFilled","orderType","useMemo","useTranslation","useLocaleCode","LocaleEnum","enUS","zhCN","useUILocale","t","localeCode","calendarLocale","createContext","useContext","AppConfigContext","useAppConfig","AppConfigProvider","props","useState","useRestrictedInfo","useTrackingInstance","useWS","getTimestamp","useAssetconvertEvent","ws","unsubscribe","useChains","useConfig","useStorageChain","useWalletConnector","useCurrentChainId","defaultChain","storageChain","setStorageChain","currentChainId","setCurrentChainId","chains","networkId","connectedChain","fallbackChain","firstChain","chainId","parseJSON","useAccount","useScreen","WALLET_KEY","useLinkDevice","disconnect","_","setLinkDeviceStorage","account","isMobile","configStore","onDisconnect","label","linkData","getLinkDeviceData","walletInfo","linkDevice","address","secretKey","chainNamespace","url","decodedUrl","autoLinkDevice","getLinkDeviceStorage","orderlyKey","accountId","linkDeviceStorage","link","decodeBase64","base64","currentTime","expiredTime","useSettleSubscription","useSettleEvent","modal","useStorageLedgerAddress","useWalletConnectError","setLedgerAddress","res","useSessionStorage","useWalletSubscription","useWalletEvent","recordRef","record","setRecord","id","transStatus","showToast","isPushed","prev","useKeyStore","AccountStatusEnum","SDKError","ChainNamespace","TrackerEventName","ABSTRACT_CHAIN_ID_MAP","parseChainIdToNumber","praseChainIdToNumber","windowGuard","useWalletStateHandle","options","connectedWallet","connect","namespace","isManualConnect","brokerId","accountState","keyStore","checkChainSupport","unsupported","setUnsupported","track","setTrackUserId","currentWalletAddress","currentChain","isSupported","localAddress","error","walletState","wallet","AppStateContext","show","useAppContext","AppStateProvider","showAnnouncement","setShowAnnouncement","connectWallet","wrongNetwork","restrictedInfo","disabledConnect","memoizedValue","ExecutionReportListener","OrderlyAppProvider","components","appIcons","onChainChanged","widgetConfigs","configProps","uiLocale","useDataTap","state","useCallback","useOrderEntryFormErrorMsg","errors","getMessage","key","type","params","value","min","max","customValue"],"mappings":"AACA,OAAS,yBAAAA,GAAuB,YAAAC,OAAgB,gCAChD,OACE,kBAAkBC,GAClB,iBAAAC,GACA,wBAAAC,GACA,WAAAC,GACA,mBAAAC,OACK,6BCRP,OAAS,aAAAC,OAAiB,QAEnB,IAAMC,EAAe,IAAM,CAChCD,GAAU,IAAM,CAEd,IAAME,EADe,IAAI,gBAAgB,OAAO,SAAS,MAAM,EAClC,IAAI,KAAK,EAClCA,GACF,aAAa,QAAQ,gBAAiBA,CAAO,CAEjD,EAAG,CAAC,CAAC,CACP,ECTA,OAAS,aAAAF,EAAW,UAAAG,OAAc,QAClC,OACE,kBAAAC,GACA,mBAAAC,GACA,wBAAAC,GACA,kBAAAC,GACA,mBAAAC,GACA,qBAAAC,OACK,gCACP,OAAS,eAAAC,MAAmB,gCAC5B,OAAS,SAAAC,OAAa,6BCXtB,OAAS,Q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ent":["import React, { PropsWithChildren } from \"react\";\nimport { OrderlyConfigProvider, useTrack } from \"@kodiak-finance/orderly-hooks\";\nimport {\n LocaleProvider as UILocaleProvider,\n ModalProvider,\n OrderlyThemeProvider,\n Toaster,\n TooltipProvider,\n} from \"@kodiak-finance/orderly-ui\";\nimport { OrderlyThemeProviderProps } from \"@kodiak-finance/orderly-ui\";\nimport { useBootstrap } from \"../hooks/useBootstrap\";\nimport { useExecutionReport } from \"../hooks/useExecutionReport\";\nimport { useUILocale } from \"../hooks/useUILocale\";\nimport { OrderlyAppConfig } from \"../types\";\nimport { AppConfigProvider } from \"./appConfigProvider\";\nimport { AppStateProvider, AppStateProviderProps } from \"./appStateProvider\";\n\nexport type OrderlyAppProviderProps = PropsWithChildren<\n OrderlyAppConfig & AppStateProviderProps & OrderlyThemeProviderProps\n>;\n\n// Cannot be called outside of Provider because useExecutionReport requires useOrderlyContext.\nconst ExecutionReportListener: React.FC = () => {\n useExecutionReport();\n return null;\n};\n\nconst OrderlyAppProvider: React.FC<OrderlyAppProviderProps> = (props) => {\n const {\n // dateFormatting,\n components,\n appIcons,\n onChainChanged,\n defaultChain,\n widgetConfigs,\n ...configProps\n } = props;\n\n useTrack();\n useBootstrap();\n\n const uiLocale = useUILocale();\n\n return (\n <AppConfigProvider appIcons={appIcons} brokerName={props.brokerName!}>\n <OrderlyThemeProvider\n // dateFormatting={dateFormatting}\n components={components}\n overrides={props.overrides}\n >\n <OrderlyConfigProvider {...configProps}>\n <ExecutionReportListener />\n <AppStateProvider\n onChainChanged={onChainChanged}\n defaultChain={defaultChain}\n restrictedInfo={props.restrictedInfo}\n onRouteChange={props.onRouteChange}\n widgetConfigs={widgetConfigs}\n >\n <UILocaleProvider locale={uiLocale}>\n <TooltipProvider delayDuration={300}>\n <ModalProvider>{props.children}</ModalProvider>\n </TooltipProvider>\n </UILocaleProvider>\n </AppStateProvider>\n <Toaster />\n </OrderlyConfigProvider>\n </OrderlyThemeProvider>\n </AppConfigProvider>\n );\n};\n\nif (process.env.NODE_ENV !== \"production\") {\n OrderlyAppProvider.displayName = \"OrderlyAppProvider\";\n}\n\nexport { OrderlyAppProvider };\n","import { useEffect } from \"react\";\n\nexport const useBootstrap = () => {\n useEffect(() => {\n const searchParams = new URLSearchParams(window.location.search);\n const refCode = searchParams.get(\"ref\");\n if (refCode) {\n localStorage.setItem(\"referral_code\", refCode);\n }\n }, []);\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { useEffect, useRef } from \"react\";\nimport {\n useSymbolsInfo,\n useEventEmitter,\n useDebouncedCallback,\n useAudioPlayer,\n useLocalStorage,\n useOrderlyContext,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { OrderStatus } from \"@kodiak-finance/orderly-types\";\nimport { toast } from \"@kodiak-finance/orderly-ui\";\nimport { getOrderExecutionReportMsg } from \"./getOrderExecutionReportMsg\";\n\nexport const ORDERLY_ORDER_SOUND_ALERT_KEY = \"orderly_order_sound_alert\";\n\nexport const useExecutionReport = () => {\n const ee = useEventEmitter();\n\n const symbolsInfo = useSymbolsInfo();\n const symbolsInfoRef = useRef({});\n\n const { notification } = useOrderlyContext();\n\n useEffect(() => {\n symbolsInfoRef.current = symbolsInfo;\n }, [symbolsInfo]);\n\n const src = notification?.orderFilled?.media ?? \"\";\n\n const [soundAutoPlay] = useLocalStorage<boolean>(\n ORDERLY_ORDER_SOUND_ALERT_KEY,\n notification?.orderFilled?.defaultOpen ?? false,\n );\n\n const [audioElement] = useAudioPlayer(src, {\n autoPlay: soundAutoPlay,\n volume: 1,\n });\n\n const handler = useDebouncedCallback((data: any) => {\n const showToast = (data: any) => {\n const { title, msg, status } = getOrderExecutionReportMsg(\n data,\n symbolsInfoRef.current,\n );\n const isFilled =\n status === OrderStatus.FILLED || status === OrderStatus.PARTIAL_FILLED;\n // only show latest msg for same order type\n const orderType = data.algo_type || data.type;\n if (title && msg) {\n toast.success(\n <div>\n {title}\n <br />\n <div className=\"orderly-text-white/[0.54] orderly-text-xs\">\n {msg}\n </div>\n {isFilled && audioElement}\n </div>,\n { id: orderType },\n );\n }\n };\n showToast(data);\n }, 100);\n\n useEffect(() => {\n ee.on(\"orders:changed\", handler);\n return () => {\n ee.off(\"orders:changed\", handler);\n handler.cancel();\n };\n }, [ee, handler]);\n};\n","import { i18n } from \"@kodiak-finance/orderly-i18n\";\nimport { API, OrderStatus, OrderType } from \"@kodiak-finance/orderly-types\";\nimport { AlgoOrderRootType } from \"@kodiak-finance/orderly-types\";\nimport { parseNumber } from \"@kodiak-finance/orderly-ui\";\nimport {\n capitalizeString,\n transSymbolformString,\n} from \"@kodiak-finance/orderly-utils\";\n\nfunction getDisplaySide(side: string) {\n if (side === \"BUY\") {\n return i18n.t(\"common.buy\");\n } else if (side === \"SELL\") {\n return i18n.t(\"common.sell\");\n }\n return capitalizeString(side);\n}\n\ntype AlgoOrderFieldChanges = Partial<\n Record<OrderType, Partial<Record<keyof API.AlgoOrder, boolean>>>\n>;\n\nexport function getOrderExecutionReportMsg(\n data: (API.AlgoOrder | API.Order) & {\n fieldChanges?: AlgoOrderFieldChanges;\n },\n symbolsInfo: any,\n) {\n const { symbol, side, quantity, client_order_id, fieldChanges } = data;\n const total_executed_quantity =\n \"total_executed_quantity\" in data ? data.total_executed_quantity : 0;\n const status = \"status\" in data ? data.status : data.algo_status;\n const getSymbolInfo = symbolsInfo[symbol];\n const base_dp = getSymbolInfo(\"base_dp\");\n const quote_dp = getSymbolInfo(\"quote_dp\");\n const displaySide = getDisplaySide(side);\n const displaySymbol = transSymbolformString(symbol);\n const displayQuantity =\n \"algo_type\" in data && data.algo_type === AlgoOrderRootType.POSITIONAL_TP_SL\n ? i18n.t(\"tpsl.entirePosition\")\n : base_dp === undefined\n ? quantity\n : parseNumber(quantity, { dp: base_dp });\n\n let title = \"\";\n let msg = \"\";\n switch (status) {\n case OrderStatus.NEW:\n const isScaledOrder = client_order_id?.startsWith(\"scaled_\");\n // if client_order_id is scaled order, show the scaled order message\n if (isScaledOrder) {\n title = i18n.t(\"orders.status.scaledSubOrderOpened.toast.title\");\n msg = `${displaySide} ${displaySymbol} ${displayQuantity}`;\n } else {\n title = i18n.t(\"orders.status.opened.toast.title\");\n msg = `${displaySide} ${displaySymbol} ${displayQuantity}`;\n }\n\n break;\n case OrderStatus.FILLED:\n case OrderStatus.PARTIAL_FILLED:\n const displayTotalExecutedQuantity =\n base_dp === undefined\n ? total_executed_quantity\n : parseNumber(total_executed_quantity, { dp: base_dp });\n title = i18n.t(\"orders.status.filled.toast.title\");\n msg = `${displaySide} ${displaySymbol} ${displayTotalExecutedQuantity} / ${displayQuantity}`;\n break;\n case OrderStatus.CANCELLED:\n title = i18n.t(\"orders.status.canceled.toast.title\");\n msg = `${displaySide} ${displaySymbol} ${displayQuantity}`;\n break;\n case OrderStatus.REJECTED:\n title = i18n.t(\"orders.status.rejected.toast.title\");\n msg = `${displaySide} ${displaySymbol} ${displayQuantity}`;\n break;\n case OrderStatus.REPLACED:\n const { algo_type, activated_price } = data as API.AlgoOrder;\n if (algo_type === AlgoOrderRootType.TRAILING_STOP) {\n const fieldChange =\n fieldChanges?.[AlgoOrderRootType.TRAILING_STOP] || {};\n // when trailing stop order is activated, and extreme_price will also changed\n if (\n fieldChange.is_activated &&\n fieldChange.extreme_price &&\n activated_price\n ) {\n title = i18n.t(\"orders.trailingStop.activated\");\n msg = `${displaySymbol} @${activated_price}`;\n } else if (fieldChange.extreme_price) {\n // if extreme_price is changed, skip show the message\n title = \"\";\n msg = \"\";\n }\n } else {\n title = i18n.t(\"orders.status.replaced.toast.title\");\n msg = `${side} ${displaySymbol} ${total_executed_quantity} / ${displayQuantity}`;\n }\n\n break;\n default:\n break;\n }\n\n return {\n title,\n msg,\n status,\n };\n}\n","import { useMemo } from \"react\";\nimport {\n useTranslation,\n useLocaleCode,\n LocaleEnum,\n} from \"@kodiak-finance/orderly-i18n\";\nimport { Locale } from \"@kodiak-finance/orderly-ui\";\nimport { enUS, zhCN, ja, es, ko, vi, de, fr, nl } from \"date-fns/locale\";\n\nexport function useUILocale() {\n const { t } = useTranslation();\n const localeCode = useLocaleCode();\n\n return useMemo<Locale>(() => {\n const calendarLocale = {\n [LocaleEnum.en]: enUS,\n [LocaleEnum.zh]: zhCN,\n // [LocaleEnum.ja]: ja,\n // [LocaleEnum.es]: es,\n // [LocaleEnum.ko]: ko,\n // [LocaleEnum.vi]: vi,\n // [LocaleEnum.de]: de,\n // [LocaleEnum.fr]: fr,\n // [LocaleEnum.nl]: nl,\n };\n return {\n locale: localeCode,\n dialog: {\n ok: t(\"common.ok\"),\n cancel: t(\"common.cancel\"),\n },\n modal: {\n confirm: t(\"common.confirm\"),\n cancel: t(\"common.cancel\"),\n },\n pagination: {\n morePages: t(\"ui.pagination.morePages\"),\n rowsPerPage: t(\"ui.pagination.rowsPerPage\"),\n },\n picker: {\n selectDate: t(\"ui.picker.selectDate\"),\n dayPicker: calendarLocale[localeCode as keyof typeof calendarLocale],\n },\n empty: {\n description: t(\"ui.empty.description\"),\n },\n } as const;\n }, [t, localeCode]);\n}\n","import { createContext, useContext } from \"react\";\nimport { AppLogos } from \"../types\";\n\nexport type ThemeContextState = {\n appIcons?: AppLogos;\n brokerName: string;\n};\n\nexport const AppConfigContext = createContext({} as ThemeContextState);\n\nexport const useAppConfig = () => {\n return useContext(AppConfigContext);\n};\n","import { FC, PropsWithChildren } from \"react\";\nimport { AppLogos } from \"../types\";\nimport { AppConfigContext } from \"./appConfigContext\";\n\nexport type ThemeContextState = {\n appIcons?: AppLogos;\n brokerName: string;\n};\n\nexport const AppConfigProvider: FC<\n PropsWithChildren<{ appIcons?: AppLogos; brokerName: string }>\n> = (props) => {\n return (\n <AppConfigContext.Provider value={props}>\n {props.children}\n </AppConfigContext.Provider>\n );\n};\n","import { FC, PropsWithChildren, useState, useMemo } from \"react\";\nimport {\n RestrictedInfoOptions,\n useRestrictedInfo,\n useTrackingInstance,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { useAssetconvertEvent } from \"../hooks/useAssetconvertEvent\";\nimport { DefaultChain, useCurrentChainId } from \"../hooks/useCurrentChainId\";\nimport { useLinkDevice } from \"../hooks/useLinkDevice\";\nimport { useSettleEvent } from \"../hooks/useSettleEvent\";\nimport { useWalletConnectError } from \"../hooks/useWalletConnectError\";\nimport { useWalletEvent } from \"../hooks/useWalletEvent\";\nimport { useWalletStateHandle } from \"../hooks/useWalletStateHandle\";\nimport { AppContextState, AppStateContext } from \"./appStateContext\";\n\nexport type RouteOption = {\n href: \"/portfolio\" | \"/portfolio/history\";\n name: string;\n};\n\nexport type AppStateProviderProps = {\n defaultChain?: DefaultChain;\n restrictedInfo?: RestrictedInfoOptions;\n} & Pick<AppContextState, \"onChainChanged\" | \"onRouteChange\" | \"widgetConfigs\">;\n\nexport const AppStateProvider: FC<PropsWithChildren<AppStateProviderProps>> = (\n props,\n) => {\n const [showAnnouncement, setShowAnnouncement] = useState(false);\n const [currentChainId, setCurrentChainId] = useCurrentChainId(\n props.defaultChain,\n );\n useLinkDevice();\n useTrackingInstance();\n\n const { connectWallet, wrongNetwork } = useWalletStateHandle({\n // onChainChanged: props.onChainChanged,\n currentChainId,\n });\n\n useWalletEvent();\n useSettleEvent();\n useAssetconvertEvent();\n useWalletConnectError();\n\n const restrictedInfo = useRestrictedInfo(props.restrictedInfo);\n\n const disabledConnect = restrictedInfo.restrictedOpen;\n\n const memoizedValue = useMemo<AppContextState>(\n () => ({\n connectWallet,\n wrongNetwork,\n currentChainId,\n setCurrentChainId,\n onChainChanged: props.onChainChanged,\n disabledConnect,\n restrictedInfo,\n showAnnouncement,\n setShowAnnouncement,\n onRouteChange: props.onRouteChange,\n widgetConfigs: props.widgetConfigs,\n }),\n [\n connectWallet,\n currentChainId,\n disabledConnect,\n props.onChainChanged,\n restrictedInfo,\n setCurrentChainId,\n showAnnouncement,\n wrongNetwork,\n props.onRouteChange,\n props.widgetConfigs,\n ],\n );\n\n return (\n <AppStateContext.Provider value={memoizedValue}>\n {props.children}\n </AppStateContext.Provider>\n );\n};\n","import { useEffect } from \"react\";\nimport { useWS } from \"@kodiak-finance/orderly-hooks\";\nimport { useTranslation } from \"@kodiak-finance/orderly-i18n\";\nimport { toast } from \"@kodiak-finance/orderly-ui\";\nimport { getTimestamp } from \"@kodiak-finance/orderly-utils\";\n\nexport const useAssetconvertEvent = () => {\n const ws = useWS();\n const { t } = useTranslation();\n useEffect(() => {\n const unsubscribe = ws.privateSubscribe(\n {\n id: \"assetconvert\",\n event: \"subscribe\",\n topic: \"assetconvert\",\n ts: getTimestamp(),\n },\n {\n onMessage(data) {\n if (data.convertId) {\n toast.success(t(\"transfer.convert.completed\"));\n }\n },\n },\n );\n return () => unsubscribe();\n }, []);\n};\n","import { useEffect, useState } from \"react\";\nimport {\n Chains,\n useChains,\n useConfig,\n useStorageChain,\n useWalletConnector,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { Chain, NetworkId } from \"@kodiak-finance/orderly-types\";\ntype ReturnChain = Pick<Chain, \"id\"> & Partial<Omit<Chain, \"id\">>;\n\nexport type DefaultChain =\n | {\n mainnet?: ReturnChain;\n testnet?: ReturnChain;\n }\n | ((networkId: NetworkId, chains: Chains) => ReturnChain)\n | undefined;\n\nexport function useCurrentChainId(defaultChain?: DefaultChain) {\n const { storageChain, setStorageChain } = useStorageChain();\n const [currentChainId, setCurrentChainId] = useState<number | undefined>();\n\n const [chains] = useChains();\n const networkId = useConfig(\"networkId\") as NetworkId;\n\n const { connectedChain } = useWalletConnector();\n\n useEffect(() => {\n if (connectedChain) {\n setCurrentChainId?.(\n typeof connectedChain.id === \"number\"\n ? connectedChain.id\n : parseInt(connectedChain.id)\n );\n } else {\n if (!!currentChainId) return;\n let fallbackChain: Partial<Chain> | undefined;\n\n const firstChain =\n networkId === \"mainnet\" ? chains.mainnet?.[0] : chains.testnet?.[0];\n\n if (typeof defaultChain === \"function\") {\n fallbackChain = defaultChain(networkId, chains);\n } else if (typeof defaultChain === \"object\") {\n fallbackChain =\n networkId === \"mainnet\"\n ? defaultChain?.mainnet\n : defaultChain?.testnet;\n }\n\n const chainId = fallbackChain?.id || firstChain?.network_infos?.chain_id;\n if (!chainId) return;\n\n if (storageChain) {\n setCurrentChainId?.(storageChain.chainId);\n } else {\n setStorageChain(chainId);\n setCurrentChainId?.(chainId);\n \n }\n }\n }, [\n connectedChain,\n chains,\n currentChainId,\n networkId,\n setCurrentChainId,\n defaultChain,\n ]);\n\n return [currentChainId, setCurrentChainId] as const;\n}\n","import { useCallback, useEffect } from \"react\";\nimport {\n parseJSON,\n useAccount,\n useConfig,\n useLocalStorage,\n useWalletConnector,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { ChainNamespace } from \"@kodiak-finance/orderly-types\";\nimport { useScreen } from \"@kodiak-finance/orderly-ui\";\n\ntype DecodedData = {\n /** secret key */\n k: string;\n /* timestamp */\n t: number;\n /** address */\n a: string;\n /** chain id */\n i: number;\n /** chain namespace */\n n: ChainNamespace;\n};\n\ntype LinkDeviceStorage = { chainId: number; chainNamespace: ChainNamespace };\n\nconst WALLET_KEY = \"orderly:wallet-info\";\n\nexport function useLinkDevice() {\n const { connectedChain, disconnect } = useWalletConnector();\n const [_, setLinkDeviceStorage] = useLocalStorage(\n \"orderly_link_device\",\n {} as LinkDeviceStorage,\n );\n\n const { account } = useAccount();\n const { isMobile } = useScreen();\n const configStore = useConfig();\n\n const onDisconnect = async (label: string) => {\n // The cache must be cleared first, otherwise it will be auto connect wallet\n localStorage.removeItem(WALLET_KEY);\n await account.disconnect();\n await disconnect({ label });\n };\n\n useEffect(() => {\n const linkData = getLinkDeviceData();\n const walletInfo = JSON.parse(localStorage.getItem(WALLET_KEY) ?? \"{}\");\n if (linkData && walletInfo) {\n // clear connect data when link device\n onDisconnect(walletInfo.label);\n }\n }, []);\n\n const linkDevice = async () => {\n const linkData = getLinkDeviceData();\n if (!linkData) return;\n\n const { address, secretKey, chainId, chainNamespace } = linkData;\n const isSuccess = await account.importOrderlyKey({\n address,\n secretKey,\n chainNamespace,\n });\n if (!isSuccess) return;\n setLinkDeviceStorage({\n chainId,\n chainNamespace,\n });\n\n const url = new URL(window.location.href);\n url.searchParams.delete(\"link\");\n // use set instead of append, because the param possibly in the url\n url.searchParams.set(\"utm_medium\", \"qrcode\");\n const decodedUrl = decodeURIComponent(url.toString());\n history.replaceState(null, \"\", decodedUrl);\n };\n\n useEffect(() => {\n if (isMobile && !connectedChain) {\n linkDevice();\n }\n }, [account, connectedChain, isMobile]);\n\n const autoLinkDevice = async () => {\n // this can't use the value returned by useLocalStorage here, because it will trigger extra state change\n const { chainId, chainNamespace } = getLinkDeviceStorage() || {};\n if (isMobile && !connectedChain && chainId && chainNamespace) {\n const address = account.keyStore.getAddress();\n const orderlyKey = account.keyStore.getOrderlyKey();\n const accountId = account.keyStore.getAccountId(address!);\n const res = await account.checkOrderlyKey(\n address!,\n orderlyKey!,\n accountId!,\n );\n if (res) {\n configStore.set(\"chainNamespace\", chainNamespace);\n }\n }\n };\n\n // persist status when refresh page\n useEffect(() => {\n autoLinkDevice();\n }, [account, isMobile, connectedChain]);\n\n return { linkDevice };\n}\n\nfunction getLinkDeviceStorage() {\n try {\n const linkDeviceStorage = localStorage.getItem(\"orderly_link_device\");\n const json = linkDeviceStorage ? parseJSON(linkDeviceStorage) : null;\n return json as LinkDeviceStorage;\n } catch (err) {\n console.error(\"getLinkDeviceStorage\", err);\n }\n}\n\nexport function getLinkDeviceData() {\n const url = new URL(window.location.href);\n const link = url.searchParams.get(\"link\");\n\n if (!link) return;\n\n const {\n a: address,\n k: secretKey,\n i: chainId,\n n: chainNamespace,\n } = decodeBase64(link) || {};\n\n if (address && secretKey && chainId && chainNamespace) {\n return {\n address,\n secretKey,\n chainId,\n chainNamespace,\n };\n }\n}\n\nfunction decodeBase64(base64: string) {\n try {\n const data = JSON.parse(window.atob(base64)) as DecodedData;\n console.log(\"decodeBase64\", data);\n const currentTime = Math.floor(Date.now() / 1000);\n const expiredTime = data.t;\n\n if (!expiredTime || currentTime > expiredTime) {\n console.error(\"Orderly key has expired.\");\n return;\n }\n\n return data;\n } catch (error) {\n console.error(\"Invalid or expired orderly key.\");\n }\n}\n","import { useSettleSubscription } from \"@kodiak-finance/orderly-hooks\";\nimport { toast } from \"@kodiak-finance/orderly-ui\";\nimport { useTranslation } from \"@kodiak-finance/orderly-i18n\";\n\nexport function useSettleEvent() {\n const { t } = useTranslation();\n\n useSettleSubscription({\n onMessage: (data: any) => {\n const { status } = data;\n\n // console.log(\"settle ws: \", data);\n\n switch (status) {\n case \"COMPLETED\":\n toast.success(t(\"settle.settlement.completed\"));\n break;\n case \"FAILED\":\n toast.error(t(\"settle.settlement.failed\"));\n break;\n default:\n break;\n }\n },\n });\n}\n","import { useEventEmitter } from \"@kodiak-finance/orderly-hooks\";\nimport { useEffect } from \"react\";\nimport { modal, toast } from \"@kodiak-finance/orderly-ui\";\nimport { LedgerWalletKey } from \"@kodiak-finance/orderly-types\";\nimport { useStorageLedgerAddress } from \"@kodiak-finance/orderly-hooks\";\nimport { useTranslation } from \"@kodiak-finance/orderly-i18n\";\n\nexport function useWalletConnectError() {\n const { t } = useTranslation();\n const ee = useEventEmitter();\n const { setLedgerAddress } = useStorageLedgerAddress();\n\n useEffect(() => {\n ee.on(\"wallet:connect-error\", (data) => {\n toast.error(data.message);\n });\n ee.on(\n \"wallet:sign-message-with-ledger-error\",\n (data: { userAddress: string; message: string }) => {\n window.setTimeout(() => {\n modal\n .confirm({\n title: t(\"connector.ledger.signMessageFailed\"),\n content: t(\"connector.ledger.signMessageFailed.description\"),\n size: \"sm\",\n onOk: async () => {\n console.log(\"-- use ledger\", true);\n setLedgerAddress(data.userAddress);\n\n return Promise.resolve();\n },\n okLabel: t(\"common.ok\"),\n onCancel: async () => {\n toast.error(data.message);\n return Promise.resolve();\n },\n cancelLabel: t(\"common.no\"),\n })\n .then((res) => {\n console.log(\"-- dialog res\", res);\n });\n });\n }\n );\n }, [ee, t]);\n\n return {};\n}\n","import { useRef } from \"react\";\nimport {\n useEventEmitter,\n useSessionStorage,\n useWalletSubscription,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { useTranslation } from \"@kodiak-finance/orderly-i18n\";\nimport { toast } from \"@kodiak-finance/orderly-ui\";\nimport { capitalizeString } from \"@kodiak-finance/orderly-utils\";\n\nexport function useWalletEvent() {\n const { t } = useTranslation();\n const ee = useEventEmitter();\n\n const recordRef = useRef<Record<number, boolean>>({});\n\n const [record, setRecord] = useSessionStorage(\n \"orderly_wallet_change_id\",\n {} as Record<number, boolean>,\n );\n\n recordRef.current = record;\n\n useWalletSubscription({\n onMessage: (data: any) => {\n console.log(\"wallet:changed\", data);\n const { id, side, transStatus } = data;\n let showToast = true;\n\n // DEPOSIT and WITHDRAW will push twice COMPLETED and FAILED event\n if (\n [\"DEPOSIT\", \"WITHDRAW\"].includes(side) &&\n [\"COMPLETED\", \"FAILED\"].includes(transStatus)\n ) {\n const isPushed = !!recordRef.current[id];\n if (!isPushed) {\n recordRef.current[id] = true;\n setRecord((prev: Record<number, boolean>) => ({\n ...prev,\n [id]: true,\n }));\n }\n showToast = !isPushed;\n }\n\n if (transStatus === \"COMPLETED\" && showToast) {\n let msg = `${capitalizeString(side)} completed`;\n\n if (side === \"DEPOSIT\") {\n msg = t(\"transfer.deposit.completed\");\n } else if (side === \"WITHDRAW\") {\n msg = t(\"transfer.withdraw.completed\");\n }\n\n toast.success(msg);\n } else if (transStatus === \"FAILED\" && showToast) {\n let msg = `${capitalizeString(side)} failed`;\n\n if (side === \"DEPOSIT\") {\n msg = t(\"transfer.deposit.failed\");\n } else if (side === \"WITHDRAW\") {\n msg = t(\"transfer.withdraw.failed\");\n }\n toast.error(msg);\n }\n\n ee.emit(\"wallet:changed\", data);\n },\n });\n}\n","import { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n useConfig,\n useEventEmitter,\n useTrack,\n WalletState,\n} from \"@kodiak-finance/orderly-hooks\";\nimport {\n useAccount,\n useChains,\n useKeyStore,\n useWalletConnector,\n} from \"@kodiak-finance/orderly-hooks\";\nimport {\n AccountStatusEnum,\n SDKError,\n ChainNamespace,\n NetworkId,\n TrackerEventName,\n ABSTRACT_CHAIN_ID_MAP,\n} from \"@kodiak-finance/orderly-types\";\nimport {\n parseChainIdToNumber,\n praseChainIdToNumber,\n windowGuard,\n} from \"@kodiak-finance/orderly-utils\";\nimport { getLinkDeviceData } from \"./useLinkDevice\";\n\nconst WALLET_KEY = \"orderly:wallet-info\";\nconst CHAIN_NAMESPACE = \"orderly:chain-namespace\";\n\nexport const useWalletStateHandle = (options: {\n // onChainChanged?: (chainId: number, isTestnet: boolean) => void;\n currentChainId?: number;\n}) => {\n const {\n wallet: connectedWallet,\n connect,\n connectedChain,\n disconnect,\n namespace,\n } = useWalletConnector();\n //\n // console.log(\"🔗 wallet state handle\", {\n // connectedWallet,\n // connectedChain,\n // namespace,\n // });\n\n if (typeof connect !== \"function\") {\n throw new SDKError(\"Please provide a wallet connector provider\");\n }\n\n const ee = useEventEmitter();\n const isManualConnect = useRef<boolean>(false);\n const brokerId = useConfig(\"brokerId\");\n const { account, state: accountState } = useAccount();\n const keyStore = useKeyStore();\n const networkId = useConfig(\"networkId\") as NetworkId;\n const [chains, { checkChainSupport }] = useChains();\n\n const [unsupported, setUnsupported] = useState(false);\n const { track, setTrackUserId } = useTrack();\n\n // current connected wallet address\n const currentWalletAddress = useMemo<string | undefined>(() => {\n return connectedWallet?.accounts?.[0]?.address;\n }, [connectedWallet]);\n\n // current connected chain id\n const currentChain = useMemo<\n { id: number; namespace: string } | undefined\n >(() => {\n const id = connectedWallet?.chains?.[0]?.id;\n const namespace = connectedWallet?.chains?.[0]?.namespace as string;\n if (typeof id === \"undefined\") return undefined;\n return {\n id: parseChainIdToNumber(id),\n namespace,\n };\n }, [connectedWallet]);\n\n useEffect(() => {\n if (\n accountState.status >= AccountStatusEnum.EnableTrading &&\n account.accountId\n ) {\n setTrackUserId(account.accountId!);\n }\n }, [account, accountState]);\n\n useEffect(() => {\n if (!connectedChain) {\n setUnsupported(false);\n return;\n }\n\n let isSupported = checkChainSupport(\n connectedChain.id,\n networkId,\n // networkId === \"testnet\" ? chains.testnet : chains.mainnet\n );\n if (\n ABSTRACT_CHAIN_ID_MAP.has(parseInt(connectedChain.id as string)) &&\n connectedWallet?.label !== \"AGW\"\n ) {\n isSupported = false;\n }\n\n setUnsupported(!isSupported);\n }, [connectedChain, chains, checkChainSupport, networkId, connectedWallet]);\n\n useEffect(() => {\n // if (unsupported) return;\n\n windowGuard(() => {\n const localAddress = keyStore.getAddress();\n const walletInfo = JSON.parse(localStorage.getItem(WALLET_KEY) ?? \"{}\");\n\n /**\n * if locale address is exist, restore account state\n */\n if (connectedChain?.namespace === ChainNamespace.solana) {\n return;\n }\n if (\n localAddress &&\n account.address !== localAddress &&\n walletInfo.label\n ) {\n connect({\n autoSelect: {\n label: walletInfo.label,\n disableModals: true,\n },\n }).then(\n (res) => {\n console.log(\"silent connect wallet successes\", res);\n },\n (error) => console.log(\"connect error\", error),\n );\n }\n });\n }, [connectedWallet, account.address]);\n\n /**\n * handle wallet connection\n */\n useEffect(() => {\n if (\n connectedWallet === null &&\n accountState.status > AccountStatusEnum.NotConnected &&\n !accountState.validating\n ) {\n account.disconnect();\n return;\n }\n\n if (unsupported || !connectedChain) return;\n if (isManualConnect.current) return;\n\n const linkData = getLinkDeviceData();\n\n // updateAccount(currentWalletAddress!, connectedWallet!, currentChainId!);\n /**\n * switch account\n */\n if (\n !!currentWalletAddress &&\n currentWalletAddress !== account.address &&\n !linkData\n ) {\n account.setAddress(currentWalletAddress, {\n provider: connectedWallet?.provider,\n chain: {\n id: praseChainIdToNumber(currentChain!.id),\n namespace: currentChain!.namespace.toUpperCase() as ChainNamespace,\n },\n wallet: {\n name: connectedWallet?.label ?? \"\",\n },\n additionalInfo: connectedWallet?.additionalInfo ?? {},\n });\n track(TrackerEventName.walletConnect, {\n wallet: connectedWallet?.label ?? \"\",\n network: currentChain!.namespace.toUpperCase() as ChainNamespace,\n });\n\n // save wallet connector info to local storage\n windowGuard(() => {\n localStorage.setItem(\n WALLET_KEY,\n JSON.stringify({\n label: connectedWallet?.label ?? \"\",\n }),\n );\n });\n }\n\n /**\n * switch chainId\n */\n if (currentChain?.id !== account.chainId) {\n account.switchChainId(currentChain?.id!);\n\n // emit chain changed event\n // options.onChainChanged?.(currentChainId!, isTestnet(networkId));\n }\n }, [\n connectedWallet,\n connectedChain,\n currentWalletAddress,\n currentChain,\n account.address,\n accountState,\n account.chainId,\n unsupported,\n ]);\n\n /**\n * User manually connects to wallet\n */\n const connectWallet = async (): Promise<{\n wallet?: WalletState;\n status?: AccountStatusEnum;\n wrongNetwork?: boolean;\n } | null> => {\n isManualConnect.current = true;\n // const walletState = await connect();\n\n return connect({ chainId: options.currentChainId })\n .then(async (walletState) => {\n if (\n Array.isArray(walletState) &&\n walletState.length > 0 &&\n walletState[0] &&\n walletState[0].accounts.length > 0\n ) {\n const wallet = walletState[0];\n const chainId = praseChainIdToNumber(wallet.chains[0].id);\n\n if (!checkChainSupport(chainId, networkId)) {\n return {\n wrongNetwork: true,\n };\n }\n //\n if (!account) {\n throw new Error(\"account is not initialized\");\n }\n // clear link device data when connect wallt\n if (\n accountState.status ===\n AccountStatusEnum.EnableTradingWithoutConnected\n ) {\n localStorage.removeItem(\"orderly_link_device\");\n await account.disconnect();\n }\n\n const status = await account.setAddress(wallet.accounts[0].address, {\n provider: wallet.provider,\n chain: {\n id: praseChainIdToNumber(wallet.chains[0].id),\n namespace:\n wallet.chains[0].namespace.toUpperCase() as ChainNamespace,\n },\n wallet: {\n name: wallet.label,\n },\n // label: ,\n });\n track(TrackerEventName.walletConnect, {\n wallet: wallet.label,\n network: wallet.chains[0].namespace.toUpperCase() as ChainNamespace,\n });\n console.log(\"-- xxxxxx status\", status);\n\n return { wallet, status, wrongNetwork: false };\n }\n\n return null;\n })\n .finally(() => {\n isManualConnect.current = false;\n });\n };\n\n return {\n connectWallet,\n wrongNetwork: unsupported,\n };\n};\n","import React, { createContext, useContext } from \"react\";\nimport { RestrictedInfoReturns } from \"@kodiak-finance/orderly-hooks\";\nimport { useWalletStateHandle } from \"../hooks/useWalletStateHandle\";\n\nexport type RouteOption = {\n href: \"/portfolio\" | \"/portfolio/history\";\n name: string;\n};\n\nexport type WidgetConfigs = {\n scanQRCode?: {\n onSuccess?: (url: string) => void;\n };\n};\n\nexport type AppContextState = {\n connectWallet: ReturnType<typeof useWalletStateHandle>[\"connectWallet\"];\n /**\n * Whether the current network is not supported\n */\n wrongNetwork: boolean;\n disabledConnect: boolean;\n currentChainId: number | undefined;\n setCurrentChainId: (chainId: number | undefined) => void;\n onChainChanged?: (\n chainId: number,\n state: { isTestnet: boolean; isWalletConnected: boolean },\n ) => void;\n // networkStatus: ReturnType<typeof useAppState>[\"networkStatus\"];\n restrictedInfo: RestrictedInfoReturns;\n showAnnouncement: boolean;\n setShowAnnouncement: (show: boolean) => void;\n onRouteChange?: (option: RouteOption) => void;\n widgetConfigs?: WidgetConfigs;\n};\n\nexport const AppStateContext = createContext<AppContextState>({\n setCurrentChainId: (chainId?: number) => {},\n restrictedInfo: {},\n setShowAnnouncement: (show: boolean) => {},\n} as AppContextState);\n\nexport const useAppContext = () => {\n return useContext(AppStateContext);\n};\n","import { useAccount } from \"@kodiak-finance/orderly-hooks\";\nimport { AccountStatusEnum } from \"@kodiak-finance/orderly-types\";\nimport { useAppContext } from \"../provider/appStateContext\";\n\nexport const useDataTap = <T = any>(\n data: T,\n options?: {\n skip?: false;\n fallbackData?: T;\n accountStatus?: AccountStatusEnum;\n },\n): T | null => {\n const { wrongNetwork, disabledConnect } = useAppContext();\n const { state } = useAccount();\n /**\n * ignore\n */\n if (options?.skip) {\n return data;\n }\n\n if (wrongNetwork || disabledConnect) {\n return typeof options?.fallbackData !== \"undefined\"\n ? options.fallbackData\n : null;\n }\n\n if (typeof options?.accountStatus !== \"undefined\") {\n if (state.status < options.accountStatus) {\n return typeof options?.fallbackData !== \"undefined\"\n ? options.fallbackData\n : null;\n }\n }\n\n // return wrongNetwork\n // ? typeof options?.fallbackData !== \"undefined\"\n // ? options.fallbackData\n // : null\n // : data;\n //\n return data;\n};\n","import { useCallback } from \"react\";\nimport {\n OrderValidationItem,\n OrderValidationResult,\n} from \"@kodiak-finance/orderly-hooks\";\nimport { useTranslation } from \"@kodiak-finance/orderly-i18n\";\n\ntype Keys = keyof OrderValidationResult;\ntype ErrorType = Partial<OrderValidationItem[\"type\"]>;\n\nexport function useOrderEntryFormErrorMsg(\n errors: OrderValidationResult | null,\n) {\n const { t } = useTranslation();\n\n const getMessage = (\n key: Keys,\n type: ErrorType,\n params: {\n value?: string | number;\n min?: string | number;\n max?: string | number;\n },\n ) => {\n const { value, min, max } = params || {};\n const map: Partial<Record<Keys, Partial<Record<ErrorType, string>>>> = {\n quantity: {\n required: t(\"orderEntry.orderQuantity.error.required\"),\n min: t(\"orderEntry.orderQuantity.error.min\", { value }),\n max: t(\"orderEntry.orderQuantity.error.max\", { value }),\n },\n order_quantity: {\n required: t(\"orderEntry.orderQuantity.error.required\"),\n min: t(\"orderEntry.orderQuantity.error.min\", { value }),\n max: t(\"orderEntry.orderQuantity.error.max\", { value }),\n },\n order_price: {\n required: t(\"orderEntry.orderPrice.error.required\"),\n min: t(\"orderEntry.orderPrice.error.min\", { value }),\n max: t(\"orderEntry.orderPrice.error.max\", { value }),\n },\n trigger_price: {\n required: t(\"orderEntry.triggerPrice.error.required\"),\n min: t(\"orderEntry.triggerPrice.error.min\", { value }),\n max: t(\"orderEntry.triggerPrice.error.max\", { value }),\n },\n tp_trigger_price: {\n required: t(\"tpsl.validate.tpTriggerPrice.error.required\"),\n min: t(\"orderEntry.tpTriggerPrice.error.min\", { value }),\n max: t(\"orderEntry.tpTriggerPrice.error.max\", { value }),\n priceErrorMin: t(\"tpsl.validate.tpTriggerPrice.error.priceErrorMin\"),\n priceErrorMax: t(\"tpsl.validate.tpTriggerPrice.error.priceErrorMax\"),\n },\n sl_trigger_price: {\n required: t(\"tpsl.validate.slTriggerPrice.error.required\"),\n min: t(\"orderEntry.slTriggerPrice.error.min\", { value }),\n max: t(\"orderEntry.slTriggerPrice.error.max\", { value }),\n priceErrorMin: t(\"tpsl.validate.slTriggerPrice.error.priceErrorMin\"),\n priceErrorMax: t(\"tpsl.validate.slTriggerPrice.error.priceErrorMax\"),\n },\n tp_order_price: {\n required: t(\"tpsl.validate.tpOrderPrice.error.required\"),\n min: t(\"tpsl.validate.tpOrderPrice.error.min\", { value }),\n max: t(\"tpsl.validate.tpOrderPrice.error.max\", { value }),\n },\n sl_order_price: {\n required: t(\"tpsl.validate.slOrderPrice.error.required\"),\n min: t(\"tpsl.validate.slOrderPrice.error.min\", { value }),\n max: t(\"tpsl.validate.slOrderPrice.error.max\", { value }),\n },\n total: {\n min: t(\"orderEntry.total.error.min\", { value }),\n },\n // not show form input tooltip\n // slippage: {\n // max: t(\"orderEntry.slippage.error.max\"),\n // },\n start_price: {\n required: t(\"orderEntry.startPrice.error.required\"),\n min: t(\"orderEntry.startPrice.error.min\", { value }),\n max: t(\"orderEntry.startPrice.error.max\", { value }),\n },\n end_price: {\n required: t(\"orderEntry.endPrice.error.required\"),\n min: t(\"orderEntry.endPrice.error.min\", { value }),\n max: t(\"orderEntry.endPrice.error.max\", { value }),\n },\n total_orders: {\n required: t(\"orderEntry.totalOrders.error.required\"),\n range: t(\"orderEntry.totalOrders.error.range\"),\n },\n skew: {\n required: t(\"orderEntry.skew.error.required\"),\n min: t(\"orderEntry.skew.error.min\", { value }),\n max: t(\"orderEntry.skew.error.max\", { value }),\n },\n activated_price: {\n min: t(\"orderEntry.triggerPrice.error.min\", { value }),\n max: t(\"orderEntry.triggerPrice.error.max\", { value }),\n },\n callback_value: {\n required: t(\"orderEntry.callbackValue.error.required\"),\n min: t(\"orderEntry.callbackValue.error.min\", { value }),\n range: t(\"orderEntry.callbackValue.error.range\", {\n min,\n max,\n }),\n },\n callback_rate: {\n required: t(\"orderEntry.callbackRate.error.required\"),\n range: t(\"orderEntry.callbackRate.error.range\", {\n min,\n max,\n }),\n },\n };\n\n return map[key]?.[type] || \"\";\n };\n\n const getErrorMsg = useCallback(\n (key: Keys, customValue?: string) => {\n const { type, value, min, max } = errors?.[key] || ({} as any);\n if (type) {\n return getMessage(key, type, { value: customValue || value, min, max });\n }\n return \"\";\n },\n [errors],\n );\n\n return {\n getErrorMsg,\n };\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@kodiak-finance/orderly-react-app",
|
|
3
|
+
"version": "2.7.4",
|
|
4
|
+
"description": "Create React App with Orderly Network components",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.mjs",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"Orderly",
|
|
9
|
+
"Exchange",
|
|
10
|
+
"React",
|
|
11
|
+
"DApp"
|
|
12
|
+
],
|
|
13
|
+
"files": [
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"publishConfig": {
|
|
17
|
+
"access": "public"
|
|
18
|
+
},
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"date-fns": "^3.6.0",
|
|
21
|
+
"@kodiak-finance/orderly-hooks": "2.7.4",
|
|
22
|
+
"@kodiak-finance/orderly-i18n": "2.7.4",
|
|
23
|
+
"@kodiak-finance/orderly-ui": "2.7.4",
|
|
24
|
+
"@kodiak-finance/orderly-utils": "2.7.4",
|
|
25
|
+
"@kodiak-finance/orderly-types": "2.7.4"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/react": "^18.3.2",
|
|
29
|
+
"@types/react-dom": "^18.3.0",
|
|
30
|
+
"react": "^18.2.0",
|
|
31
|
+
"react-dom": "^18.2.0",
|
|
32
|
+
"tailwindcss": "^3.4.4",
|
|
33
|
+
"tsup": "^7.3.0",
|
|
34
|
+
"tsconfig": "0.10.4"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"react": ">=18",
|
|
38
|
+
"react-dom": ">=18"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "tsup",
|
|
42
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
43
|
+
}
|
|
44
|
+
}
|